How to implement Gtk.Buildable.add_child in Python?

I am subclassing Gtk.ListBoxRow with a Gtk.Box instance as its child. The new class is named CursorSizeSelectorRow. I would like to use it inside a ui file where adding a new child to its instance appends the child to the box instead of replacing it. I also need to connect to some signals of the children.

I tried adding Gtk.Buildable as a base and defining a add_child() method. It didn’t work. I tried changing the method name to buildable_add_child(). It still didn’t work. My custom add_child method is never called.

I tried searching the web but found nothing useful.

How do I do it?

I am not sure overriding add_child() is possible, but for ui file you would most likely would like to use

<template class=" CursorSizeSelectorRow" parent=“GtkListBoxRow”>

and then in Python do class like this

@Gtk.Template(resource_path=‘cursorsizeselectorrow.ui’)
class CursorSizeSelectorRow(Gtk.ListBoxRow):

and then add override there?

1 Like

For your use case you just need to implement do_add_child. Hopefully this example helps you:

import gi

gi.require_version('Gtk', '4.0')
from gi.repository import Gtk


UI = """
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <object class="GtkListBox" id="list">
    <child>
        <object class="CustomRow"></object>
    </child>
    <child>
      <object class="CustomRow">
        <child>
            <object class="GtkBox">
                <child>
                    <object class="GtkLabel">
                        <property name="label">A new label</property>
                    </object>
                </child>
            </object>
        </child>
      </object>
    </child>
  </object>
</interface>
"""


class CustomRow(Gtk.ListBoxRow, Gtk.Buildable):
    __gtype_name__ = 'CustomRow'

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

        # Default content
        self.box = Gtk.Box()
        label = Gtk.Label(label='Some label')
        self.box.append(label)
        self.set_child(self.box)

    def do_add_child(self, _builder, child, _type):
        self.box.append(child)


class Window(Gtk.ApplicationWindow):
    def __init__(self, **kargs):
        super().__init__(**kargs)

        builder = Gtk.Builder.new_from_string(UI, -1)
        list_box = builder.get_object('list')
        self.set_child(list_box)


def on_activate(app):
    win = Window(application=app)
    win.present()


app = Gtk.Application(application_id='com.example.App')
app.connect('activate', on_activate)

app.run(None)
1 Like

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