Skip to content

Add Gtk.build helper

Sonny Piers requested to merge sonny/builder-helper into master

This MR adds a helper to simplify using a piece of GTK interface.

It's painful to use Gtk.Builder, I have identified the following problems:

  1. verbose and lots of jargon
  2. difficult to bind signals
  3. difficult to connect objects for property binding and expressions
  4. Loading a xml file correctly takes a lot of care

I would like to propose a simple API in GJS to load, build, expose objects and connect signals on builder XML.

In addition to regular GJS development, this is also useful to simplify GJS examples in Workbench Library or general documentation.

This is how you would use the helper:

<interface>
  <requires lib="gtk" version="4.0" />
  <object class="GtkApplicationWindow" id="window">
    <!-- property binding -->
    <property
      name="title"
      bind-source="app"
      bind-property="application-id"
      bind-flags="sync-create"
    />
    <!-- expression -->
    <binding name="application">
      <constant>app</constant>
    </binding>
    <property name="default-width">400</property>
    <property name="default-height">400</property>
    <child>
      <object class="GtkButton" id="button">
        <!-- signal handler -->
        <signal name="clicked" handler="onClicked" />
      </object>
    </child>
  </object>
</interface>
// We can use import.meta.resolve('window.xml') in the future
const uri = GLib.Uri.resolve_relative(import.meta.url, 'gtk4-interface.ui', GLib.UriFlags.NONE);

// build returns a Proxy object that lets the user get objects directly
const {window, button} = Gtk.build(uri, {
  // You can pass signal handlers
  onClicked,
  // And GObjects for bindings
  app,
});

button.title = "Naturaleza es maravillosa";
window.present();

Note: this is not for <template/> for which we already have a good helper

Edited by Sonny Piers

Merge request reports