How do I insert a dynamically created widget into a Gtk.Builder / Gtk.Template -created tree of widgets?

I’m basically trying to use the .ui file and logic, based off of the GNOME Builder’s boilerplate code, but to inject an arbitrary widget after the others have been created:

 @Gtk.Template(resource_path='/net/videotune/tuner/window.ui')
 class VideotuneWindow(Adw.ApplicationWindow):

     def __init__(self, **kwargs):
         super().__init__(**kwargs)

[...]

        box = Gtk.Template.Child("video_container")
        box.append(gtksink.props.widget)
[...]
        <child>
          <object class="GtkBox" id="video_container">
            <property name="orientation">vertical</property>
          </object>
        </child>
[...]

But this is the result:

Traceback (most recent call last):
  File "/app/share/videotune/videotune/main.py", line 48, in do_activate
    win = VideotuneWindow(application=self)
  File "/app/share/videotune/videotune/window.py", line 40, in __init__
    box.append(gtksink.props.widget)
AttributeError: 'Child' object has no attribute 'append'

Does anyone know how to extract a reference to the Gtk.Box object?

While I have a general sense about Python decorators, the Python gi doc doesn’t have a section for Gtk.Template, so I wonder if it would be more straight-forward, and a bit less magical, if I explicitly used Gtk.Builder rather than Gtk.Template?

Here are the python docs for Gtk.Template: Gtk.Template — PyGObject.

You must define them as class attributes.

Thanks for the help. : ) The following worked for me, with or without the parameter to Gtk.Template.Child:

@Gtk.Template(resource_path='/net/videotune/tuner/window.ui')
 class VideotuneWindow(Adw.ApplicationWindow):
     __gtype_name__ = 'VideotuneWindow'
 
    video_container = Gtk.Template.Child("video_container")

    [...]

In case anyone is wondering, I previously tried building the widget tree using Gtk.Builder, but ran into the following issue:

(python3:2): Gtk-ERROR **: 08:38:27.805: failed to add UI from resource /net/videotune/tuner/window.ui: .:2:147 Template declaration (class 'VideotuneWindow', parent 'AdwApplicationWindow') where templates aren't supported

In case anyone is wondering, I previously tried building the widget tree using Gtk.Builder, but ran into the following issue:

When you are using Gtk.Builder you shouldn’t use <template> but a regular <object>.

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