Python + Gtk.Builder + connecting signals

Hi all. I have a very simple example app:

import gi

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

from gi.repository import Gtk , Adw

class ExampleApplication( Adw.Application ):

    def __init__( self , **kwargs ):
        super().__init__( **kwargs )
        self.connect( 'activate' , self.on_activate )

    def on_activate( self , app ):

        self.builder = Gtk.Builder()
        self.builder.set_current_object( self )
        self.builder.add_from_file( '/home/dankasak/cambalache/test.ui' )
        self.test_window = self.builder.get_object('test')
        self.test_window.set_application( self )

        # ... some other things happen here to create a self.form object

    def on_apply( self ):
        self.form.apply()

app = ExampleApplication()
app.run()

This works if I don’t have any signals defined in the Gtk.Builder file. If I place a button and add a callback for the ‘clicked’ signal … to call the on_apply callback … I get:

    self.builder.add_from_file( '/home/dankasak/cambalache/test.ui' )
gi.repository.GLib.GError: gtk-builder-error-quark: No function named `on_apply`. (14)

So I guess builder is not looking in the correct scope for the on_apply ‘function’. This is why ( after searching here ) I added the line:

self.builder.set_current_object( self )

… but this doesn’t help. How do I get Gtk.Builder to map callback in the builder definition with my class ( ie self ). In previous versions / languages ( gtk3 + perl ) this kinda happened automatically.

Hi,

You have to pass a mapping (typically a class instance) with the callbacks to the GtkBuilder constructor.

self.builder = Gtk.Builder(self)

GtkBuilder will then automatically lookup into self for the callbacks. Make sure on_apply is a method of ExampleApplication.

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