Reusable XML defined Widget with GTKmm4

Hello.

I’m trying to build an application using GTKmm4 (C++) that will need to replicate the same “complex” widget multiple times.

This complex widget is composed by an Overlay, an image, some boxes, two labels and a button, plus some custom CSS.
I will instantiate it multiple times (how many is something that can be evaluated at runtime) and I will need to change the button text, labels texts and image content dynamically.

Provided that the quickest solution would be to create a class that will compose the widget in code; for the sake maintainability, readability, and to separate UI definition from the business code (as emphasized by the GTK documentation) I wanted to keep the widget definition separated.

From what I understood GTK (or at least, GTK4 in itself) has a template feature that allows the creation of a custom widget which loads the template and displays what I defined on the XML file, unfortunately however GTKmm offers no binding for the usage of such feature, and while documented I failed to create a C custom Widget that can use said custom template.

I also saw that GTKmm supports a different feature (which should achieve the same goal?) called a derived widget, I once again found examples online, but failed to reproduce them.

I am wondering if someone could provide an elegant and readable way to initialize a widget from a template, or even to instantiate multiple instances of a widget defined via XML as an object (since Builder does not allow to do that and since widgets are non copyable).

Thanks in advance!

I found the solution, it’s way easier than I thought and It’s actually surprising I didn’t get it before.

Just instantiate a new Gtk::Builder.
It turns outs that the builder parses XML UI files and instantiates the widgets specified inside of it, this means that you get an instance for every Gtk::Builder that you instantiate.

If you want to create a single widget definition via an XML UI file and then instantiate it multiple times, you just need to instantiate multiple Gtk::Builder and then do whatever you want with the individual widgets instances.

No derived widgets, no templates, just an extra builder.

1 Like

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