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 some
39 <ulink url="http://www.gtk.org/documentation">tutorials</ulink> and other
40 documentation (most of it about GTK+ 2.x, but mostly still applicable).
41 More documentation ranging from whitepapers to online books can be found at
42 the <ulink url="http://developer.gnome.org">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"
106 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
108 undocumented exception 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
190 gettext can find the files containing your translations, call textdomain()
191 to set the default translation domain, call bind_textdomain_codeset() to
192 request that all translated strings are returned in UTF-8, then call
193 gettext() to look up each string to be translated in the default domain.
196 <filename>gi18n.h</filename> provides the following shorthand macros for
198 Conventionally, people define macros as follows for convenience:
201 #define _(x) gettext (x)
203 #define C_(ctx,x) pgettext (ctx, x)
206 You use N_() (N stands for no-op) to mark a string for translation in
207 a location where a function call to gettext() is not allowed, such as
208 in an array initializer.
209 You eventually have to call gettext() on the string to actually fetch
210 the translation. _() both marks the string for translation and actually
212 The C_() macro (C stands for context) adds an additional context to
213 the string that is marked for translation, which can help to disambiguate
214 short strings that might need different translations in different
215 parts of your program.
218 Code using these macros ends up looking like this:
221 #include <gi18n.h>
223 static const char *global_variable = N_("Translate this string");
231 label1 = gtk_label_new (_("Another string to translate"));
232 label2 = gtk_label_new (_(global_variable));
238 Libraries using gettext should use dgettext() instead of gettext(), which
239 allows them to specify the translation domain each time they ask for a
240 translation. Libraries should also avoid calling textdomain(), since
241 they will be specifying the domain instead of using the default.
244 With the convention that the macro <literal>GETTEXT_PACKAGE</literal> is
245 defined to hold your libraries translation domain,
246 <filename>gi18n-lib.h</filename> can be included to provide
247 the following convenience:
250 #define _(x) dgettext (GETTEXT_PACKAGE, x)
260 How do I use non-ASCII characters in GTK+ programs ?
266 GTK+ uses <ulink url="http://www.unicode.org">Unicode</ulink> (more exactly
267 UTF-8) for all text. UTF-8 encodes each Unicode codepoint as a sequence of
268 one to six bytes and has a number of nice properties which make it a good
269 choice for working with Unicode text in C programs:
272 ASCII characters are encoded by their familiar ASCII codepoints.
275 ASCII characters never appear as part of any other character.
278 The zero byte doesn't occur as part of a character, so that UTF-8 strings
279 can be manipulated with the usual C library functions for handling
280 zero-terminated strings.
283 More information about Unicode and UTF-8 can be found in the
284 <ulink url="http://www.cl.cam.ac.uk/~mgk25/unicode.html">UTF-8 and Unicode
285 FAQ for Unix/Linux</ulink>.
286 GLib provides functions for converting strings between UTF-8 and other
287 encodings, see g_locale_to_utf8() and g_convert().
290 Text coming from external sources (e.g. files or user input), has to be
291 converted to UTF-8 before being handed over to GTK+. The following example
292 writes the content of a IS0-8859-1 encoded text file to
293 <literal>stdout</literal>:
294 <informalexample><programlisting>
295 gchar *text, *utf8_text;
297 GError *error = NULL;
299 if (g_file_get_contents (filename, &text, &length, NULL))
301 utf8_text = g_convert (text, length, "UTF-8", "ISO-8859-1",
302 NULL, NULL, &error);
305 fprintf ("Couldn't convert file %s to UTF-8\n", filename);
306 g_error_free (error);
312 fprintf (stderr, "Unable to read file %s\n", filename);
313 </programlisting></informalexample>
316 For string literals in the source code, there are several alternatives for
317 handling non-ASCII content:
319 <varlistentry><term>direct UTF-8</term>
321 If your editor and compiler are capable of handling UTF-8 encoded sources,
322 it is very convenient to simply use UTF-8 for string literals, since it
323 allows you to edit the strings in "wysiwyg". Note that choosing this option
324 may reduce the portability of your code.
328 <varlistentry><term>escaped UTF-8</term>
330 Even if your toolchain can't handle UTF-8 directly, you can still encode
331 string literals in UTF-8 by using octal or hexadecimal escapes like
332 <literal>\212</literal> or <literal>\xa8</literal> to encode each byte.
333 This is portable, but modifying the escaped strings is not very convenient.
334 Be careful when mixing hexadecimal escapes with ordinary text;
335 <literal>"\xa8abcd"</literal> is a string of length 1 !
339 <varlistentry><term>runtime conversion</term>
341 If the string literals can be represented in an encoding which your
342 toolchain can handle (e.g. IS0-8859-1), you can write your source files
343 in that encoding and use g_convert() to convert the strings to UTF-8 at
344 runtime. Note that this has some runtime overhead, so you may want to move
345 the conversion out of inner loops.
349 Here is an example showing the three approaches using the copyright sign
350 © which has Unicode and ISO-8859-1 codepoint 169 and is represented
351 in UTF-8 by the two bytes 194, 169, or <literal>"\302\251"</literal> as
353 <informalexample><programlisting>
354 g_print ("direct UTF-8: ©");
355 g_print ("escaped UTF-8: \302\251");
356 text = g_convert ("runtime conversion: ©", -1, "ISO-8859-1", "UTF-8", NULL, NULL, NULL);
359 </programlisting></informalexample>
362 If you are using gettext() to localize your application, you need to
363 call bind_textdomain_codeset() to ensure that translated strings are
364 returned in UTF-8 encoding.
371 How do I use GTK+ with C++?
376 There are two ways to approach this. The GTK+ header files use the subset
377 of C that's also valid C++, so you can simply use the normal GTK+ API
378 in a C++ program. Alternatively, you can use a "C++ binding"
379 such as <ulink url="http://gtkmm.sourceforge.net/">gtkmm</ulink>
380 which provides a native C++ API.
383 When using GTK+ directly, keep in mind that only functions can be
384 connected to signals, not methods. So you will need to use global
385 functions or "static" class functions for signal connections.
388 Another common issue when using GTK+ directly is that
389 C++ will not implicitly convert an integer to an enumeration.
390 This comes up when using bitfields; in C you can write the following
394 gdk_window_set_events (gdk_window,
395 GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
398 while in C++ you must write:
401 gdk_window_set_events (gdk_window,
402 (GdkEventMask) GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
405 There are very few functions that require this cast, however.
413 How do I use GTK+ with other non-C languages?
418 See the <ulink url="http://www.gtk.org/bindings.html">list of language
419 bindings</ulink> on <ulink
420 url="http://www.gtk.org">http://www.gtk.org</ulink>.
429 How do I load an image or animation from a file?
435 To load an image file straight into a display widget, use
436 gtk_image_new_from_file() <footnote><para> If the file load fails,
437 gtk_image_new_from_file() will display no image graphic — to detect
438 a failed load yourself, use gdk_pixbuf_new_from_file() directly, then
439 gtk_image_new_from_pixbuf().</para></footnote>.
440 To load an image for another purpose, use gdk_pixbuf_new_from_file(). To i
441 load an animation, use gdk_pixbuf_animation_new_from_file().
442 gdk_pixbuf_animation_new_from_file() can also load non-animated images, so
443 use it in combination with gdk_pixbuf_animation_is_static_image() to load a
444 file of unknown type.
447 To load an image or animation file asynchronously (without blocking), use
461 To draw a piece of text, use a Pango layout and pango_cairo_show_layout().
464 layout = gtk_widget_create_pango_layout (widget, text);
465 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
466 pango_layout_set_font_description (layout, fontdesc);
467 pango_cairo_show_layout (cr, layout);
468 pango_font_description_free (fontdesc);
469 g_object_unref (layout);
476 <ulink url="http://developer.gnome.org/pango/stable/pango-Cairo-Rendering.html">Cairo Rendering</ulink>
477 section of <ulink url="http://developer.gnome.org/pango/stable/">Pango manual</ulink>.
486 How do I measure the size of a piece of text ?
492 To obtain the size of a piece of text, use a Pango layout and
493 pango_layout_get_pixel_size(), using code like the following:
496 layout = gtk_widget_create_pango_layout (widget, text);
497 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
498 pango_layout_set_font_description (layout, fontdesc);
499 pango_layout_get_pixel_size (layout, &width, &height);
500 pango_font_description_free (fontdesc);
501 g_object_unref (layout);
508 <ulink url="http://developer.gnome.org/pango/stable/pango-Layout-Objects.html">Layout Objects</ulink>
509 section of <ulink url="http://developer.gnome.org/pango/stable/">Pango manual</ulink>.
517 Why are types not registered if I use their <literal>GTK_TYPE_BLAH</literal>
524 The <literal>GTK_TYPE_BLAH</literal> macros are defined as calls to
525 <literal>gtk_blah_get_type()</literal>, and the <literal>_get_type()</literal> i
526 functions are declared as %G_GNUC_CONST which allows the compiler to optimize
527 the call away if it appears that the value is not being used.
531 A common workaround for this problem is to store the result in a volatile
532 variable, which keeps the compiler from optimizing the call away.
533 <informalexample><programlisting>
534 volatile GType dummy = GTK_TYPE_BLAH;
535 </programlisting></informalexample>
543 How do I create a transparent toplevel window ?
549 To make a window transparent, it needs to use a visual which supports that.
550 This is done by getting the RGBA visual of the screen with
551 gdk_screen_get_rgba_visual() and setting it on the window. Note that
552 gdk_screen_get_rgba_visual() will return %NULL if transparent windows
553 are not supported on the screen, you should fall back to
554 gdk_screen_get_system_visual() in that case. Additionally, note that this
555 will change from screen to screen, so it needs to be repeated whenever the
556 window is moved to a different screen.
557 <informalexample><programlisting>
560 visual = gdk_screen_get_rgba_visual (screen);
562 visual = gdk_screen_get_system_visual (screen);
564 gtk_widget_set_visual (GTK_WIDGET (window), visual);
565 </programlisting></informalexample>
566 To fill the alpha channel on the window simply use cairos
567 RGBA drawing capabilities.
570 Note that the presence of an RGBA visual is no guarantee that the
571 window will actually appear transparent on screen. On X11, this
572 requires a compositing manager to be running. See
573 gtk_widget_is_composited() for a way to find out if the alpha
574 channel will be respected.
581 <qandadiv><title>Which widget should I use...</title>
585 ...for lists and trees?
590 See <link linkend="TreeWidget">tree widget overview</link> — you
591 should use the #GtkTreeView widget. (A list is just a tree with no branches,
592 so the tree widget is used for lists as well).
599 ...for multi-line text display or editing?
604 See <link linkend="TextWidget">text widget overview</link> — you
605 should use the #GtkTextView widget.
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 the
641 #GtkComboBox:has-entry property.
648 <qandadiv><title>GtkWidget</title>
652 How do I change the color of a widget?
656 See gtk_widget_override_color() and gtk_widget_override_background_color().
657 You can also change the appearance of a widget by installing a
658 custom style provider, see gtk_style_context_add_provider().
661 <para>To change the background color for widgets such as #GtkLabel that
662 have no background, place them in a #GtkEventBox and set the background
669 How do I change the font of a widget?
673 This has several possible answers, depending on what exactly you want to
674 achieve. One option is gtk_widget_override_font().
675 <informalexample><programlisting>
676 PangoFontDesc *font_desc = pango_font_description_new (<!-- -->);
677 pango_font_description_set_size (font_desc, 40);
678 gtk_widget_override_font (widget, font);
679 pango_font_description_free (font_desc);
680 </programlisting></informalexample>
683 If you want to make the text of a label larger, you can use
684 gtk_label_set_markup():
685 <informalexample><programlisting>
686 gtk_label_set_markup (label, "<big>big text</big>");
687 </programlisting></informalexample>
688 This is preferred for many apps because it's a relative size to the
689 user's chosen font size. See g_markup_escape_text() if you are
690 constructing such strings on the fly.
693 You can also change the font of a widget by putting
699 in a CSS file, loading it with gtk_css_provider_load_from_file(), and
700 adding the provider with gtk_style_context_add_provider_for_screen().
701 To associate this style information with your widget, set a style class
702 on its #GtkStyleContext using gtk_style_context_add_class().
703 The advantage of this approach is that users can then override the font
704 you have chosen. See the #GtkStyleContext documentation for more discussion.
711 How do I disable/ghost/desensitize a widget?
715 In GTK+ a disabled widget is termed "insensitive."
716 See gtk_widget_set_sensitive().
723 <qandadiv><title>GtkTextView</title>
727 How do I get the contents of the entire text widget as a string?
731 See gtk_text_buffer_get_bounds() and gtk_text_buffer_get_text()
732 or gtk_text_iter_get_text().
735 <informalexample><programlisting>
736 GtkTextIter start, end;
737 GtkTextBuffer *buffer;
740 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view));
741 gtk_text_buffer_get_bounds (buffer, &start, &end);
742 text = gtk_text_iter_get_text (&start, &end);
745 </programlisting></informalexample>
751 How do I make a text widget display its complete contents in a specific font?
755 If you use gtk_text_buffer_insert_with_tags() with appropriate tags to
756 select the font, the inserted text will have the desired appearance, but
757 text typed in by the user before or after the tagged block will appear in
761 To ensure that all text has the desired appearance, use
762 gtk_widget_override_font() to change the default font for the widget.
769 How do I make a text view scroll to the end of the buffer automatically ?
775 A good way to keep a text buffer scrolled to the end is to place a
776 <link linkend="GtkTextMark">mark</link> at the end of the buffer, and
777 give it right gravity. The gravity has the effect that text inserted
778 at the mark gets inserted <emphasis>before</emphasis>, keeping the mark
783 To ensure that the end of the buffer remains visible, use
784 gtk_text_view_scroll_to_mark() to scroll to the mark after
789 The gtk-demo application contains an example of this technique.
797 <qandadiv><title>#GtkTreeView</title>
801 How do I associate some data with a row in the tree?
806 Remember that the #GtkTreeModel columns don't necessarily have to be
807 displayed. So you can put non-user-visible data in your model just
808 like any other data, and retrieve it with gtk_tree_model_get().
809 See the <link linkend="TreeWidget">tree widget overview</link>.
816 How do I put an image and some text in the same column?
821 You can pack more than one #GtkCellRenderer into a single #GtkTreeViewColumn
822 using gtk_tree_view_column_pack_start() or gtk_tree_view_column_pack_end().
823 So pack both a #GtkCellRendererPixbuf and a #GtkCellRendererText into the
831 I can set data easily on my #GtkTreeStore/#GtkListStore models using
832 gtk_list_store_set() and gtk_tree_store_set(), but can't read it back?
837 Both the #GtkTreeStore and the #GtkListStore implement the #GtkTreeModel
838 interface. Consequentially, you can use any function this interface
839 implements. The easiest way to read a set of data back is to use
840 gtk_tree_model_get().
847 How do I change the way that numbers are formatted by #GtkTreeView?
850 Use gtk_tree_view_insert_column_with_data_func()
851 or gtk_tree_view_column_set_cell_data_func() and do the conversion
852 from number to string yourself (with, say, g_strdup_printf()).
856 The following example demonstrates this:
857 <informalexample><programlisting>
864 GtkListStore *mycolumns;
865 GtkTreeView *treeview;
868 my_cell_double_to_text (GtkTreeViewColumn *tree_column,
869 GtkCellRenderer *cell,
870 GtkTreeModel *tree_model,
874 GtkCellRendererText *cell_text = (GtkCellRendererText *)cell;
878 /* Get the double value from the model. */
879 gtk_tree_model_get (tree_model, iter, (gint)data, &d, -1);
880 /* Now we can format the value ourselves. */
881 text = g_strdup_printf ("%.2f", d);
882 g_object_set (cell, "text", text, NULL);
887 set_up_new_columns (GtkTreeView *myview)
889 GtkCellRendererText *renderer;
890 GtkTreeViewColumn *column;
891 GtkListStore *mycolumns;
893 /* Create the data model and associate it with the given TreeView */
894 mycolumns = gtk_list_store_new (N_COLUMNS, G_TYPE_DOUBLE);
895 gtk_tree_view_set_model (myview, GTK_TREE_MODEL (mycolumns));
897 /* Create a GtkCellRendererText */
898 renderer = gtk_cell_renderer_text_new (<!-- -->);
900 /* Create a new column that has a title ("Example column"),
901 * uses the above created renderer that will render the double
902 * value into text from the associated model's rows.
904 column = gtk_tree_view_column_new (<!-- -->);
905 gtk_tree_view_column_set_title (column, "Example column");
906 renderer = gtk_cell_renderer_text_new (<!-- -->);
907 gtk_tree_view_column_pack_start (column, renderer, TRUE);
909 /* Append the new column after the GtkTreeView's previous columns. */
910 gtk_tree_view_append_column (GTK_TREE_VIEW (myview), column);
911 /* Since we created the column by hand, we can set it up for our
912 * needs, e.g. set its minimum and maximum width, etc.
914 /* Set up a custom function that will be called when the column content
915 * is rendered. We use the func_data pointer as an index into our
916 * model. This is convenient when using multi column lists.
918 gtk_tree_view_column_set_cell_data_func (column, renderer,
919 my_cell_double_to_text,
920 (gpointer)DOUBLE_COLUMN, NULL);
922 </programlisting></informalexample>
928 How do I hide the expander arrows in my tree view ?
932 Set the expander-column property of the tree view to a hidden column.
933 See gtk_tree_view_set_expander_column() and gtk_tree_view_column_set_visible().
939 <qandadiv><title>Using cairo with GTK+</title>
943 How do I use cairo to draw in GTK+ applications ?
947 The #GtkWidget::draw signal gets a ready-to-use cairo context
948 as parameter that you should use.
951 All drawing in GTK+ is normally done in a draw handler, and GTK+
952 creates a temporary pixmap for double-buffering the drawing.
953 It is possible to turn off double-buffering, with
954 gtk_widget_set_double_buffered(), but this is not ideal,
955 since it can cause some flickering.
962 Can I improve the performance of my application by using the
963 Glitz or GL backend of cairo ?
967 No. The GDK X11 backend uses the cairo X backend (and the other
968 GDK backends use their respective native cairo backends). The
969 GTK+ developers believe that the best way to improving the GDK
970 drawing performance is to optimize the cairo X backend and the
971 relevant code paths in the X server that is uses (mostly the
978 Can I use cairo to draw on a #GdkPixbuf ?
982 No, at least not yet. The cairo image surface does not support the
983 pixel format used by GdkPixbuf.