Common Questions

This is an index of the reference manual organized by common How do I… questions. If you aren’t sure which documentation to read for the question you have, this list is a good place to start.

General Questions

  1. How do I get started with GTK?

    The GTK website offers some tutorials and other documentation (most of it about GTK 2.x and 3.x, but still somewhat applicable). This reference manual also contains a introductory Getting Started part.

    More documentation ranging from whitepapers to online books can be found at the GNOME developer’s site. After studying these materials you should be well prepared to come back to this reference manual for details.

  2. Where can I get help with GTK, submit a bug report, or make a feature request?

    See the documentation on this topic.

  3. How do I port from one GTK version to another?

    See the migration guide. You may also find useful information in the documentation for specific widgets and functions. If you have a question not covered in the manual, feel free to ask, and please file a bug report against the documentation.

  4. How does memory management work in GTK? Should I free data returned from functions?

    See the documentation for GObject and GInitiallyUnowned. For GObject note specifically g_object_ref() and g_object_unref(). GInitiallyUnowned is a subclass of GObject so the same points apply, except that it has a floating state (explained in its documentation).

    For strings returned from functions, they will be declared const if they should not be freed. Non-const strings should be freed with g_free(). Arrays follow the same rule. If you find an undocumented exception to the rules, please file a bug report..

    The transfer annotations for gobject-introspection that are part of the documentation can provide useful hints for memory handling semantics as well.

  5. Why does my program leak memory, if I destroy a widget immediately after creating it ?

    If GtkFoo isn’t a toplevel window, then

    foo = gtk_foo_new();
    g_object_unref (foo);
    

    is a memory leak, because no one assumed the initial floating reference (you will get a warning about this too). If you are using a widget and you aren’t immediately packing it into a container, then you probably want standard reference counting, not floating reference counting.

    To get this, you must acquire a reference to the widget and drop the floating reference (ref and sink in GObject parlance) after creating it:

    foo = gtk_foo_new();
    g_object_ref_sink (foo);
    

    When you immediately add a widget to a container, it takes care of assuming the initial floating reference and you don’t have to worry about reference counting at all … just remove the widget from the container to get rid of it.

  6. How do I use GTK with threads?

    GTK requires that all GTK API calls are made from the same thread in which the GtkApplication was created, or gtk_init() was called (the main thread).

    If you want to take advantage of multi-threading in a GTK application, it is usually best to send long-running tasks to worker threads, and feed the results back to the main thread using g_idle_add() or GAsyncQueue. GIO offers useful tools for such an approach such as GTask.

  7. How do I internationalize a GTK program?

    Most people use GNU gettext, already required in order to install GLib. On a UNIX or Linux system with gettext installed, type info gettext to read the documentation.

    The short checklist on how to use gettext is: call bindtextdomain() so gettext can find the files containing your translations, call textdomain() to set the default translation domain, call bind_textdomain_codeset() to request that all translated strings are returned in UTF-8, then call gettext() to look up each string to be translated in the default domain.

    gi18n.h provides the following shorthand macros for convenience. Conventionally, people define macros as follows for convenience:

    #define  _(x)     gettext (x)
    #define N_(x)     x
    #define C_(ctx,x) pgettext (ctx, x)
    

    You use N_() (N stands for no-op) to mark a string for translation in a location where a function call to gettext() is not allowed, such as in an array initializer. You eventually have to call gettext() on the string to actually fetch the translation. _() both marks the string for translation and actually translates it. The C_() macro (C stands for context) adds an additional context to the string that is marked for translation, which can help to disambiguate short strings that might need different translations in different parts of your program.

    Code using these macros ends up looking like this:

    #include <gi18n.h>
    
    static const char *global_variable = N_("Translate this string");
    
    static void
    make_widgets (void)
    {
      GtkWidget *label1;
      GtkWidget *label2;
    
      label1 = gtk_label_new (_("Another string to translate"));
      label2 = gtk_label_new (_(global_variable));
    ...
    

    Libraries using gettext should use dgettext() instead of gettext(), which allows them to specify the translation domain each time they ask for a translation. Libraries should also avoid calling textdomain(), since they will be specifying the domain instead of using the default.

    With the convention that the macro GETTEXT_PACKAGE is defined to hold your libraries translation domain, gi18n-lib.h can be included to provide the following convenience:

    #define _(x) dgettext (GETTEXT_PACKAGE, x)
    
  8. How do I use non-ASCII characters in GTK programs ?

    GTK uses Unicode (more exactly UTF-8) for all text. UTF-8 encodes each Unicode codepoint as a sequence of one to six bytes and has a number of nice properties which make it a good choice for working with Unicode text in C programs:

    • ASCII characters are encoded by their familiar ASCII codepoints.

    • ASCII characters never appear as part of any other character.

    • The zero byte doesn’t occur as part of a character, so that UTF-8 string can be manipulated with the usual C library functions for handling zero-terminated strings.

    More information about Unicode and UTF-8 can be found in the UTF-8 and Unicode FAQ. GLib provides functions for converting strings between UTF-8 and other encodings, see g_locale_to_utf8() and g_convert().

    Text coming from external sources (e.g. files or user input), has to be converted to UTF-8 before being handed over to GTK. The following example writes the content of a IS0-8859-1 encoded text file to stdout:

    char *text, *utf8_text;
    gsize length;
    GError *error = NULL;
    
    if (g_file_get_contents (filename, &amp;text, &amp;length, NULL))
      {
        utf8_text = g_convert (text, length, "UTF-8", "ISO-8859-1",
                               NULL, NULL, &error);
        if (error != NULL)
          {
            fprintf ("Couldn't convert file s to UTF-8\n", filename);
            g_error_free (error);
          }
        else
          g_print (utf8_text);
      }
    else
      fprintf (stderr, "Unable to read file s\n", filename);
    

    For string literals in the source code, there are several alternatives for handling non-ASCII content:

    • Direct UTF-8

      If your editor and compiler are capable of handling UTF-8 encoded sources, it is very convenient to simply use UTF-8 for string literals, since it allows you to edit the strings in wysiwyg. Note that choosing this option may reduce the portability of your code.

    • Escaped UTF-8

      Even if your toolchain can’t handle UTF-8 directly, you can still encode string literals in UTF-8 by using octal or hexadecimal escapes like \212 or \xa8 to encode each byte. This is portable, but modifying the escaped strings is not very convenient. Be careful when mixing hexadecimal escapes with ordinary text; "\xa8abcd" is a string of length 1 !

    • Runtime conversion

      If the string literals can be represented in an encoding which your toolchain can handle (e.g. IS0-8859-1), you can write your source files in that encoding and use g_convert() to convert the strings to UTF-8 at runtime. Note that this has some runtime overhead, so you may want to move the conversion out of inner loops.

    Here is an example showing the three approaches using the copyright sign © which has Unicode and ISO-8859-1 codepoint 169 and is represented in UTF-8 by the two bytes 194, 169, or "\302\251" as a string literal:

    g_print ("direct UTF-8: ©");
    g_print ("escaped UTF-8: \302\251");
    text = g_convert ("runtime conversion: ©", -1,
                      "ISO-8859-1", "UTF-8", NULL, NULL, NULL);
    g_print (text);
    g_free (text);
    

    If you are using gettext() to localize your application, you need to call bind_textdomain_codeset() to ensure that translated strings are returned in UTF-8 encoding.

  9. How do I use GTK with C++?

    There are two ways to approach this. The GTK header files use the subset of C that’s also valid C++, so you can simply use the normal GTK API in a C++ program. Alternatively, you can use a C++ binding such as gtkmm which provides a native C++ API.

    When using GTK directly, keep in mind that only functions can be connected to signals, not methods. So you will need to use global functions or static class functions for signal connections.

    Another common issue when using GTK directly is that C++ will not implicitly convert an integer to an enumeration. This comes up when using bitfields; in C you can write the following code:

    gdk_surface_set_events (gdk_surface,
                            GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
    

    while in C++ you must write:

    gdk_surface_set_events (gdk_surface,
                            (GdkEventMask) GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
    

    There are very few functions that require this cast, however.

  10. How do I use GTK with other non-C languages?

    See the list of language bindings on the GTK website.

  11. How do I load an image or animation from a file?

    To load an image file straight into a display widget, use gtk_image_new_from_file(). To load an image for another purpose, use gdk_texture_new_from_file(). To load a video from a file, use gtk_media_file_new_for_file().

  12. How do I draw text?

    To draw a piece of text onto a cairo surface, use a Pango layout and pango_cairo_show_layout().

    layout = gtk_widget_create_pango_layout (widget, text);
    fontdesc = pango_font_description_from_string ("Luxi Mono 12");
    pango_layout_set_font_description (layout, fontdesc);
    pango_cairo_show_layout (cr, layout);
    pango_font_description_free (fontdesc);
    g_object_unref (layout);
    

    See also the Cairo Rendering section of the Pango documentation.

    To draw a piece of text in a widget snapshot() implementation, use gtk_snapshot_append_layout().

  13. How do I measure the size of a piece of text?

    To obtain the size of a piece of text, use a Pango layout and pango_layout_get_pixel_size(), using code like the following:

    layout = gtk_widget_create_pango_layout (widget, text);
    fontdesc = pango_font_description_from_string ("Luxi Mono 12");
    pango_layout_set_font_description (layout, fontdesc);
    pango_layout_get_pixel_size (layout, &amp;width, &amp;height);
    pango_font_description_free (fontdesc);
    g_object_unref (layout);
    

    See also the Layout Objects section of the Pango documentation.

  14. Why are types not registered if I use their GTK_TYPE_BLAH macro?

    The GTK_TYPE_BLAH macros are defined as calls to gtk_blah_get_type(), and the _get_type() functions are declared as G_GNUC_CONST which allows the compiler to optimize the call away if it appears that the value is not being used.

    GLib provides the g_type_ensure() function to work around this problem.

    g_type_ensure (GTK_TYPE_BLAH);
    
  15. How do I create a transparent toplevel window?

    Any toplevel window can be transparent. It is just a matter of setting a transparent background in the CSS style for it.