Set child for custom templated widget

Hi, I created a custom “MyApplicationWindow” class derived from “Gtk::AppliaktionWindow” for that I have designed an “template.ui” with an e.g. “Gtk::Stack” for hosting child widgets. Now I used this custom class in the application.ui file. But I am wondering how to achieve that child widgets (here a “Gtk::Button”) are added to the “Gtk::Stack” now?

Template.ui:

<?xml version='1.0' encoding='UTF-8'?>
<interface>
	<requires lib="gtk" version="4.0"/>
	<template class="MyApplicationWindow" parent="GtkApplicationWindow">
		<property name="title">Title</property>
		<child>
			<object class="GtkStack" id="content">
			</object>
		</child>
	</template>
</interface>

Application.ui:

<?xml version='1.0' encoding='UTF-8'?>
<interface>
	<requires lib="gtk" version="4.0"/>
	<object class="MyApplicationWindow" id="mainWindow">
		<child>
			<object class="GtkButton" id="button">
				<property name="label">Hello World!</property>
			</object>
		</child>
	</object>
</interface>

You have to do this in the file where you are instantiating the MyApplicationWindow class, where you are importing Template.ui. One of the properties of this class will be Gtk.Stake, represented by its ID. In your case, the ID is “content”. So just use the Gtk.Stack method to add child.

The button will not be added (and does not need to be) in Application.ui, but will be created and added via code in the file where the MyApplicationWindow class is being instantiated.

This makes no sense as it makes templates and ui files completely worthless. I don’t want to create hundrets of ui elements in code. So this means, the GTKs template system is broken by design?

Hi,

From Application.ui you can refer to the Stack by its ID as internal-child:

<object class="MyApplicationWindow" id="mainWindow">
    <child internal-child="content">
        ...
    </child>
</object>

Look in gtk source code, for example gtkmessagedialog inherits from gtkdialog and sets some of its internal elements.

1 Like

I didn’t know about the solution proposed by @gwillems, but in my use of Templates it is very rare that I need to insert an element via code. This only happens when the element is generated in real time; in any other situation the element is added directly to the Template or is itself a template that I can import.

If you are using a pre-existing Template that you cannot modify, as is the case with gtkmessagedialog inherits from gtkdialog, I believe this is the only solution. But when it is a new Template built by you, this solution seems to me more like a workaround for a Template that was not created in the best way.

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