Search code examples
c++gtkmmgtkmm3

Initialize a Gtk::Window derived class with a Gtk::Builder


I have a Glade layout compiled into a gresource that I'm setting to a Gtk::Window object manually in my constructor. A simplified version of the code I'm using now would be:


MyClass::MyClass()
{
    Gtk::Window *window;
    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_resource("/layouts/mywindow.glade");
    builder->get_widget("myWindow", window);
    window->show();
}

*Note: this is not my actual code, it's just a very simplified version of what I'm doing.

I'd like use Gtk::Window as a base class and just "run" my class like:

#include "myclass.h"

int main(int argc, char *argv[])
{
    Gtk::Main kit(argc, argv);

    MyClass helloworld;

    kit.run(loginScreen);

    return 0;
}

But I can't seem to figure out how to use the builder to insert/assign the layout to the Gtk::Window base class. I'm fairly certain I need to use get_widget_derived but I can't seem to figure out how to use it within the constructor (...or can you not use it in a consructor?). For example, altering my class definition to:

class MyClass : public Gtk::Window
{
public:
    MyClass(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder);
}

what should I put in my constructor to put the layout from the builder into the base Gtk::Window?

MyClass::MyClass(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder)
    : Gtk::Window(cobject)
{
    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_resource("/layouts/mywindow.glade");
    // What goes here?
    // something like?: builder->get_widget_derived("myWindow", ???);
}

Solution

  • The function get_widget_derived will be needed to create that base object, so you cannot delay calling it in this manner. You can accomplish this with a static function, which will generate everything for you

    #include "myclass.h"
    int main(int argc, char *argv[])
    {
        Gtk::Main kit(argc, argv);
    
        MyClass* helloworld = MyClass::getInstance();
    
        kit.run(*helloworld);
    
        return 0;
    }
    

    with the following definition:

    MyClass* MyClass::getInstance() // a static function
    {
        MyClass* result;
        Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_resource("/layouts/mywindow.glade");
        builder->get_widget_derived("NameOfMyWindow", result);
        return result
    }
    

    and the constructor is simple after that:

    MyClass::MyClass(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refBuilder)
        : Gtk::Window(cobject)
    {
        // Start doing stuff, because the object is constructed
    }
    

    Note: This code is not tested