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

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"?>
  <object class="GtkListBox" id="list">
        <object class="CustomRow"></object>
      <object class="CustomRow">
            <object class="GtkBox">
                    <object class="GtkLabel">
                        <property name="label">A new label</property>

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

    def __init__(self, **kargs):

        # Default content = Gtk.Box()
        label = Gtk.Label(label='Some label')

    def do_add_child(self, _builder, child, _type):

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

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

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

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

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