Difference between composite and regular GtkWidgets?

Forgive me if this an obvious question, but I just started doing GTK development, and noticed that there is such a thing as a composite (template) widget, which essentially is a widget composed of other widgets. However, can’t this also be done with a regular object-wrapped GtkBuilder file? If so, what’s the upside to using a composite version? Thanks.

3 Likes

A template is a specific type of UI description that is attached to a GtkWidget subclass, and is automatically parsed and built every time that class is instantiated. The upside is that GTK provides API to attach the UI description data to the class, as well as allowing you to automatically gather the widgets you’re interested in from the template and store a reference to them in your instance data; this is much more convenient than doing it yourself.

For more information on template files, you can read the documentation for GtkWidget.

3 Likes

Thanks for that. I definitely understand the concept now, but how exactly does this differ in code? Could someone post code using a template and the equivalent code without?

In one case, you create a GtkBuilder instance, load the UI definitions from a file/resource/buffer, then you call gtk_builder_get_object() for every widget you want to access, and store those pointers somewhere in order to access them.

In the template case you have to:

  • create your own derived type
  • add the pointers to each child you care about into the instance data structure, or the private instance data structure
  • call gtk_widget_class_set_template() inside the class initialisation function
  • call gtk_widget_class_bind_template_* pointing to the fields in the instance data
  • call gtk_widget_init_template() inside the instance initialisation function

The documentation for GtkWidget that I linked above has examples on how to use the API. Additionally, the API reference for each function has more information on how to use it.

If you want more examples, you can look at the gtk3-demo demo application that is provided by GTK itself.

2 Likes

That is all I needed to know. Thanks again for your help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.