Gtk.Builder


Gtk.Builder — Build an interface from an XML UI definition

Object Hierarchy:

    GObject
    ╰── Gtk.Builder

Functions:

Description:

A Gtk.Builder is an auxiliary object that reads textual descriptions of a user interface and instantiates the described objects. To create a Gtk.Builder from a user interface description, call Gtk.Builder::new_from_file(), Gtk.Builder::new_from_resource() or Gtk.Builder::new_from_string().

In the (unusual) case that you want to add user interface descriptions from multiple sources to the same Gtk.Builder you can call Gtk.Builder::new() to get an empty builder and populate it by (multiple) calls to Gtk.Builder::add_from_file(), Gtk.Builder::add_from_resource() or Gtk.Builder::add_from_string().

A Gtk.Builder holds a reference to all objects that it has constructed and drops these references when it is finalized. This finalization can cause the destruction of non-widget objects or widgets which are not contained in a toplevel window. For toplevel windows constructed by a builder, it is the responsibility of the user to call Gtk.Widget::destroy() to get rid of them and all the widgets they contain.

The functions Gtk.Builder::get_object() and Gtk.Builder::get_objects() can be used to access the widgets in the interface by the names assigned to them inside the UI description. Toplevel windows returned by these functions will stay around until the user explicitly destroys them with Gtk.Widget::destroy(). Other widgets will either be part of a larger hierarchy constructed by the builder (in which case you should not have to worry about their lifecycle), or without a parent, in which case they have to be added to some container to make use of them.

Non-widget objects need to be reffed with g_object_ref() to keep them beyond the lifespan of the builder.

The function Gtk.Builder::connect_signals() and variants thereof can be used to connect handlers to the named signals in the description.

Gtk.Builder UI Definitions:

Gtk.Builder parses textual descriptions of user interfaces which are specified in an XML format which can be roughly described by the RELAX NG schema below. We refer to these descriptions as Gtk.Builder UI definitions or just UI definitions if the context is clear.

Do not confuse Gtk.Builder UI Definitions with [GtkUIManager UI Definitions][XML-UI], which are more limited in scope.

It is common to use .ui as the filename extension for files containing Gtk.Builder UI definitions.

[RELAX NG Compact Syntax](https://git.gnome.org/browse/gtk+/tree/gtk/gtkbuilder.rnc\) The toplevel element is <interface>. It optionally takes a domain attribute, which will make the builder look for translated strings using dgettext() in the domain specified. This can also be done by calling Gtk.Builder::set_translation_domain() on the builder.

Objects are described by <object> elements, which can contain <property> elements to set properties, <signal> elements which connect signals to handlers, and <child> elements, which describe child objects (most often widgets inside a container, but also e.g. actions in an action group, or columns in a tree model). A <child> element contains an <object> element which describes the child object.

The target toolkit version(s) are described by <requires> elements, the lib attribute specifies the widget library in question (currently the only supported value is gtk+) and the version attribute specifies the target version in the form <major>`.`<minor>. The builder will error out if the version requirements are not met.

Typically, the specific kind of object represented by an <object> element is specified by the class attribute. If the type has not been loaded yet, GTK+ tries to find the get_type() function from the class name by applying heuristics. This works in most cases, but if necessary, it is possible to specify the name of the get_type() function explictly with the "type-func" attribute. As a special case, Gtk.Builder allows to use an object that has been constructed by a GtkUIManager in another part of the UI definition by specifying the id of the GtkUIManager in the constructor attribute and the name of the object in the id attribute.

Objects may be given a name with the id attribute, which allows the application to retrieve them from the builder with Gtk.Builder::get_object().

An id is also necessary to use the object as property value in other parts of the UI definition. GTK+ reserves ids starting and ending with _ (3 underscores) for its own purposes.

Setting properties of objects is pretty straightforward with the property, and the content of the element specifies the value.

If the translatable attribute is set to a true value, GTK+ uses gettext() (or dgettext() if the builder has a translation domain set) to find a translation for the value. This happens before the value is parsed, so it can be used for properties of any type, but it is probably most useful for string properties. It is also possible to specify a context to disambiguate short strings, and comments which may help the translators.

Gtk.Builder can parse textual representations for the most common booleans (strings like TRUE, t, yes, y, 1 are interpreted as True, strings like FALSE, f, no, n, 0 are interpreted as False), enumerations (can be specified by their name, nick or integer value), flags (can be specified by their name, nick, integer value, optionally combined with |, e.g. GTK_VISIBLE|GTK_REALIZED) and colors (in a format understood by gdk_rgba_parse()). Pixbufs can be specified as a filename of an image file to load. Objects can be referred to by their name and by default refer to objects declared in the local xml fragment and objects exposed via Gtk.Builder::expose_object().

In general, Gtk.Builder allows forward references to objects — declared in the local xml; an object doesn’t have to be constructed before it can be referred to. The exception to this rule is that an object has to be constructed before it can be used as the value of a construct-only property.

It is also possible to bind a property value to another object's property value using the attributes "bind-source" to specify the source object of the binding, "bind-property" to specify the source property and optionally "bind-flags" to specify the binding flags Internally builder implement this using GBinding objects.

For more information see g_object_bind_property() Signal handlers are set up with the <signal> element. The name attribute specifies the name of the signal, and the handler attribute specifies the function to connect to the signal. By default, GTK+ tries to find the handler using g_module_symbol(), but this can be changed by passing a custom Gtk.BuilderConnectFunc to Gtk.Builder::connect_signals_full(). The remaining attributes, after, swapped and object, have the same meaning as the corresponding parameters of the g_signal_connect_object() or g_signal_connect_data() functions. A last_modification_time attribute is also allowed, but it does not have a meaning to the builder.

Sometimes it is necessary to refer to widgets which have implicitly been constructed by GTK+ as part of a composite widget, to set properties on them or to add further children (e.g. the vbox of a Gtk.Dialog). This can be achieved by setting the internal-child propery of the <child> element to a true value. Note that Gtk.Builder still requires an <object> element for the internal child, even if it has already been constructed.

A number of widgets have different places where a child can be added (e.g. tabs vs. page content in notebooks). This can be reflected in a UI definition by specifying the type attribute on a <child>. The possible values for the type attribute are described in the sections describing the widget-specific portions of UI definitions.

A Gtk.Builder UI Definition

<interface>
  <object class="GtkDialog" id="dialog1">
    <child internal-child="vbox">
      <object class="GtkBox" id="vbox1">
        <property name="border-width">10</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox" id="hbuttonbox1">
            <property name="border-width">20</property>
            <child>
              <object class="GtkButton" id="ok_button">
                <property name="label">gtk-ok</property>
                <property name="use-stock">TRUE</property>
                <signal name="clicked" handler="ok_button_clicked"/>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>

Beyond this general structure, several object classes define their own XML DTD fragments for filling in the ANY placeholders in the DTD above. Note that a custom element in a <child> element gets parsed by the custom tag handler of the parent object, while a custom element in an <object> element gets parsed by the custom tag handler of the object.

These XML fragments are explained in the documentation of the respective objects.

Additionally, since 3.10 a special <template> tag has been added to the format allowing one to define a widget class’s components.

See the [Gtk.Widget documentation][composite-templates] for details.


Function Details:

new()

new () -> Gtk.Builder

Creates a new empty builder object. This function is only useful if you intend to make multiple callsto Gtk.Builder:add_from_file(), Gtk.Builder:add_from_resource()or Gtk.Builder:add_from_string() in order to merge multiple UIdescriptions into a single builder. Most users will probably want to use Gtk.Builder:new_from_file(),Gtk.Builder:new_from_resource() or Gtk.Builder:new_from_string().

  • Returns: a new (empty) Gtk.Builder object

  • Since: 2.12


new_from_file()

new_from_file (filename:str) -> Gtk.Builder

Builds the Gtk.Builder UI definitionin the file filename. If there is an error opening the file or parsing the description thenthe program will be aborted. You should only ever attempt to parseuser interface descriptions that are shipped as part of your program.

  • Returns: a Gtk.Builder containing the described interface

  • Since: 3.10


new_from_resource()

new_from_resource (resource_path:str) -> Gtk.Builder

Builds the Gtk.Builder UI definitionat resource_path. If there is an error locating the resource or parsing thedescription, then the program will be aborted.

  • Returns: a Gtk.Builder containing the described interface

  • Since: 3.10


new_from_string()

new_from_string (string:str, length:int) -> Gtk.Builder

Builds the user interface described by string (in theGtk.Builder UI definition format). If string is None-terminated, then length should be -1.If length is not -1, then it is the length of string. If there is an error parsing string then the program will beaborted. You should not attempt to parse user interface descriptionfrom untrusted sources.

  • Returns: a Gtk.Builder containing the interface described by string

  • Since: 3.10


add_callback_symbol()

add_callback_symbol (self, callback_name:str, callback_symbol:GObject.Callback)

Adds the callback_symbol to the scope of builder under the given callback_name. Using this function overrides the behavior of Gtk.Builder:connect_signals()for any callback symbols that are added. Using this method allows for betterencapsulation as it does not require that callback symbols be declared inthe global namespace.

  • Since: 3.10

add_from_file()

add_from_file (self, filename:str) -> int

Parses a file containing a Gtk.Builder UI definitionand merges it with the current contents of builder. Most users will probably want to use Gtk.Builder:new_from_file(). If an error occurs, 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_FILE_ERRORdomain. It’s not really reasonable to attempt to handle failures of thiscall. You should not use this function with untrusted files (ie:files that are not part of your application). Broken Gtk.Builderfiles can easily crash your program, and it’s possible that memorywas leaked leading up to the reported failure. The only reasonablething to do when an error is detected is to call g_error().

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 2.12


add_from_resource()

add_from_resource (self, resource_path:str) -> int

Parses a resource file containing a Gtk.Builder UI definitionand merges it with the current contents of builder. Most users will probably want to use Gtk.Builder:new_from_resource(). If an error occurs, 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_RESOURCE_ERRORdomain. It’s not really reasonable to attempt to handle failures of thiscall. The only reasonable thing to do when an error is detected isto call g_error().

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 3.4


add_from_string()

add_from_string (self, buffer:str, length:int) -> int

Parses a string containing a Gtk.Builder UI definitionand merges it with the current contents of builder. Most users will probably want to use Gtk.Builder:new_from_string(). Upon errors 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR orG_VARIANT_PARSE_ERROR domain. It’s not really reasonable to attempt to handle failures of thiscall. The only reasonable thing to do when an error is detected isto call g_error().

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 2.12


add_objects_from_file()

add_objects_from_file (self, filename:str, object_ids:list) -> int

Parses a file containing a Gtk.Builder UI definitionbuilding only the requested objects and mergesthem with the current contents of builder. Upon errors 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_FILE_ERRORdomain. If you are adding an object that depends on an object that is notits child (for instance a Gtk.TreeView that depends on itsGtk.TreeModel), you have to explicitly list all of them in object_ids.

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 2.14


add_objects_from_string()

add_objects_from_string (self, buffer:str, length:int, object_ids:list) -> int

Parses a string containing a Gtk.Builder UI definitionbuilding only the requested objects and mergesthem with the current contents of builder. Upon errors 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR or G_MARKUP_ERROR domain. If you are adding an object that depends on an object that is notits child (for instance a Gtk.TreeView that depends on itsGtk.TreeModel), you have to explicitly list all of them in object_ids.

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 2.14


add_objects_from_resource()

add_objects_from_resource (self, resource_path:str, object_ids:list) -> int

Parses a resource file containing a Gtk.Builder UI definitionbuilding only the requested objects and mergesthem with the current contents of builder. Upon errors 0 will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_RESOURCE_ERRORdomain. If you are adding an object that depends on an object that is notits child (for instance a Gtk.TreeView that depends on itsGtk.TreeModel), you have to explicitly list all of them in object_ids.

  • Returns: A positive value on success, 0 if an error occurred

  • Since: 3.4


get_object()

get_object (self, name:str) -> GObject.Object

Gets the object named name. Note that this function does notincrement the reference count of the returned object.

  • Returns: the object named nameor None ifit could not be found in the object tree.

  • Since: 2.12


get_objects()

get_objects (self) -> list

Gets all objects that have been constructed by builder. Note thatthis function does not increment the reference counts of the returnedobjects.

  • Returns: a newly-allocated GSList containing all the objectsconstructed by the Gtk.Builder instance. It should be freed byg_slist_free().

  • Since: 2.12


expose_object()

expose_object (self, name:str, object:GObject.Object)

Add object to the builder object pool so it can be referenced just like anyother object built by builder.

  • Since: 3.8

connect_signals_full()

connect_signals_full (self, func:Gtk.BuilderConnectFunc, user_data=None)

This function can be thought of the interpreted language bindingversion of Gtk.Builder:connect_signals(), except that it does notrequire GModule to function correctly.

  • Since: 2.12

set_translation_domain()

set_translation_domain (self, domain:str=None)

Sets the translation domain of builder.See “translation-domain”.

  • Since: 2.12

get_translation_domain()

get_translation_domain (self) -> str

Gets the translation domain of builder.

  • Returns: the translation domain. This string is ownedby the builder object and must not be modified or freed.

  • Since: 2.12


set_application()

set_application (self, application:Gtk.Application)

Sets the application associated with builder. You only need this function if there is more than one GApplicationin your process. application cannot be None.

  • Since: 3.10

get_application()

get_application (self) -> Gtk.Application

Gets the Gtk.Application associated with the builder. The Gtk.Application is used for creating action proxies as requestedfrom XML that the builder is loading. By default, the builder uses the default application: the one fromg_application_get_default(). If you want to use another applicationfor constructing proxies, use Gtk.Builder:set_application().

  • Returns: the application being used by the builder,or None.

  • Since: 3.10


get_type_from_name()

get_type_from_name (self, type_name:str) -> GType

Looks up a type by name, using the virtual function thatGtk.Builder has for that purpose. This is mainly used whenimplementing the Gtk.Buildable interface on a type.

  • Returns: the GType found for type_nameor G_TYPE_INVALIDif no type was found

  • Since: 2.12


value_from_string()

value_from_string (self, pspec:GObject.ParamSpec, string:str) -> bool, value:GObject.Value

This function demarshals a value from a string. This functioncalls g_value_init() on the value argument, so it need not beinitialised beforehand. This function can handle char, uchar, boolean, int, uint, long,ulong, enum, flags, float, double, string, GdkColor, GdkRGBA andGtk.Adjustment type values. Support for Gtk.Widget type values isstill to come. Upon errors FALSE will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR domain.

  • Returns: True on success

  • Since: 2.12


value_from_string_type()

value_from_string_type (self, type:GType, string:str) -> bool, value:GObject.Value

Like Gtk.Builder:value_from_string(), this function demarshalsa value from a string, but takes a GType instead of GParamSpec.This function calls g_value_init() on the value argument, so itneed not be initialised beforehand. Upon errors FALSE will be returned and error will be assigned aGError from the GTK_BUILDER_ERROR domain.

  • Returns: True on success

  • Since: 2.12


Example:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Handler:
    def on_button_clicked(self, button):
        print("Button clicked!")

    def on_togglebutton_toggled(self, togglebutton):
        print("ToggleButton toggled!")

    def on_exit_application(self, *args):
        Gtk.main_quit()

builder = Gtk.Builder()
builder.add_from_file("builder.glade")
builder.connect_signals(Handler())

window = builder.get_object("window1")
window.show_all()

Gtk.main()

results matching ""

    No results matching ""