Unable to find signal callback function when using UI description
Although manually connecting a signal through button.connect("clicked", on_click)
works, trying to define the callbacks in the UI definition results in getting an error that the function cannot be found. It looks like the overrides/Gtk.py
module is overriding Gtk.Builder to set a custom scope, I'm not sure how that scope gets passed in, though.
import sys
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, Adw
layout = """
<?xml version='1.0' encoding='UTF-8'?>
<interface>
<requires lib="gtk" version="4.6"/>
<object class="GtkBox">
<child>
<object class="GtkButton" id="button1">
<signal name="clicked" handler="on_click"/>
</object>
</child>
</object>
</interface>
"""
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.builder = Gtk.Builder()
self.builder.add_from_string(layout, -1)
def on_click(self, button: Gtk.Button):
print(f"Number button {button.get_name()} clicked")
class MyApp(Adw.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.connect("activate", self.on_activate)
def on_activate(self, app):
self.win = MainWindow(application=app)
self.win.present()
app = MyApp(application_id="com.example.GtkApplication")
app.run(sys.argv)
Gives the following error:
Traceback (most recent call last):
File "/home/dan/Projects/gtk-signal-test/signal_test.py", line 40, in on_activate
self.win = MainWindow(application=app)
File "/home/dan/Projects/gtk-signal-test/signal_test.py", line 28, in __init__
self.builder.add_from_string(layout)
File "/home/dan/Projects/gtk-signal-test/.venv/lib/python3.10/site-packages/gi/overrides/Gtk.py", line 489, in add_from_string
return Gtk.Builder.add_from_string(self, buffer, length)
gi.repository.GLib.GError: gtk-builder-error-quark: No function named `on_click`. (14)
Edited by Dan Yeaw