The GIMP Toolkit
Note: This FAQ mainly covers GTK+ 1.2
This FAQ mainly covers GTK+ 1.2. Where the text covers GTK+ 2.x this will be indicated by prefixing the text with: [GTK+ 2.x]
Before anything else: the greetings
The FAQ authors want to thank:
If we forgot you, please email us! Thanks again (I know, it's really short :)
The original authors of GTK+ were:
Since then, much has been added by others. Please see the AUTHORS file in the distribution for the GTK+ Team.
What is GTK+?
GTK+ is a small and efficient widget set designed with the general look and feel of Motif. In reality, it looks much better than Motif. It contains common widgets and some more complex widgets such as a file selection, and color selection widgets.
GTK+ provides some unique features. (At least, I know of no other widget library which provides them). For example, a button does not contain a label, it contains a child widget, which in most instances will be a label. However, the child widget can also be a pixmap, image or any combination possible the programmer desires. This flexibility is adhered to throughout the library.
What is the + in GTK+?
Peter Mattis informed the gtk mailing list that:
"I originally wrote gtk which included the three libraries, libglib, libgdk and libgtk. It featured a flat widget hierarchy. That is, you couldn't derive a new widget from an existing one. And it contained a more standard callback mechanism instead of the signal mechanism now present in gtk+. The + was added to distinguish between the original version of gtk and the new version. You can think of it as being an enhancement to the original gtk that adds object oriented features."
Does the G in GTK+, GDK and GLib stand for?
GTK+ == Gimp Toolkit
GDK == GTK+ Drawing Kit
GLib == G Library
Where is the documentation for GTK+?
In the GTK+ distribution's doc/ directory you will find the reference material for both GTK and GDK, this FAQ and the GTK Tutorial.
In addition, you can find links to HTML versions of these documents by going to http://www.gtk.org/. A packaged version of the GTK Tutorial, with SGML, HTML, Postscript, DVI and text versions can be found in ftp://ftp.gtk.org/pub/gtk/tutorial
There are now a couple of books available that deal with programming GTK+, GDK and GNOME:
Is there a mailing list (or mailing list archive) for GTK+?
Information on mailing lists relating to GTK+ can be found at: http://www.gtk.org/mailinglists.html
How to get help with GTK+
First, make sure your question isn't answered in the documentation, this FAQ or the tutorial. Done that? You're sure you've done that, right? In that case, the best place to post questions is to the GTK+ mailing list.
How to report bugs in GTK+
Bugs should be reported to the GNOME bug tracking system (http://bugzilla.gnome.org/). You will need to enter your email address and receive a password before you can use the system to register a new bug report.
There are a number of options to select and boxes to fill in when submitting a bug report. Please remember that the more information you give, the easier it will be to track the problem down. Extra information that may prove useful includes:
Is there a Windows version of GTK+?
There is an on going port of GTK+ to the Windows platform which is making impressive progress.
See http://www.iki.fi/tml/gimp/win32 for more information.
What applications have been written with GTK+?
A list of some GTK+ based application can be found on the GTK+ web server at http://www.gtk.org/apps/ and contains more than 350 applications.
Failing that, look for a project to work on for the GNOME project, http://www.gnome.org/ Write a game. Write something that is useful.
Some of these are:
I'm looking for an application to write in GTK+. How about an IRC client?
Ask on gtk-list for suggestions. There are at least three IRC clients already under development (probably more in fact. The server at http://www.forcix.cx/irc-clients.html list a bunch of them).
What do I need to run GTK+?
To compile GTK+, all you need is a C compiler (gcc) and the X Window System and associated libraries on your system.
Where can I get GTK+?
The canonical site is ftp://ftp.gtk.org/pub/gtk.
This site tends to get busy around the time of a new GTK+ release so try and use one of the mirror sites that are listed in ftp://ftp.gtk.org/etc/mirrors
Here's a few mirror sites to get you started:
How do I configure/compile GTK+?
Generally, all you will need to do is issue the commands:
in the gtk+-version/ directory.
When compiling GTK+ I get an error like: make: file `Makefile' line 456: Syntax error
Make sure that you are using GNU make (use make -v to check). There are many weird and wonderful versions of make out there, and not all of them handle the automatically generated Makefiles.
I've compiled and installed GTK+, but I can't get any programs to link with it! [GTK 2.x]
This problem is most often encountered when the GTK+ libraries can't be found or are the wrong version. Generally, the compiler will complain about an 'unresolved symbol'.
Make sure that the libraries can be found. You want to edit /etc/ld.so.conf to include the directories which contain the GTK libraries, so it looks something like:
Then you need to run /sbin/ldconfig as root. You can find what libraries GTK requires using
pkg-config gtk+-2.0 --libs
If your system doesn't use ld.so to find libraries (such as Solaris), then you will have to use the LD_LIBRARY_PATH environment variable (or compile the path into your program, which I'm not going to cover here). So, with a Bourne type shell you can do (if your GTK libraries are in /usr/local/lib):
and in a csh, you can do:
setenv LD_LIBRARY_PATH /usr/local/lib
When installing a GTK+ application, configure reports that it can't find GTK. [GTK 2.x]
There are several common reasons for this:
If none of the above help, then have a look in config.log, which is generated by ./configure as it runs. At the bottom will be the last action it took before failing. If it is a section of source code, copy the source code to a file and compile it with the line just above it in config.log. If the compilation is successful, try executing it.
Whats this CVS thing that everyone keeps talking about, and how do I access it?
CVS is the Concurrent Version System and is a very popular means of version control for software projects. It is designed to allow multiple authors to be able to simultanously operate on the same source tree. This source tree is centrally maintained, but each developer has a local mirror of this repository that they make their changes to.
The GTK+ developers use a CVS repository to store the master copy of the current development version of GTK+. As such, people wishing to contribute patches to GTK+ should generate them against the CVS version. Normal people should use the packaged releases.
The CVS toolset is available as RPM packages from the usual RedHat sites. The latest version is available at http://download.cyclic.com/pub/
Anyone can download the latest CVS version of GTK+ by using anonymous access using the following steps:
How can I contribute to GTK+?
It's simple. If something doesn't work like you think it should in a program, check the documentation to make sure you're not missing something. If it is a true bug or missing feature, track it down in the GTK+ source, change it, and then generate a patch in the form of a 'context diff'. This can be done using a command such as diff -ru <oldfile> <newfile>. Then upload the patchfile to:
along with a README file. Make sure you follow the naming conventions or your patch will just be deleted! The filenames should be of this form:
The "n" in the date indicates a unique number (starting from 0) of patches you uploaded that day. It should be 0, unless you upload more than one patch in the same day.
Once you upload anything, send the README to [email protected]
How do I know if my patch got applied, and if not, why not?
Uploaded patches will be moved to ftp://ftp.gtk.org/pub/gtk/patches where one of the GTK+ development team will pick them up. If applied, they will be moved to /pub/gtk/patches/old.
Patches that aren't applied, for whatever reason, are moved to /pub/gtk/patches/unapplied or /pub/gtk/patches/outdated. At this point you can ask on the gtk-list mailing list why your patch wasn't applied. There are many possible reasons why patches may not be applied, ranging from it doesn't apply cleanly, to it isn't right. Don't be put off if your patch didn't make it first time round.
What is the policy on incorporating new widgets into the library?
This is up to the authors, so you will have to ask them once you are done with your widget. As a general guideline, widgets that are generally useful, work, and are not a disgrace to the widget set will gladly be included.
Is anyone working on bindings for languages other than C?
The GTK+ home page (http://www.gtk.org/) presents a list of GTK+ bindings.
How do I get started?
So, after you have installed GTK+ there are a couple of things that can ease you into developing applications with it. There is the GTK+ Tutorial http://www.gtk.org/tutorial/, which is undergoing development. This will introduce you to writing applications using C.
The Tutorial doesn't (yet) contain information on all of the widgets that are in GTK+. For example code on how to use the basics of all the GTK+ widgets you should look at the file gtk/testgtk.c (and associated source files) within the GTK+ distribution. Looking at these examples will give you a good grounding on what the widgets can do.
4.2. How do I write security sensitive/SUID/SGID programs with GTK+? Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
How do I write security sensitive/SUID/SGID programs with GTK+? Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
The short answer to this question is: Don't write SUID/SGID programs with GTK+
For a more thorough explanation of the GTK+ Developers position on this issue see http://www.gtk.org/setuid.html.
I tried to compile a small Hello World of mine, but it failed. Any clue? [GTK 2.x]
Since you are good at coding, we will not deal with compile time error here :)
The classic command line to compile a GTK+ based program is
gcc -o myprog [c files] `pkg-config gtk+-2.0 --cflags --libs`
You should notice the backquote character which is used in this command line. A common mistake when you start a GTK+ based development is to use quote instead of backquotes. If you do so, the compiler will complain about an unknown file called pkg-config gtk+-2.0 --cflags --libs. The text in backquotes is an instruction to your shell to substitute the output of executing this command into the commandline.
The command line above ensures that:
What about using the make utility? [GTK 2.x]
This is a sample makefile which compile a GTK+ based program:
For more information about the make utility, you should read either the related man page or the relevant info file.
I use the backquote stuff in my makefiles, but my make process failed.
The backquote construction seems to not be accepted by some old make utilities. If you use one of these, the make process will probably fail. In order to have the backquote syntax working again, you should use the GNU make utility (get it on the GNU ftp server at ftp://ftp.gnu.org/).
I want to add some configure stuff, how could I do this?
To use autoconf/automake, you must first install the relevant packages. These are:
You'll find these packages on the GNU main ftp server (ftp://ftp.gnu.org/) or on any GNU mirror.
In order to use the powerful autoconf/automake scheme, you must create a configure.in which may look like:
You must add a Makefile.am file:
If your project contains more than one subdirectory, you'll have to create one Makefile.am in each directory plus a master Makefile.am which will look like:
then, to use these, simply type the following commands:
For further information, you should look at the autoconf and the automake documentation (the shipped info files are really easy to understand, and there are plenty of web resources that deal with autoconf and automake).
I try to debug my GTK+ application with gdb, but it hangs my X server when I hit some breakpoint. Any Idea?
From Federico Mena Quintero:
"X is not locked up. It is likely that you are hitting a breakpoint inside a callback that is called from a place in Gtk that has a mouse grab."
"Run your program with the --sync option; it will make it easier to debug. Also, you may want to use the console for running the debugger, and just let the program run in another console with the X server."
Eric Mouw had another solution:
"An old terminal connected to an otherwise unused serial port is also great for debugging X programs. Old vt100/vt220 terminals are dirt cheap but a bit hard to get (here in The Netherlands, YMMV)."
What widgets are in GTK?
The GTK+ Tutorial lists the following widgets:
Is GTK+ thread safe? How do I write multi-threaded GTK+ applications?
The GLib library can be used in a thread-safe mode by calling g_thread_init() before making any other GLib calls. In this mode GLib automatically locks all internal data structures as needed. This does not mean that two threads can simultaneously access, for example, a single hash table, but they can access two different hash tables simultaneously. If two different threads need to access the same hash table, the application is responsible for locking itself.
When GLib is intialized to be thread-safe, GTK+ is thread aware. There is a single global lock that you must acquire with gdk_threads_enter() before making any GDK calls, and release with gdk_threads_leave() afterwards.
A minimal main program for a threaded GTK+ application looks like:
Callbacks require a bit of attention. Callbacks from GTK+ (signals) are made within the GTK+ lock. However callbacks from GLib (timeouts, IO callbacks, and idle functions) are made outside of the GTK+ lock. So, within a signal handler you do not need to call gdk_threads_enter(), but within the other types of callbacks, you do.
Erik Mouw contributed the following code example to illustrate how to use threads within GTK+ programs.
Why does this strange 'x io error' occur when I fork() in my GTK+ app?
This is not really a GTK+ problem, and the problem is not related to fork() either. If the 'x io error' occurs then you probably use the exit() function in order to exit from the child process.
When GDK opens an X display, it creates a socket file descriptor. When you use the exit() function, you implicitly close all the open file descriptors, and the underlying X library really doesn't like this.
The right function to use here is _exit().
Erik Mouw contributed the following code example to illustrate handling fork() and exit().
5.4. Why don't the contents of a button move when the button is pressed? Here's a patch to make it work that way...
Why don't the contents of a button move when the button is pressed? Here's a patch to make it work that way...
From: Peter Mattis
"The reason buttons don't move their child down and to the right when they are depressed is because I don't think that's what is happening visually. My view of buttons is that you are looking at them straight on. That is, the user interface lies in a plane and you're above it looking straight at it. When a button gets pressed it moves directly away from you. To be absolutely correct I guess the child should actually shrink a tiny amount. But I don't see why the child should shift down and to the left. Remember, the child is supposed to be attached to the buttons surface. Its not good for it to appear like the child is slipping on the surface of the button."
"On a more practical note, I did implement this at one point and determined it didn't look good and removed it."
How do I identifiy a widgets top level window or other ancestor?
There are a couple of ways to find the top level parent of a widget. The easier way is to call the gtk_widget_top_level() function that returns pointer to a GtkWidget that is the top level window.
A more complicated way to do this (but less limited, as it allows the user to get the closest ancestor of a known type) is to use gtk_widget_get_ancestor() as in:
Since virtually all the GTK_TYPEs can be used as the second parameter of this function, you can get any parent widget of a particular widget. Suppose you have an hbox which contains a vbox, which in turn contains some other atomic widget (entry, label, etc. To find the master hbox using the entry widget simply use:
How do I get the Window ID of a GtkWindow?
The actual Gdk/X window will be created when the widget gets realized. You can get the Window ID with:
How do I catch a double click event (in a list widget, for example)?
Tim Janik wrote to gtk-list (slightly modified):
Define a signal handler:
And connect the handler to your object:
and, Owen Taylor wrote:
"Note that a single button press will be received beforehand, and if you are doing this for a button, you will therefore also get a "clicked" signal for the button. (This is going to be true for any toolkit, since computers aren't good at reading one's mind.)"
By the way, what are the differences between signals and events?
First of all, Havoc Pennington gives a rather complete description of the differences between events and signals in his free book (two chapters can be found at http://www106.pair.com/rhp/sample_chapters.html).
Moreover, Havoc posted this to the gtk-list "Events are a stream of messages received from the X server. They drive the Gtk main loop; which more or less amounts to "wait for events, process them" (not exactly, it is really more general than that and can wait on many different input streams at once). Events are a Gdk/Xlib concept."
"Signals are a feature of GtkObject and its subclasses. They have nothing to do with any input stream; really a signal is just a way to keep a list of callbacks around and invoke them ("emit" the signal). There are lots of details and extra features of course. Signals are emitted by object instances, and are entirely unrelated to the Gtk main loop. Conventionally, signals are emitted "when something changes" about the object emitting the signal."
"Signals and events only come together because GtkWidget happens to emit signals when it gets events. This is purely a convenience, so you can connect callbacks to be invoked when a particular widget receives a particular event. There is nothing about this that makes signals and events inherently related concepts, any more than emitting a signal when you click a button makes button clicking and signals related concepts."
Data I pass to the delete_event (or other event) handler gets corrupted.
All event handlers take an additional argument which contains information about the event that triggered the handler. So, a delete_event handler must be declared as:
5.10. I have my signal connected to the the (whatever) event, but it seems I don't catch it. What's wrong?
I have my signal connected to the the (whatever) event, but it seems I don't catch it. What's wrong?
There is some special initialisation to do in order to catch some particular events. In fact, you must set the correct event mask bit of your widget before getting some particular events.
lets you catch the key release events. If you want to catch every events, simply us the GDK_ALL_EVENTS_MASK event mask.
All the event masks are defined in the gdktypes.h file.
I need to add a new signal to a GTK+ widget. Any idea?
If the signal you want to add may be beneficial for other GTK+ users, you may want to submit a patch that presents your changes. Check the tutorial for more information about adding signals to a widget class.
If you don't think it is the case or if your patch is not applied you'll have to use the gtk_object_class_user_signal_new function. gtk_object_class_user_signal_new allows you to add a new signal to a predefined GTK+ widget without any modification of the GTK+ source code. The new signal can be emited with gtk_signal_emit and can be handled in the same way as other signals.
Tim Janik posted this code snippet:
If you want your new signal to have more than the classical gpointer parameter, you'll have to play with GTK+ marshallers.
Is it possible to get some text displayed which is truncated to fit inside its allocation?
GTK's behavior (no clipping) is a consequence of its attempts to conserve X resources. Label widgets (among others) don't get their own X window - they just draw their contents on their parent's window. While it might be possible to have clipping occur by setting the clip mask before drawing the text, this would probably cause a substantial performance penalty.
Its possible that, in the long term, the best solution to such problems might be just to change gtk to give labels X windows. A short term workaround is to put the label widget inside another widget that does get its own window - one possible candidate would be the viewport widget.
If you were doing this for a bunch of widgets, you might want to copy gtkviewport.c and strip out the adjustment and shadow functionality (perhaps you could call it GtkClipper).
How do I make my window modal? / How do I make a single window active?
After you create your window, do gtk_grab_add(my_window). And after closing the window do gtk_grab_remove(my_window).
Why doesn't my widget (e.g. progressbar) update?
You are probably doing all the changes within a function without returning control to gtk_main(). This may be the case if you do some lengthy calculation in your code. Most drawing updates are only placed on a queue, which is processed within gtk_main(). You can force the drawing queue to be processed using something like:
inside you're function that changes the widget.
What the above snippet does is run all pending events and high priority idle functions, then return immediately (the drawing is done in a high priority idle function).
How do I attach data to some GTK+ object/widget?
First of all, the attached data is stored in the object_data field of a GtkObject. The type of this field is GData, which is defined in glib.h. So you should read the gdataset.c file in your glib source directory very carefully.
There are two (easy) ways to attach some data to a gtk object. Using gtk_object_set_data() and gtk_object_get_data() seems to be the most common way to do this, as it provides a powerful interface to connect objects and data.
Since a short example is better than any lengthy speech:
The gtk_object_set_user_data() and gtk_object_get_user_data() functions does exactly the same thing as the functions above, but does not let you specify the "key" parameter.Instead, it uses a standard "user_data" key. Note that the use of these functions is deprecated in 1.2. They only provide a compatibility mode with some old gtk packages.
How do I remove the data I have attached to an object?
When attaching the data to the object, you can use the gtk_object_set_data_full() function. The three first arguments of the function are the same as in gtk_object_set_data(). The fourth one is a pointer to a callback function which is called when the data is destroyed. The data is destroyed when you:
How do I reparent a widget?
The normal way to reparent (ie change the owner) of a widget should be to use the function:
But this is only a "should be" since this function does not correctly do its job on some specific widgets. The main goal of gtk_widget_reparent() is to avoid unrealizing widget if both widget and new_parent are realized (in this case, widget->window is successfully reparented). The problem here is that some widgets in the GTK+ hierarchy have multiple attached X subwindows and this is notably the case for the GtkSpinButton widget. For those, gtk_widget_reparent() will fail by leaving an unrealized child window where it should not.
To avoid this problem, simply use the following code snippet:
How could I get any widgets position?
As Tim Janik pointed out, there are different cases, and each case requires a different solution.
Your choice of Window Manager will have an effect of the results of the above functions. You should keep this in mind when writing your application. This is dependant upon how the Window Managers manage the decorations that they add around windows.
How do I set the size of a widget/window? How do I prevent the user resizing my window?
The gtk_widget_set_uposition() function is used to set the position of any widget.
The gtk_widget_set_usize() function is used to set the size of a widget. In order to use all the features that are provided by this function when it acts on a window, you may want to use the gtk_window_set_policy function. The definition of these functions are:
auto_shrink will automatically shrink the window when the requested size of the child widgets goes below the current size of the window. allow_shrink will give the user the authorisation to make the window smaller that it should normally be. allow_grow gives the user the ability to make the window bigger. The default values for these parameters are:
The gtk_widget_set_usize() functions is not the easiest way to set a window size since you cannot decrease this window size with another call to this function unless you call it twice, as in:
Another way to set the size of and/or move a window is to use the gdk_window_move_resize() function which uses to work fine both to grow or to shrink the window:
How do I add a popup menu to my GTK+ application?
The menu example in the examples/menu directory of the GTK+ distribution implements a popup menu with this technique:
How do I disable or enable a widget, such as a button?
To disable (or to enable) a widget, use the gtk_widget_set_sensitive() function. The first parameter is you widget pointer. The second parameter is a boolean value: when this value is TRUE, the widget is enabled.
Shouldn't the text argument in the gtk_clist_* functions be declared const?
Answer: No, while a type "gchar*" (pointer to char) can automatically be cast into "const gchar*" (pointer to const char), this does not apply for "gchar *" (array of an unspecified number of pointers to char) into "const gchar *" (array of an unspecified number of pointers to const char).
The type qualifier "const" may be subject to automatic casting, but in the array case, it is not the array itself that needs the (const) qualified cast, but its members, thus changing the whole type.
How do I render pixels (image data) to the screen?
There are several ways to approach this. The simplest way is to use GdkRGB, see gdk/gdkrgb.h. You create an RGB buffer, render to your RGB buffer, then use GdkRGB routines to copy your RGB buffer to a drawing area or custom widget. The book "GTK+/Gnome Application Development" gives some details; GdkRGB is also documented in the GTK+ reference documentation.
If you're writing a game or other graphics-intensive application, you might consider a more elaborate solution. OpenGL is the graphics standard that will let you access hardware accelaration in future versions of XFree86; so for maximum speed, you probably want to use OpenGL. A GtkGLArea widget is available for using OpenGL with GTK+ (but GtkGLArea does not come with GTK+ itself). There are also several open source game libraries, such as ClanLib and Loki's Simple DirectMedia Layer library (SDL).
You do NOT want to use gdk_draw_point(), that will be extremely slow.
How do I create a pixmap without having my window being realized/shown?
Functions such as gdk_pixmap_create_from_xpm() require a valid window as a parameter. During the initialisation phase of an application, a valid window may not be available without showing a window, which may be inappropriate. In order to avoid this, a function such as gdk_pixmap_colormap_create_from_xpm can be used, as in:
How do I do drag-and-drop?
GTK+ has a high level set of functions for doing inter-process communication via the drag-and-drop system. GTK+ can perform drag-and-drop on top of the low level Xdnd and Motif drag-and-drop protocols.
The documentation on GTK+ drag-and-drop isn't complete, but there is some information in the Tutorial. You should also look at the drag-and-drop example code that is part of the GTK+ source distribution, in the file gtk/testdnd.c.
Why does GTK+/GLib leak memory?
It doesn't. Both GLib and the C library (malloc implementation) will cache allocated memory on occasion, even if you free it with free().
So you can't generally use tools such as top to see if you are using free() properly (aside from the very roughest of estimations, i.e. if you are really, really screwing up top will show that, but you can't distinguish small mistakes from the GLib/malloc caches).
In order to find memory leaks, use proper memory profiling tools.
How do I find out about the selection of a GtkList?
Get the selection something like this:
This is how GList is defined (quoting glist.h):
A GList structure is just a simple structure for doubly linked lists. There exist several g_list_*() functions to modify a linked list in glib.h. However the GTK_LIST(MyGtkList)->selection is maintained by the gtk_list_*() functions and should not be modified.
The selection_mode of the GtkList determines the selection facilities of a GtkList and therefore the contents of GTK_LIST(AnyGtkList)->selection:
The data field of the GList structure GTK_LIST(MyGtkList)->selection points to the first GtkListItem that is selected. So if you would like to determine which listitems are selected you should go like this:
To get known about the selection:
How do I stop the column headings of a GtkCList disappearing when the list is scrolled?
This happens when a GtkCList is packed into a GtkScrolledWindow using the function gtk_scroll_window_add_with_viewport(). The prefered method of adding a CList to a scrolled window is to use the function gtk_container_add, as in:
I don't want the user of my applications to enter text into a GtkCombo. Any idea?
A GtkCombo has an associated entry which can be accessed using the following expression:
If you don't want the user to be able to modify the content of this entry, you can use the gtk_entry_set_editable() function:
Set the editable parameter to FALSE to disable typing into the entry.
How do I catch a combo box change?
The entry which is associated to your GtkCombo send a "changed" signal when:
To catch any combo box change, simply connect your signal handler with
How can I define a separation line in a menu?
See the Tutorial for information on how to create menus. However, to create a separation line in a menu, just insert an empty menu item:
How can I right justify a menu, such as Help?
Depending on if you use the MenuFactory or not, there are two ways to proceed. With the MenuFactory, use something like the following:
If you do not use the MenuFactory, you should simply use:
How do I add some underlined accelerators to menu items?
Damon Chaplin, the technical force behind the Glade project, provided the following code sample (this code is an output from Glade). It creates a small File menu item with only one child (New). The F in File and the N in New are underlined, and the relevant accelerators are created.
How can I retrieve the text from a GtkMenuItem?
You can usually retrieve the label of a specific GtkMenuItem with:
To get the active menu item from a GtkOptionMenu you can do:
But, there's a catch. For this specific case, you can not get the label widget from menu_item with the above code, because the option menu reparents the menu_item's child temporarily to display the currently active contents. So to retrive the child of the currently active menu_item of an option menu, you'll have to do:
How do I right (or otherwise) justify a GtkLabel?
Are you sure you want to justify the labels? The label class contains the gtk_label_set_justify() function that is used to control the justification of a multi-line label.
What you probably want is to set the alignment of the label, ie right align it, center it or left align it. If you want to do this, you should use:
where the xalign and yalign values are floats in [0.00;1.00].
How do I set the background color of a GtkLabel widget?
The GtkLabel widget is one of a few GTK+ widgets that don't create their own window to render themselves into. Instead, they draw themselves directly onto their parents window.
This means that in order to set the background color for a GtkLabel widget, you need to change the background color of its parent, i.e. the object that you pack it into.
How do I set the color and font of a GtkLabel using a Resource File?
The widget name path constructed for a Label consists of the widget names of its object hierarchy as well, e.g.
The widget path your pattern needs to match would be: humphrey.GtkHBox.mylabel
The resource file may look something like:
In your program, you would also need to give a name to the Label widget, which can be done using:
How do I configure Tooltips in a Resource File?
The tooltip's window is named "gtk-tooltips", GtkTooltips in itself is not a GtkWidget (though a GtkObject) and as such is not attempted to match any widget styles.
So, you resource file should look something like:
I can't add more than (something like) 2000 chars in a GtkEntry. What's wrong?
There is now a known problem in the GtkEntry widget. In the gtk_entry_insert_text() function, the following lines limit the number of chars in the entry to 2047.
How do I make a GtkEntry widget activate on pressing the Return key?
The Entry widget emits an 'activate' signal when you press return in it. Just attach to the activate signal on the entry and do whatever you want to do. Typical code would be:
How do I validate/limit/filter the input to a GtkEntry?
If you want to validate the text that a user enters into a GtkEntry widget you can attach to the "insert_text" signal of the entry, and modify the text within the callback function. The example below forces all characters to uppercase, and limits the range of characters to A-Z. Note that the entry is cast to an object of type GtkEditable, from which GtkEntry is derived.
How do I use horizontal scrollbars with a GtkText widget?
The short answer is that you can't. The current version of the GtkText widget does not support horizontal scrolling. There is an intention to completely rewrite the GtkText widget, at which time this limitation will be removed.
How do I change the font of a GtkText widget?
There are a couple of ways of doing this. As GTK+ allows the appearance of applications to be changed at run time using resources you can use something like the following in the appropriate file:
Another way to do this is to load a font within your program, and then use this in the functions for adding text to the text widget. You can load a font using, for example:
How do I set the cursor position in a GtkText object?
Notice that the response is valid for any object that inherits from the GtkEditable class.
Are you sure that you want to move the cursor position? Most of the time, while the cursor position is good, the insertion point does not match the cursor position. If this apply to what you really want, then you should use the gtk_text_set_point() function. If you want to set the insertion point at the current cursor position, use the following:
If you want the insertion point to follow the cursor at all time, you should probably catch the button press event, and then move the insertion point. Be careful : you'll have to catch it after the widget has changed the cursor position though. Thomas Mailund Jensen proposed the following code:
Now, if you really want to change the cursor position, you should use the gtk_editable_set_position() function.
What is GDK?
GDK is basically a wrapper around the standard Xlib function calls. If you are at all familiar with Xlib, a lot of the functions in GDK will require little or no getting used to. All functions are written to provide an way to access Xlib functions in an easier and slightly more intuitive manner. In addition, since GDK uses GLib (see below), it will be more portable and safer to use on multiple platforms.
How do I use color allocation?
One of the nice things about GDK is that it's based on top of Xlib; this is also a problem, especially in the area of color management. If you want to use color in your program (drawing a rectangle or such, your code should look something like this:
What is GLib?
GLib is a library of useful functions and definitions available for use when creating GDK and GTK applications. It provides replacements for some standard libc functions, such as malloc, which are buggy on some systems.
It also provides routines for handling:
How can I use the doubly linked lists?
The GList object is defined as:
To use the GList objects, simply:
The same code is usable with singly linked lists (GSList objects) by replacing g_list_* functions with the relevant g_slist_* ones (g_slist_append, g_slist_remove, ...). Just remember that since you can't go backward in a singly linked list, there is no g_slist_first function - you'll need to keep a reference on the first node of the list.
Memory does not seem to be released when I free the list nodes I've allocated
GLib tries to be "intelligent" on this special issue: it assumes that you are likely to reuse the objects, so caches the allocated memory. If you do not want to use this behavior, you'll probably want to set up a special allocator.
To quote Tim Janik:
"If you have a certain portion of code that uses *lots* of GLists or GNodes, and you know you'd better want to release all of them after a short while, you'd want to use a GAllocator. Pushing an allocator into g_list will make all subsequent glist operations private to that allocator's memory pool (and thus you have to take care to pop the allocator again, before making any external calls): "
Why use g_print, g_malloc, g_strdup and fellow glib functions?
Thanks to Tim Janik who wrote to gtk-list: (slightly modified)
"Regarding g_malloc(), g_free() and siblings, these functions are much safer than their libc equivalents. For example, g_free() just returns if called with NULL. Also, if USE_DMALLOC is defined, the definition for these functions changes (in glib.h) to use MALLOC(), FREE() etc... If MEM_PROFILE or MEM_CHECK are defined, there are even small statistics made counting the used block sizes (shown by g_mem_profile() / g_mem_check())."
"Considering the fact that glib provides an interface for memory chunks to save space if you have lots of blocks that are always the same size and to mark them ALLOC_ONLY if needed, it is just straight forward to create a small saver (debug able) wrapper around the normal malloc/free stuff as well - just like gdk covers Xlib. ;)"
"Using g_error() and g_warning() inside of applications like the GIMP that fully rely on gtk even gives the opportunity to pop up a window showing the messages inside of a gtk window with your own handler (by using g_set_error_handler()) along the lines of gtk_print() (inside of gtkmain.c)."
What's a GScanner and how do I use one?
A GScanner will tokenize your text, that is, it'll return an integer for every word or number that appears in its input stream, following certain (customizable) rules to perform this translation. You still need to write the parsing functions on your own though.
Here's a little test program supplied by Tim Janik that will parse
<SYMBOL> = <OPTIONAL-MINUS> <NUMBER> ;
constructs, while skipping "#\n" and "/**/" style comments.
You need to understand that the scanner will parse its input and tokenize it, it is up to you to interpret these tokens, not define their types before they get parsed, e.g. watch gscanner parse a string:
"hi i am 17"
If you configure the scanner with:
and add "am" as a symbol with
GScanner will parse it as
"hi i am 17"
You need to match the token sequence with your code, and if you encounter something that you don't want, you error out:
If you got past here, you have parsed "hi i am 17" and would have accepted "dooh i am 42" and "bah i am 0.75" as well, but you would have not accepted "hi 7 am 17" or "hi i hi 17".
If you would like to make a contribution to the FAQ, send either one of us an e-mail message with the exact text you think should be included (question and answer). With your help, this document can grow and become more useful!
This document is maintained by Tony Gale mailto:[email protected] Nathan Froyd mailto:[email protected], and Emmanuel Deloget mailto:[email protected]. This FAQ was created by Shawn T. Amundson mailto:[email protected] who continues to provide support. Contributions should be sent to Tony Gale mailto:[email protected]
The GTK+ FAQ is Copyright (C) 1997-2000 by Shawn T. Amundson, Tony Gale, Emmanuel Deloget and Nathan Froyd.
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this document under the conditions for verbatim copying, provided that this copyright notice is included exactly as in the original, and that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this document into another language, under the above conditions for modified versions.
If you are intending to incorporate this document into a published work, please contact one of the maintainers, and we will make an effort to ensure that you have the most up to date information available.
There is no guarentee that this document lives up to its intended purpose. This is simply provided as a free resource. As such, the authors and maintainers of the information provided within can not make any guarentee that the information is even accurate.