Komma åt komponenter

To access a widget, for instance to show a dialog, use the get_widget() method, providing the widget's name. This name should be specified in the Glade Properties window. If the widget could not be found, or is of the wrong type, then the pointer will be set to nullptr.

Dialogrutorna i detta kapitel är härledda från Gtk::Window eftersom Gtk::Dialog är föråldrat sedan gtkmm 4.10.

auto pDialog = builder->get_widget<Gtk::Window>("DialogBasic");

Gtk::Builder checks for a null pointer, and checks that the widget is of the expected type, and will show warnings on the command line about these.

Remember that you are not instantiating a widget with get_widget(), you are just obtaining a pointer to one that already exists. You will always receive a pointer to the same instance when you call get_widget() on the same Gtk::Builder, with the same widget name. The widgets are instantiated during Gtk::Builder::create_from_file().

get_widget() returns child widgets that are manage()ed (see the Memory Management chapter), so they will be deleted when their parent container is deleted. Windows (such as Dialogs) cannot be managed because they have no parent container, so you must delete them at some point. The documentation of Gtk::Builder has more to say about the memory management of different kinds of objects.

Referens

Exempel

This simple example shows how to load a Glade file at runtime and access the widgets with Gtk::Builder.

Källkod