Debian Codegraph @

docs/guide/gtk_template.rst

raw
1 .. _guide-gtk-template:
2
3 ============
4 Gtk.Template
5 ============
6
7 A GtkWidget subclass can use a
8 `GtkBuilder UI Definition <https://docs.gtk.org/gtk4/class.Builder.html#gtkbuilder-ui-definitions>`__
9 XML document as a template to create child widgets and set its own
10 properties, without creating a GtkBuilder instance. This is implemented
11 for Python by PyGObject with Gtk.Template.
12
13 The subclass uses a ``@Gtk.Template`` decorator and declares a class
14 variable ``__gtype_name__`` with the value of the XML ``template``
15 element ``class`` attribute.
16
17 Child widgets are declared, typically with the same names as the XML
18 ``object`` element ``id`` attributes, at the class level as instances
19 of ``Gtk.Template.Child``.
20
21 Signal handler methods, typically with the same names as the XML ``signal``
22 element ``handler`` attributes, use the ``@Gtk.Template.Callback`` decorator.
23
24 ``Gtk.Template()`` takes a mandatory keyword argument passing the XML document
25 or its location, either ``string``, ``filename`` or ``resource_path``.
26
27 ``Gtk.Template.Child()`` and ``Gtk.Template.Callback()`` optionally take
28 a ``name`` argument matching the value of the respective XML attribute,
29 in which case the Python attribute can have a different name.
30
31 Examples
32 --------
33
34 .. code-block:: python
35
36 xml = """\
37 <interface>
38 <template class="example1" parent="GtkBox">
39 <child>
40 <object class="GtkButton" id="hello_button">
41 <property name="label">Hello World</property>
42 <signal name="clicked" handler="hello_button_clicked" swapped="no" />
43 </object>
44 </child>
45 </template>
46 </interface>
47 """
48
49 @Gtk.Template(string=xml)
50 class Foo(Gtk.Box):
51 __gtype_name__ = "example1"
52
53 hello_button = Gtk.Template.Child()
54
55 @Gtk.Template.Callback()
56 def hello_button_clicked(self, *args):
57 pass
58
59 Python attribute names that are different to the XML values:
60
61 .. code-block:: python
62
63 @Gtk.Template(string=xml)
64 class Foo(Gtk.Box):
65 __gtype_name__ = "example1"
66
67 my_button = Gtk.Template.Child("hello_button")
68
69 @Gtk.Template.Callback("hello_button_clicked")
70 def bar(self, *args):
71 pass
72
73
74 Subclasses that declare ``__gtype_name__`` can be used as objects in the XML:
75
76 .. code-block:: python
77
78 xml = """\
79 <interface>
80 <template class="example3" parent="GtkBox">
81 <child>
82 <object class="ExampleButton" id="hello_button">
83 <property name="label">Hello World</property>
84 <signal name="clicked" handler="hello_button_clicked" swapped="no" />
85 </object>
86 </child>
87 </template>
88 </interface>
89 """
90
91
92 class HelloButton(Gtk.Button):
93 __gtype_name__ = "ExampleButton"
94
95
96 @Gtk.Template(string=xml)
97 class Foo(Gtk.Box):
98 __gtype_name__ = "example3"
99
100 hello_button = Gtk.Template.Child()
101
102 @Gtk.Template.Callback()
103 def hello_button_clicked(self, *args):
104 pass