Gtk4, python, builder

Hi there. I’m considering porting some python & gtk3 ( plus a LOT of builder.ui files ) stuff to gtk4. I’ve had a look at cambalache, and I think this might all work. However I don’t immediately see how to trigger the gtk main loop. In gtk3 I used to go:


… but that doesn’t work. What’s the secret?

In GTK4 you’re supposed to use GtkApplication.

Create a GtkApplication instance—either a direct one, or (better) a derived class with all your global application data—then create your window in the “activate” signal handler.

Strictly speaking, this is also recommended in GTK3.

Hi Emmanuele. I had tried that actually.


import gi

gi.require_version("Gtk", "4.0")

from gi.repository import Gtk

def on_activate(app):
    builder = Gtk.Builder.new_from_file('test.ui')
    test = builder.get_object('test')

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

test.ui - exported from cambalache:

<?xml version='1.0' encoding='UTF-8'?>
<!-- Created with Cambalache 0.8.2 -->
  <!-- interface-name test.ui -->
  <requires lib="gtk" version="4.0"/>
  <object class="GtkWindow" id="test">
    <property name="halign">start</property>
      <object class="GtkGrid"/>

Yes I’m aware there are no widgets in the builder ui file. When I run this, the window pops up and immediately disappears, with the application exiting.

You need to add the window to the application. The application’s lifetime is bound to the number of windows it has, so that when the last window is closed, the application automatically terminates:

def on_activate(app):
    builder = Gtk.Builder.new_from_file('test.ui')
    test = builder.get_object('test')

The next step is to create a subclass of GtkApplicationWindow, and use a template instead of creating a GtkBuilder and getting the window out of it.

1 Like

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