From a2bd7eb59b8a5963d27d58d58380c419ee00a472 Mon Sep 17 00:00:00 2001 From: Chris Mayo Date: Wed, 10 Feb 2021 19:01:40 +0000 Subject: docs: document Gtk.Template. Fixes #396 Examples derived from tests/test_gtk_template.py. --- docs/guide/gtk_template.rst | 90 +++++++++++++++++++++++++++++++++++++++++++++ docs/guide/index.rst | 1 + 2 files changed, 91 insertions(+) create mode 100644 docs/guide/gtk_template.rst (limited to 'docs') diff --git a/docs/guide/gtk_template.rst b/docs/guide/gtk_template.rst new file mode 100644 index 00000000..1e80fddf --- /dev/null +++ b/docs/guide/gtk_template.rst @@ -0,0 +1,90 @@ +============ +Gtk.Template +============ + +A GtkWidget subclass can use a +`GtkBuilder UI Definition `__ +XML document as a template to create child widgets and set its own +properties, without creating a GtkBuilder instance. This is implemented +for Python by PyGObject with Gtk.Template. + +The subclass uses a ``@Gtk.Template`` decorator and declares a class +variable ``__gtype_name__`` with the value of the XML ``template`` +element ``class`` attribute. + +Child widgets are declared, typically with the same names as the XML +``object`` element ``id`` attributes, at the class level as instances +of ``Gtk.Template.Child``. + +Signal handler methods, typically with the same names as the XML ``signal`` +element ``handler`` attributes, use the ``@Gtk.Template.Callback`` decorator. + +``Gtk.Template()`` takes a mandatory keyword argument passing the XML document +or its location, either ``string``, ``filename`` or ``resource_path``. + +``Gtk.Template.Child()`` and ``Gtk.Template.Callback()`` optionally take +a ``name`` argument matching the value of the respective XML attribute, +in which case the Python attribute can have a different name. + +Examples +-------- + +.. code-block:: python + + xml = """\ + + + + """ + + @Gtk.Template(string=xml) + class Foo(Gtk.Box): + __gtype_name__ = "example1" + + hello_button = Gtk.Template.Child() + + @Gtk.Template.Callback() + def hello_button_clicked(self, *args): + pass + +Python attribute names that are different to the XML values: + +.. code-block:: python + + @Gtk.Template(string=xml) + class Foo(Gtk.Box): + __gtype_name__ = "example1" + + my_button = Gtk.Template.Child("hello_button") + + @Gtk.Template.Callback("hello_button_clicked") + def bar(self, *args): + pass + + +To add widgets to the built-in child of a parent, describe the built-in widget +in the XML with its ``child`` element having an ``internal-child`` attribute set +to the name of the built-in widget: + +.. code-block:: XML + + + + diff --git a/docs/guide/index.rst b/docs/guide/index.rst index ac966d7e..e4dba05f 100644 --- a/docs/guide/index.rst +++ b/docs/guide/index.rst @@ -9,6 +9,7 @@ User Guide api/index cairo_integration + gtk_template threading debug_profile deploy -- cgit v1.2.1