GtkBuilder

GtkBuilder — Build an interface from an XML UI definition

Properties

GObject * current-object Read / Write
GtkBuilderScope * scope Read / Write / Construct
gchar * translation-domain Read / Write

Types and Values

Object Hierarchy

    GObject
    ╰── GtkBuilder

Includes

#include <gtk/gtk.h>

Description

A GtkBuilder is an auxiliary object that reads textual descriptions of a user interface and instantiates the described objects. To create a GtkBuilder 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 GtkBuilder 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 GtkBuilder 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_window_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_window_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.

GtkBuilder UI Definitions

GtkBuilder 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 “GtkBuilder UI definitions” or just “UI definitions” if the context is clear.

RELAX NG Compact Syntax

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 explicitly with the "type-func" attribute. As a special case, GtkBuilder 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> element: the “name” attribute specifies the name of 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.

GtkBuilder can parse textual representations for the most common property types: characters, strings, integers, floating-point numbers, 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()).

GVariants can be specified in the format understood by g_variant_parse(), and 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, GtkBuilder 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, and optionally, "bind-property" and "bind-flags" to specify the source property and source binding flags respectively. Internally builder implements this using GBinding objects. For more information see g_object_bind_property()

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 GtkDialog). This can be achieved by setting the “internal-child” property of the <child> element to a true value. Note that GtkBuilder 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.


Signal handlers and function pointers

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. 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.

If you rely on GModule support to lookup callbacks in the symbol table, the following details should be noted:

When compiling applications for Windows, you must declare signal callbacks with G_MODULE_EXPORT, or they will not be put in the symbol table. On Linux and Unices, this is not necessary; applications should instead be compiled with the -Wl,--export-dynamic CFLAGS, and linked against gmodule-export-2.0.


A GtkBuilder UI Definition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<interface>
  <object class="GtkDialog" id="dialog1">
    <child internal-child="vbox">
      <object class="GtkBox" id="vbox1">
        <child internal-child="action_area">
          <object class="GtkBox" id="hbuttonbox1">
            <child>
              <object class="GtkButton" id="ok_button">
                <property name="label">gtk-ok</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 GtkWidget documentation for details.

Functions

gtk_builder_new ()

GtkBuilder *
gtk_builder_new (void);

Creates a new empty builder object.

This function is only useful if you intend to make multiple calls to gtk_builder_add_from_file(), gtk_builder_add_from_resource() or gtk_builder_add_from_string() in order to merge multiple UI descriptions 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) GtkBuilder object


gtk_builder_new_from_file ()

GtkBuilder *
gtk_builder_new_from_file (const gchar *filename);

Builds the GtkBuilder UI definition in the file filename .

If there is an error opening the file or parsing the description then the program will be aborted. You should only ever attempt to parse user interface descriptions that are shipped as part of your program.

Parameters

filename

filename of user interface description file

 

Returns

a GtkBuilder containing the described interface


gtk_builder_new_from_resource ()

GtkBuilder *
gtk_builder_new_from_resource (const gchar *resource_path);

Builds the GtkBuilder UI definition at resource_path .

If there is an error locating the resource or parsing the description, then the program will be aborted.

Parameters

resource_path

a GResource resource path

 

Returns

a GtkBuilder containing the described interface


gtk_builder_new_from_string ()

GtkBuilder *
gtk_builder_new_from_string (const gchar *string,
                             gssize length);

Builds the user interface described by string (in the GtkBuilder UI definition format).

If string is NULL-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 be aborted. You should not attempt to parse user interface description from untrusted sources.

Parameters

string

a user interface (XML) description

 

length

the length of string , or -1

 

Returns

a GtkBuilder containing the interface described by string


gtk_builder_create_closure ()

GClosure *
gtk_builder_create_closure (GtkBuilder *builder,
                            const char *function_name,
                            GtkBuilderClosureFlags flags,
                            GObject *object,
                            GError **error);

Creates a closure to invoke the function called function_name .

If a closure function was set via gtk_builder_set_closure_func(), will be invoked. Otherwise, gtk_builder_create_cclosure() will be called.

If no closure could be created, NULL will be returned and error will be set.

Parameters

builder

a GtkBuilder

 

function_name

name of the function to look up

 

flags

closure creation flags

 

object

Object to create the closure with.

[nullable]

error

return location for an error, or NULL.

[allow-none]

Returns

A new closure for invoking function_name .

[nullable]


gtk_builder_add_from_file ()

gboolean
gtk_builder_add_from_file (GtkBuilder *builder,
                           const gchar *filename,
                           GError **error);

Parses a file containing a GtkBuilder UI definition and 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 a GError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_FILE_ERROR domain.

It’s not really reasonable to attempt to handle failures of this call. You should not use this function with untrusted files (ie: files that are not part of your application). Broken GtkBuilder files can easily crash your program, and it’s possible that memory was leaked leading up to the reported failure. The only reasonable thing to do when an error is detected is to call g_error().

Parameters

builder

a GtkBuilder

 

filename

the name of the file to parse

 

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_add_from_resource ()

gboolean
gtk_builder_add_from_resource (GtkBuilder *builder,
                               const gchar *resource_path,
                               GError **error);

Parses a resource file containing a GtkBuilder UI definition and 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 a GError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_RESOURCE_ERROR domain.

It’s not really reasonable to attempt to handle failures of this call. The only reasonable thing to do when an error is detected is to call g_error().

Parameters

builder

a GtkBuilder

 

resource_path

the path of the resource file to parse

 

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_add_from_string ()

gboolean
gtk_builder_add_from_string (GtkBuilder *builder,
                             const gchar *buffer,
                             gssize length,
                             GError **error);

Parses a string containing a GtkBuilder UI definition and merges it with the current contents of builder .

Most users will probably want to use gtk_builder_new_from_string().

Upon errors FALSE will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_VARIANT_PARSE_ERROR domain.

It’s not really reasonable to attempt to handle failures of this call. The only reasonable thing to do when an error is detected is to call g_error().

Parameters

builder

a GtkBuilder

 

buffer

the string to parse

 

length

the length of buffer (may be -1 if buffer is nul-terminated)

 

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_add_objects_from_file ()

gboolean
gtk_builder_add_objects_from_file (GtkBuilder *builder,
                                   const gchar *filename,
                                   const char **object_ids,
                                   GError **error);

Parses a file containing a GtkBuilder UI definition building only the requested objects and merges them with the current contents of builder .

Upon errors 0 will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_FILE_ERROR domain.

If you are adding an object that depends on an object that is not its child (for instance a GtkTreeView that depends on its GtkTreeModel), you have to explicitly list all of them in object_ids .

Parameters

builder

a GtkBuilder

 

filename

the name of the file to parse

 

object_ids

nul-terminated array of objects to build.

[array zero-terminated=1][element-type utf8]

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_add_objects_from_string ()

gboolean
gtk_builder_add_objects_from_string (GtkBuilder *builder,
                                     const gchar *buffer,
                                     gssize length,
                                     const char **object_ids,
                                     GError **error);

Parses a string containing a GtkBuilder UI definition building only the requested objects and merges them with the current contents of builder .

Upon errors FALSE will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR or G_MARKUP_ERROR domain.

If you are adding an object that depends on an object that is not its child (for instance a GtkTreeView that depends on its GtkTreeModel), you have to explicitly list all of them in object_ids .

Parameters

builder

a GtkBuilder

 

buffer

the string to parse

 

length

the length of buffer (may be -1 if buffer is nul-terminated)

 

object_ids

nul-terminated array of objects to build.

[array zero-terminated=1][element-type utf8]

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_add_objects_from_resource ()

gboolean
gtk_builder_add_objects_from_resource (GtkBuilder *builder,
                                       const gchar *resource_path,
                                       const char **object_ids,
                                       GError **error);

Parses a resource file containing a GtkBuilder UI definition building only the requested objects and merges them with the current contents of builder .

Upon errors 0 will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR, G_MARKUP_ERROR or G_RESOURCE_ERROR domain.

If you are adding an object that depends on an object that is not its child (for instance a GtkTreeView that depends on its GtkTreeModel), you have to explicitly list all of them in object_ids .

Parameters

builder

a GtkBuilder

 

resource_path

the path of the resource file to parse

 

object_ids

nul-terminated array of objects to build.

[array zero-terminated=1][element-type utf8]

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success, FALSE if an error occurred


gtk_builder_extend_with_template ()

gboolean
gtk_builder_extend_with_template (GtkBuilder *builder,
                                  GObject *object,
                                  GType template_type,
                                  const gchar *buffer,
                                  gssize length,
                                  GError **error);

Main private entry point for building composite container components from template XML.

This is exported purely to let gtk-builder-tool validate templates, applications have no need to call this function.

Parameters

builder

a GtkBuilder

 

object

the object that is being extended

 

template_type

the type that the template is for

 

buffer

the string to parse

 

length

the length of buffer (may be -1 if buffer is nul-terminated)

 

error

return location for an error, or NULL.

[allow-none]

Returns

A positive value on success, 0 if an error occurred


gtk_builder_get_object ()

GObject *
gtk_builder_get_object (GtkBuilder *builder,
                        const gchar *name);

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

Parameters

builder

a GtkBuilder

 

name

name of object to get

 

Returns

the object named name or NULL if it could not be found in the object tree.

[nullable][transfer none]


gtk_builder_get_objects ()

GSList *
gtk_builder_get_objects (GtkBuilder *builder);

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

Parameters

builder

a GtkBuilder

 

Returns

a newly-allocated GSList containing all the objects constructed by the GtkBuilder instance. It should be freed by g_slist_free().

[element-type GObject][transfer container]


gtk_builder_expose_object ()

void
gtk_builder_expose_object (GtkBuilder *builder,
                           const gchar *name,
                           GObject *object);

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

Parameters

builder

a GtkBuilder

 

name

the name of the object exposed to the builder

 

object

the object to expose

 

gtk_builder_set_current_object ()

void
gtk_builder_set_current_object (GtkBuilder *builder,
                                GObject *current_object);

Sets the current object for the builder . The current object can be tought of as the this object that the builder is working for and will often be used as the default object when an object is optional.

gtk_widget_init_template() for example will set the current object to the widget the template is inited for. For functions like gtk_builder_new_from_resource(), the current object will be NULL.

Parameters

builder

a GtkBuilder

 

current_object

the new current object or NULL for none.

[nullable][transfer none]

gtk_builder_get_current_object ()

GObject *
gtk_builder_get_current_object (GtkBuilder *builder);

Gets the current object set via gtk_builder_set_current_object().

Parameters

builder

a GtkBuilder

 

Returns

the current object.

[nullable][transfer none]


gtk_builder_set_scope ()

void
gtk_builder_set_scope (GtkBuilder *builder,
                       GtkBuilderScope *scope);

Sets the scope the builder should operate in.

If scope is NULL a new GtkBuilderCScope will be created.

See the GtkBuilderScope documentation for details.

Parameters

builder

a GtkBuilder

 

scope

the scope to use or NULL for the default.

[nullable][transfer none]

gtk_builder_get_scope ()

GtkBuilderScope *
gtk_builder_get_scope (GtkBuilder *builder);

Gets the scope in use that was set via gtk_builder_set_scope().

See the GtkBuilderScope documentation for details.

Parameters

builder

a GtkBuilder

 

Returns

the current scope.

[transfer none]


gtk_builder_set_translation_domain ()

void
gtk_builder_set_translation_domain (GtkBuilder *builder,
                                    const gchar *domain);

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

Parameters

builder

a GtkBuilder

 

domain

the translation domain or NULL.

[nullable]

gtk_builder_get_translation_domain ()

const gchar *
gtk_builder_get_translation_domain (GtkBuilder *builder);

Gets the translation domain of builder .

Parameters

builder

a GtkBuilder

 

Returns

the translation domain or NULL in case it was never set or explicitly unset via gtk_builder_set_translation_domain(). This string is owned by the builder object and must not be modified or freed.

[transfer none][nullable]


gtk_builder_get_type_from_name ()

GType
gtk_builder_get_type_from_name (GtkBuilder *builder,
                                const char *type_name);

Looks up a type by name, using the virtual function that GtkBuilder has for that purpose. This is mainly used when implementing the GtkBuildable interface on a type.

Parameters

builder

a GtkBuilder

 

type_name

type name to lookup

 

Returns

the GType found for type_name or G_TYPE_INVALID if no type was found


gtk_builder_value_from_string ()

gboolean
gtk_builder_value_from_string (GtkBuilder *builder,
                               GParamSpec *pspec,
                               const gchar *string,
                               GValue *value,
                               GError **error);

This function demarshals a value from a string. This function calls g_value_init() on the value argument, so it need not be initialised beforehand.

This function can handle char, uchar, boolean, int, uint, long, ulong, enum, flags, float, double, string, GdkRGBA and GtkAdjustment type values. Support for GtkWidget type values is still to come.

Upon errors FALSE will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR domain.

Parameters

builder

a GtkBuilder

 

pspec

the GParamSpec for the property

 

string

the string representation of the value

 

value

the GValue to store the result in.

[out]

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success


gtk_builder_value_from_string_type ()

gboolean
gtk_builder_value_from_string_type (GtkBuilder *builder,
                                    GType type,
                                    const gchar *string,
                                    GValue *value,
                                    GError **error);

Like gtk_builder_value_from_string(), this function demarshals a value from a string, but takes a GType instead of GParamSpec. This function calls g_value_init() on the value argument, so it need not be initialised beforehand.

Upon errors FALSE will be returned and error will be assigned a GError from the GTK_BUILDER_ERROR domain.

Parameters

builder

a GtkBuilder

 

type

the GType of the value

 

string

the string representation of the value

 

value

the GValue to store the result in.

[out]

error

return location for an error, or NULL.

[allow-none]

Returns

TRUE on success


GTK_BUILDER_WARN_INVALID_CHILD_TYPE()

#define             GTK_BUILDER_WARN_INVALID_CHILD_TYPE(object, type)

This macro should be used to emit a warning about and unexpected type value in a GtkBuildable add_child implementation.

Parameters

object

the GtkBuildable on which the warning ocurred

 

type

the unexpected type value

 

Types and Values

GtkBuilder

typedef struct _GtkBuilder GtkBuilder;

enum GtkBuilderClosureFlags

The list of flags that can be passed to gtk_builder_scope_create_closure(). New values may be added in the future for new features, so external implementations of GtkBuilderScopeInterface should test the flags for unknown values and raise a %GTK_BUILDER_ERROR_INVALID_ATTRIBUTE error when they encounter one.

Members

GTK_BUILDER_CLOSURE_SWAPPED

The closure should be created swapped. See g_cclosure_new_swap() for details.

 

enum GtkBuilderError

Error codes that identify various errors that can occur while using GtkBuilder.

Members

GTK_BUILDER_ERROR_INVALID_TYPE_FUNCTION

A type-func attribute didn’t name a function that returns a GType.

 

GTK_BUILDER_ERROR_UNHANDLED_TAG

The input contained a tag that GtkBuilder can’t handle.

 

GTK_BUILDER_ERROR_MISSING_ATTRIBUTE

An attribute that is required by GtkBuilder was missing.

 

GTK_BUILDER_ERROR_INVALID_ATTRIBUTE

GtkBuilder found an attribute that it doesn’t understand.

 

GTK_BUILDER_ERROR_INVALID_TAG

GtkBuilder found a tag that it doesn’t understand.

 

GTK_BUILDER_ERROR_MISSING_PROPERTY_VALUE

A required property value was missing.

 

GTK_BUILDER_ERROR_INVALID_VALUE

GtkBuilder couldn’t parse some attribute value.

 

GTK_BUILDER_ERROR_VERSION_MISMATCH

The input file requires a newer version of GTK+.

 

GTK_BUILDER_ERROR_DUPLICATE_ID

An object id occurred twice.

 

GTK_BUILDER_ERROR_OBJECT_TYPE_REFUSED

A specified object type is of the same type or derived from the type of the composite class being extended with builder XML.

 

GTK_BUILDER_ERROR_TEMPLATE_MISMATCH

The wrong type was specified in a composite class’s template XML

 

GTK_BUILDER_ERROR_INVALID_PROPERTY

The specified property is unknown for the object class.

 

GTK_BUILDER_ERROR_INVALID_SIGNAL

The specified signal is unknown for the object class.

 

GTK_BUILDER_ERROR_INVALID_ID

An object id is unknown.

 

GTK_BUILDER_ERROR_INVALID_FUNCTION

A function could not be found. This often happens when symbols are set to be kept private. Compiling code with -rdynamic or using the gmodule-export-2.0 pkgconfig module can fix this problem.

 

GTK_BUILDER_ERROR

#define GTK_BUILDER_ERROR                (gtk_builder_error_quark ())

Property Details

The “current-object” property

  “current-object”           GObject *

The object the builder is evaluating for.

Owner: GtkBuilder

Flags: Read / Write


The “scope” property

  “scope”                    GtkBuilderScope *

The scope the builder is operating in

Owner: GtkBuilder

Flags: Read / Write / Construct


The “translation-domain” property

  “translation-domain”       gchar *

The translation domain used when translating property values that have been marked as translatable in interface descriptions. If the translation domain is NULL, GtkBuilder uses gettext(), otherwise g_dgettext().

Owner: GtkBuilder

Flags: Read / Write

Default value: NULL