2 <!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
3 "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" [
5 <refentry id="gtk-question-index">
7 <refentrytitle>Common Questions</refentrytitle>
8 <manvolnum>3</manvolnum>
9 <refmiscinfo>Common Questions</refmiscinfo>
13 <refname>Common Questions</refname>
15 Find answers to common questions in the GTK+ manual
20 <title>Questions and Answers</title>
23 This is an "index" of the reference manual organized by common "How do
24 I..." questions. If you aren't sure which documentation to read for
25 the question you have, this list is a good place to start.
30 <qandadiv><title>General</title>
34 How do I get started with GTK+?
38 The GTK+ <ulink url="http://www.gtk.org">website</ulink> offers a
39 <ulink url="http://www.gtk.org/tutorial">tutorial</ulink> and a
40 <ulink url="http://www.gtk.org/faq">FAQ</ulink>. More documentation ranging
41 from whitepapers to online books can be found at the
42 <ulink url="http://library.gnome.org/devel/">GNOME developer's site</ulink>.
43 After studying these materials you should be well prepared to come back to
44 this reference manual for details.
50 Where can I get help with GTK+, submit a bug report, or make a feature
57 See the <link linkend="gtk-resources">documentation on this topic</link>.
66 <question><para>How do I port from one GTK+
67 version to another?</para></question>
72 See <xref linkend="gtk-migrating-2-to-3"/>.
73 You may also find useful information in the documentation for
74 specific widgets and functions.
78 If you have a question not covered in the manual, feel free to
79 ask on the mailing lists and please <ulink
80 url="http://bugzilla.gnome.org">file a bug report</ulink> against the
91 How does memory management work in GTK+? Should I free data returned
98 See the documentation for #GObject and #GInitiallyUnowned. For #GObject note
99 specifically g_object_ref() and g_object_unref(). #GInitiallyUnowned is a
100 subclass of #GObject so the same points apply, except that it has a "floating"
101 state (explained in its documentation).
105 For strings returned from functions, they will be declared "const" (using
106 #G_CONST_RETURN) if they should not be freed. Non-const strings should be
107 freed with g_free(). Arrays follow the same rule. (If you find an exception
108 to the rules, please report a bug to <ulink
109 url="http://bugzilla.gnome.org">http://bugzilla.gnome.org</ulink>.)
118 Why does my program leak memory, if I destroy a widget immediately
125 If <structname>GtkFoo</structname> isn't a toplevel window, then
126 <informalexample><programlisting>
127 foo = gtk_foo_new (<!-- -->);
128 gtk_widget_destroy (foo);
129 </programlisting></informalexample>
130 is a memory leak, because no one assumed the initial floating
131 reference. If you are using a widget and you aren't immediately
132 packing it into a container, then you probably want standard
133 reference counting, not floating reference counting.
137 To to get this, you must acquire a reference to the widget and drop the
138 floating reference (<quote>ref and sink</quote> in GTK+ parlance) after
140 <informalexample><programlisting>
141 foo = gtk_foo_new (<!-- -->);
142 g_object_ref_sink (foo);
143 </programlisting></informalexample>
144 When you want to get rid of the widget, you must call gtk_widget_destroy()
145 to break any external connections to the widget before dropping your
147 <informalexample><programlisting>
148 gtk_widget_destroy (foo);
149 g_object_unref (foo);
150 </programlisting></informalexample>
151 When you immediately add a widget to a container, it takes care of
152 assuming the initial floating reference and you don't have to worry
153 about reference counting at all ... just call gtk_widget_destroy()
154 to get rid of the widget.
161 How do I use GTK+ with threads?
167 This is covered in the <link linkend="gdk-Threads">GDK threads
168 documentation</link>. See also the <link linkend="glib-Threads">GThread</link>
169 documentation for portable threading primitives.
178 How do I internationalize a GTK+ program?
183 Most people use <ulink url="http://www.gnu.org/software/gettext/">GNU
184 gettext</ulink>, already required in order to install GLib. On a UNIX
185 or Linux system with gettext installed, type <literal>info gettext</literal>
186 to read the documentation.
189 The short checklist on how to use gettext is: call bindtextdomain() so gettext
190 can find the files containing your translations, call textdomain() to set the
191 default translation domain, call bind_textdomain_codeset() to request that
192 all translated strings are returned in UTF-8, then call gettext() to look up
193 each string to be translated in the default domain.
194 Conventionally, people define macros as follows for convenience:
197 #define _(x) gettext (x)
201 You use N_() (N stands for no-op) to mark a string for translation in a
202 context where a function call to gettext() is not allowed, such as in an
204 You eventually have to call gettext() on the string to actually fetch the
205 translation. _() both marks the string for translation and actually
209 Nowadays, GLib provides the common shorthand macros in the header file
210 <filename>gi18n.h</filename>, so you don't have to define them yourself,
211 just include that header.
214 Code using these macros ends up looking like this:
217 #include <gi18n.h>
219 static const char *global_variable = N_("Translate this string");
227 label1 = gtk_label_new (_("Another string to translate"));
228 label2 = gtk_label_new (_(global_variable));
234 Libraries using gettext should use dgettext() instead of gettext(), which
235 allows them to specify the translation domain each time they ask for a
236 translation. Libraries should also avoid calling textdomain(), since they
237 will be specifying the domain instead of using the default. For dgettext()
238 the _() macro can be defined as:
241 #define _(x) dgettext ("MyDomain", x)
246 Again, GLib comes with the <filename>gi18n-lib.h</filename>, saving you the
247 trouble of defining the macros by hand. The macros in that header expect the
248 translation domain to be specified by the %GETTEXT_PACKAGE macro.
256 How do I use non-ASCII characters in GTK+ programs ?
262 GTK+ uses <ulink url="http://www.unicode.org">Unicode</ulink> (more exactly
263 UTF-8) for all text. UTF-8 encodes each Unicode codepoint as a sequence of
264 one to six bytes and has a number of nice properties which make it a good
265 choice for working with Unicode text in C programs:
268 ASCII characters are encoded by their familiar ASCII codepoints.
271 ASCII characters never appear as part of any other character.
274 The zero byte doesn't occur as part of a character, so that UTF-8 strings
275 can be manipulated with the usual C library functions for handling
276 zero-terminated strings.
279 More information about Unicode and UTF-8 can be found in the
280 <ulink url="http://www.cl.cam.ac.uk/~mgk25/unicode.html">UTF-8 and Unicode i
281 FAQ for Unix/Linux</ulink>.
282 GLib provides functions for converting strings between UTF-8 and other
283 encodings, see g_locale_to_utf8() and g_convert().
286 Text coming from external sources (e.g. files or user input), has to be
287 converted to UTF-8 before being handed over to GTK+. The following example
288 writes the content of a IS0-8859-1 encoded text file to
289 <literal>stdout</literal>:
290 <informalexample><programlisting>
291 gchar *text, *utf8_text;
293 GError *error = NULL;
295 if (g_file_get_contents (filename, &text, &length, NULL))
297 utf8_text = g_convert (text, length, "UTF-8", "ISO-8859-1",
298 NULL, NULL, &error);
301 fprintf ("Couldn't convert file %s to UTF-8\n", filename);
302 g_error_free (error);
308 fprintf (stderr, "Unable to read file %s\n", filename);
309 </programlisting></informalexample>
312 For string literals in the source code, there are several alternatives for
313 handling non-ASCII content:
315 <varlistentry><term>direct UTF-8</term>
317 If your editor and compiler are capable of handling UTF-8 encoded sources,
318 it is very convenient to simply use UTF-8 for string literals, since it allows
319 you to edit the strings in "wysiwyg". Note that choosing this option may
320 reduce the portability of your code.
324 <varlistentry><term>escaped UTF-8</term>
326 Even if your toolchain can't handle UTF-8 directly, you can still encode string
327 literals in UTF-8 by using octal or hexadecimal escapes like
328 <literal>\212</literal> or <literal>\xa8</literal> to
329 encode each byte. This is portable, but modifying the escaped strings is not
330 very convenient. Be careful when mixing hexadecimal escapes with ordinary text;
331 <literal>"\xa8abcd"</literal> is a string of length 1 !
335 <varlistentry><term>runtime conversion</term>
337 If the string literals can be represented in an encoding which your toolchain
338 can handle (e.g. IS0-8859-1), you can write your source files in that encoding
339 and use g_convert() to convert the strings to UTF-8 at runtime. Note that this
340 has some runtime overhead, so you may want to move the conversion out of inner
345 Here is an example showing the three approaches using the copyright sign
346 © which has Unicode and ISO-8859-1 codepoint 169 and is represented in
347 UTF-8 by the two bytes 194, 169:
348 <informalexample><programlisting>
349 g_print ("direct UTF-8: ©");
350 g_print ("escaped UTF-8: \302\251");
351 text = g_convert ("runtime conversion: ©", -1, "ISO-8859-1", "UTF-8", NULL, NULL, NULL);
354 </programlisting></informalexample>
357 If you are using gettext() to localize your application, you need to
358 call bind_textdomain_codeset() to ensure that translated strings are
359 returned in UTF-8 encoding.
366 How do I use GTK+ with C++?
371 There are two ways to approach this. The GTK+ header files use the subset
372 of C that's also valid C++, so you can simply use the normal GTK+ API
373 in a C++ program. Alternatively, you can use a "C++ binding"
374 such as <ulink url="http://gtkmm.sourceforge.net/">gtkmm</ulink>
375 which provides a native C++ API.
378 When using GTK+ directly, keep in mind that only functions can be
379 connected to signals, not methods. So you will need to use global
380 functions or "static" class functions for signal connections.
383 Another common issue when using GTK+ directly is that
384 C++ will not implicitly convert an integer to an enumeration.
385 This comes up when using bitfields; in C you can write the following
389 gdk_window_set_events (gdk_window,
390 GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
393 while in C++ you must write:
396 gdk_window_set_events (gdk_window,
397 (GdkEventMask) GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
400 There are very few functions that require this cast, however.
408 How do I use GTK+ with other non-C languages?
413 See the <ulink url="http://www.gtk.org/bindings.html">list of language
414 bindings</ulink> on <ulink
415 url="http://www.gtk.org">http://www.gtk.org</ulink>.
424 How do I load an image or animation from a file?
430 To load an image file straight into a display widget, use
431 gtk_image_new_from_file() <footnote><para> If the file load fails,
432 gtk_image_new_from_file() will display no image graphic — to detect
433 a failed load yourself, use gdk_pixbuf_new_from_file() directly, then
434 gtk_image_new_from_pixbuf().</para></footnote>.
435 To load an image for another purpose, use gdk_pixbuf_new_from_file(). To i
436 load an animation, use gdk_pixbuf_animation_new_from_file().
437 gdk_pixbuf_animation_new_from_file() can also load non-animated images, so
438 use it in combination with gdk_pixbuf_animation_is_static_image() to load a
439 file of unknown type.
442 To load an image or animation file asynchronously (without blocking), use
456 To draw a piece of text, use a Pango layout and gdk_draw_layout(),
457 using code like the following:
460 layout = gtk_widget_create_pango_layout (widget, text);
461 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
462 pango_layout_set_font_description (layout, fontdesc);
463 gdk_draw_layout (..., layout);
464 pango_font_description_free (fontdesc);
465 g_object_unref (layout);
468 Do not use the deprecated #GdkFont and gdk_draw_text().
472 See also the "Text Handling in GTK 2" section of
473 <ulink url="http://developer.gnome.org/dotplan/porting/">Porting applications
474 to the GNOME 2.0 platform</ulink>.
483 How do I measure the size of a piece of text ?
489 To obtain the size of a piece of text, use a Pango layout and
490 pango_layout_get_pixel_size(), using code like the following:
493 layout = gtk_widget_create_pango_layout (widget, text);
494 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
495 pango_layout_set_font_description (layout, fontdesc);
496 pango_layout_get_pixel_size (layout, &width, &height);
497 pango_font_description_free (fontdesc);
498 g_object_unref (layout);
501 Do not use the deprecated function gdk_text_width().
505 See also the "Text Handling in GTK 2" section of
506 <ulink url="http://developer.gnome.org/dotplan/porting/">Porting applications
507 to the GNOME 2.0 platform</ulink>.
515 Why are types not registered if I use their <literal>GTK_TYPE_BLAH</literal>
522 The <literal>GTK_TYPE_BLAH</literal> macros are defined as calls to
523 <literal>gtk_blah_get_type()</literal>, and the <literal>_get_type()</literal> i
524 functions are declared as %G_GNUC_CONST which allows the compiler to optimize
525 the call away if it appears that the value is not being used.
529 A common workaround for this problem is to store the result in a volatile
530 variable, which keeps the compiler from optimizing the call away.
531 <informalexample><programlisting>
532 volatile GType dummy = GTK_TYPE_BLAH;
533 </programlisting></informalexample>
541 How do I create a transparent toplevel window ?
547 To make a window transparent, it needs to use a visual which supports that.
548 This is done by getting the RGBA colormap of the screen with
549 gdk_screen_get_rgba_colormap() and setting it on the window. Note that
550 gdk_screen_get_rgba_colormap() will return %NULL if transparent windows
551 are not supported on the screen; also note that this may change from
552 screen to screen, so it needs to be repeated whenever the window is moved
553 to a different screen.
554 <informalexample><programlisting>
555 GdkColormap *colormap;
557 colormap = gdk_screen_get_rgba_colormap (screen);
559 colormap = gdk_screen_get_rgb_colormap (screen);
561 gtk_widget_set_colormap (widget, colormap);
562 </programlisting></informalexample>
563 One possibility to fill the alpha channel on the window is to use
564 gdk_draw_rgb_32_image().
567 Note that the presence of an RGBA visual is no guarantee that the
568 window will actually appear transparent on screen. On X11, this
569 requires a compositing manager to be running. See
570 gtk_widget_is_composited() for a way to find out if the alpha
571 channel will be respected.
578 <qandadiv><title>Which widget should I use...</title>
582 ...for lists and trees?
587 See <link linkend="TreeWidget">tree widget overview</link> — you
588 should use the #GtkTreeView widget. (A list is just a tree with no branches,
589 so the tree widget is used for lists as well.) Do not use the deprecated
590 widgets #GtkTree or #GtkCList/#GtkCTree in newly-written code, they are
591 less flexible and result in an inferior user interface.
598 ...for multi-line text display or editing?
603 See <link linkend="TextWidget">text widget overview</link> — you
604 should use the #GtkTextView widget. Do not use the deprecated widget #GtkText
605 in newly-written code, it has a number of problems that are best avoided.
608 If you only have a small amount of text, #GtkLabel may also be appropriate
609 of course. It can be made selectable with gtk_label_set_selectable(). For a
610 single-line text entry, see #GtkEntry.
618 ...to display an image or animation?
623 #GtkImage can display images in just about any format GTK+ understands.
624 You can also use #GtkDrawingArea if you need to do something more complex,
625 such as draw text or graphics over the top of the image.
632 ...for presenting a set of mutually-exclusive choices, where Windows
633 would use a combo box?
638 With GTK+, a #GtkComboBox is the recommended widget to use for this use case.
639 This widget looks like either a combo box or the current option menu, depending
640 on the current theme. If you need an editable text entry, use #GtkComboBoxEntry.
647 <qandadiv><title>GtkWidget</title>
651 How do I change the color of a widget?
655 See gtk_widget_modify_fg(), gtk_widget_modify_bg(), gtk_widget_modify_base(),
656 and gtk_widget_modify_text(). See <link linkend="gtk-Resource-Files">GTK+
657 resource files</link> for more discussion. You can also change widget color
658 by installing a resource file and parsing it with gtk_rc_add_default_file().
659 The advantage of a resource file is that users can then override the
663 <para>To change the background color for widgets such as #GtkLabel that have
664 no background, place them in a #GtkEventBox and set the background of the
671 How do I change the font of a widget?
675 This has several possible answers, depending on what exactly you want to
676 achieve. One option is gtk_widget_modify_font(). Note that this function
677 can be used to change only the font size, as in the following example:
679 PangoFontDesc *font_desc = pango_font_description_new (<!-- -->);
680 pango_font_description_set_size (font_desc, 40);
681 gtk_widget_modify_font (widget, font);
682 pango_font_description_free (font_desc);
686 If you want to make the text of a label larger, you can use
687 gtk_label_set_markup():
689 gtk_label_set_markup (label, "<big>big text</big>");
691 This is preferred for many apps because it's a relative size to the
692 user's chosen font size. See g_markup_escape_text() if you are
693 constructing such strings on the fly.
696 You can also change the font of a widget by putting
698 gtk-font-name = "Sans 30"
700 in a resource file and parsing it with gtk_rc_add_default_file().
701 The advantage of a resource file is that users can then override the font you
702 have chosen. See <link linkend="gtk-Resource-Files">GTK+ resource files</link>
710 How do I disable/ghost/desensitize a widget?
713 <answer><para> In GTK+ a disabled widget is termed "insensitive." See
714 gtk_widget_set_sensitive().
721 <qandadiv><title>GtkTextView</title>
725 How do I get the contents of the entire text widget as a string?
729 See gtk_text_buffer_get_bounds() and gtk_text_buffer_get_text()
730 or gtk_text_iter_get_text().
733 <informalexample><programlisting>
734 GtkTextIter start, end;
735 GtkTextBuffer *buffer;
738 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view));
739 gtk_text_buffer_get_bounds (buffer, &start, &end);
740 text = gtk_text_iter_get_text (&start, &end);
743 </programlisting></informalexample>
749 How do I make a text widget display its complete contents in a specific font?
753 If you use gtk_text_buffer_insert_with_tags() with appropriate tags to select
754 the font, the inserted text will have the desired appearance, but text typed
755 in by the user before or after the tagged block will appear in the default
759 To ensure that all text has the desired appearance, use gtk_widget_modify_font()
760 to change the default font for the widget.
767 How do I make a text view scroll to the end of the buffer automatically ?
773 A good way to keep a text buffer scrolled to the end is to place a
774 <link linkend="GtkTextMark">mark</link> at the end of the buffer, and
775 give it right gravity. The gravity has the effect that text inserted
776 at the mark gets inserted <emphasis>before</emphasis>, keeping the mark
781 To ensure that the end of the buffer remains visible, use
782 gtk_text_view_scroll_to_mark() to scroll to the mark after
787 The gtk-demo application contains an example of this technique.
795 <qandadiv><title>#GtkTreeView</title>
799 How do I associate some data with a row in the tree?
804 Remember that the #GtkTreeModel columns don't necessarily have to be displayed.
805 So you can put non-user-visible data in your model just like any other data,
806 and retrieve it with gtk_tree_model_get(). See the
807 <link linkend="TreeWidget">tree widget overview</link>.
814 What's the #GtkTreeView equivalent of gtk_clist_find_row_from_data()?
819 As there is no separate data column in the #GtkTreeModel, there's no
820 built in function to find the iter from data. You can write a custom
821 searching function to walk the tree and find the data, or use
822 gtk_tree_model_foreach().
829 How do I put an image and some text in the same column?
834 You can pack more than one #GtkCellRenderer into a single #GtkTreeViewColumn
835 using gtk_tree_view_column_pack_start() or gtk_tree_view_column_pack_end().
836 So pack both a #GtkCellRendererPixbuf and a #GtkCellRendererText into the
844 I can set data easily on my #GtkTreeStore/#GtkListStore models using
845 gtk_list_store_set() and gtk_tree_store_set(), but can't read it back?
850 Both the #GtkTreeStore and the #GtkListStore implement the #GtkTreeModel
851 interface. Consequentially, the can use any function this interface
852 implements. The easiest way to read a set of data back is to use
853 gtk_tree_model_get().
860 How do I change the way that numbers are formatted by #GtkTreeView?
863 Use gtk_tree_view_insert_column_with_data_func()
864 or gtk_tree_view_column_set_cell_data_func() and do the conversion from i
865 number to string yourself (with, say, g_strdup_printf()).
869 The following example demonstrates this:
870 <informalexample><programlisting>
877 GtkListStore *mycolumns;
878 GtkTreeView *treeview;
881 my_cell_double_to_text (GtkTreeViewColumn *tree_column,
882 GtkCellRenderer *cell,
883 GtkTreeModel *tree_model,
887 GtkCellRendererText *cell_text = (GtkCellRendererText *)cell;
891 /* Get the double value from the model. */
892 gtk_tree_model_get (tree_model, iter, (gint)data, &d, -1);
893 /* Now we can format the value ourselves. */
894 text = g_strdup_printf ("%.2f", d);
895 g_object_set (cell, "text", text, NULL);
900 set_up_new_columns (GtkTreeView *myview)
902 GtkCellRendererText *renderer;
903 GtkTreeViewColumn *column;
904 GtkListStore *mycolumns;
906 /* Create the data model and associate it with the given TreeView */
907 mycolumns = gtk_list_store_new (N_COLUMNS, G_TYPE_DOUBLE);
908 gtk_tree_view_set_model (myview, GTK_TREE_MODEL (mycolumns));
910 /* Create a GtkCellRendererText */
911 renderer = gtk_cell_renderer_text_new (<!-- -->);
913 /* Create a new column that has a title ("Example column"),
914 * uses the above created renderer that will render the double
915 * value into text from the associated model's rows.
917 column = gtk_tree_view_column_new (<!-- -->);
918 gtk_tree_view_column_set_title (column, "Example column");
919 renderer = gtk_cell_renderer_text_new (<!-- -->);
920 gtk_tree_view_column_pack_start (column, renderer, TRUE);
922 /* Append the new column after the GtkTreeView's previous columns. */
923 gtk_tree_view_append_column (GTK_TREE_VIEW (myview), column);
924 /* Since we created the column by hand, we can set it up for our
925 * needs, e.g. set its minimum and maximum width, etc.
927 /* Set up a custom function that will be called when the column content
928 * is rendered. We use the func_data pointer as an index into our
929 * model. This is convenient when using multi column lists.
931 gtk_tree_view_column_set_cell_data_func (column, renderer,
932 my_cell_double_to_text,
933 (gpointer)DOUBLE_COLUMN, NULL);
935 </programlisting></informalexample>
941 How do I hide the expander arrows in my tree view ?
945 Set the expander-column property of the tree view to a hidden column.
946 See gtk_tree_view_set_expander_column() and gtk_tree_view_column_set_visible().
952 <qandadiv><title>Using cairo with GTK+</title>
956 How do I use cairo to draw in GTK+ applications ?
960 Use gdk_cairo_create() to obtain a cairo context for drawing
961 on a GDK window or pixmap. See <link linkend="gdk-Cairo-Interaction">Cairo
962 Interaction</link> for some more useful functions.
968 I have created a cairo context with gdk_cairo_create(), but when I
969 later use it, my drawing does not show up. Why is that ?
974 All drawing in GTK+ is normally done in an expose handler, and GTK+
975 creates a temporary pixmap for double-buffering the drawing. If you
976 create a cairo context outside the expose handler, it is backed
977 by the GDK window itself, not the double-buffering pixmap. Consequently,
978 any drawing you do with that cairo context gets overwritten at the
979 end of the expose handler, when the double-buffering pixmap is copied
983 Possible solutions to this problem are:
986 Turn off double-buffering, with gtk_widget_set_double_buffered().
987 This is not ideal, since it can cause some flickering.
990 Create the cairo context inside the expose handler. If you do this,
991 gdk_create_cairo() arranges for it to be backed by the double-buffering
992 pixmap. This is the preferred solution, and is used throughout GTK+
1002 Can I improve the performance of my application by using the
1003 Glitz backend of cairo ?
1007 No. The GDK X11 backend uses the cairo X backend (and the other
1008 GDK backends use their respective native cairo backends). The
1009 GTK+ developers believe that the best way to improving the GDK
1010 drawing performance is to optimize the cairo X backend and the
1011 relevant code paths in the X server that is uses (mostly the
1018 Can I use cairo to draw on a #GdkPixbuf ?
1022 No, at least not yet. The cairo image surface does not support the
1023 pixel format used by GdkPixbuf.