Search code examples
c++gtkmmmodulargtkmm3

How to write modular code in c++ with gtkmm?


How to write modular code in gtkmm3 I want to create objects in a window that I have using the different classes I created (inherited from Gtk::Grid) and put them in the mainGrid window

I do this but it shows me nothing

class MainWindow:public Gtk::Window{
    public:
        MainWindow();
    private:
        Gtk::Grid mainGrid;
};
class FirstGrid:public Gtk::Grid{
    public:
        FirstGrid();
        Gtk::Grid getGrid();
    private:
        Gtk::Grid mainGrid;
        Gtk::Button button{"button"};
};
FirstGrid::FirstGrid(){
    mainGrid.attach(button,1,1);
}
FirstGrid::getGrid(){
    return std::move(mainGrid);
}
MainWindow::MainWindow(){
    set_size_request(500,500);
    add(mainGrid);
    FirstGrid firstGrid;
    mainGrid = firstGrid.getGrid();
    show_all();
}

Solution

  • The problem here seems to be that you are not using inheritance and polymorphism, even though you made it clear in your classes that they are indeed inheriting.

    Here is a working example:

    #include <gtkmm.h>
    
    class FirstGrid : public Gtk::Grid
    {
    
    public:
    
        FirstGrid()
        {
            // Since FirstGrid is a Gtk::Grid, the `attach` method is
            // inherited, you can use it directly:
            attach(button, 0, 0, 1, 1);
        }
    
    private:
    
        // No need for an extra Gtk::Grid here.
        Gtk::Button button{"button"};
    }; 
    
    class MainWindow : public Gtk::Window
    {
    
    public:
    
        MainWindow()
        {
            set_size_request(500, 500);
    
            // Use FirstGrid as a Gtk::Grid here:
            add(mainGrid);
            show_all();
        }
    
    private:
    
        FirstGrid mainGrid;
    };
    
    int main(int argc, char *argv[])
    {
        auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
      
        MainWindow window;
        window.set_default_size(200, 200);
      
        return app->run(window);
    }
    

    which you ca build with:

    g++ main.cpp -o example.out `pkg-config --cflags --libs gtkmm-3.0`
    

    assuming you copy it in a file named main.cpp.