Next Previous Contents

5. Development with GTK+: the programming part

5.1 What widgets are in GTK?

The GTK+ Tutorial lists the following widgets:

  GtkObject
   +GtkData
   | +GtkAdjustment
   | `GtkTooltips
   `GtkWidget
     +GtkContainer
     | +GtkBin
     | | +GtkAlignment
     | | +GtkEventBox
     | | +GtkFrame
     | | | `GtkAspectFrame
     | | +GtkHandleBox
     | | +GtkItem
     | | | +GtkListItem
     | | | +GtkMenuItem
     | | | | `GtkCheckMenuItem
     | | | |   `GtkRadioMenuItem
     | | | `GtkTreeItem
     | | +GtkViewport
     | | `GtkWindow
     | |   +GtkColorSelectionDialog
     | |   +GtkDialog
     | |   | `GtkInputDialog
     | |   `GtkFileSelection
     | +GtkBox
     | | +GtkButtonBox
     | | | +GtkHButtonBox
     | | | `GtkVButtonBox
     | | +GtkHBox
     | | | +GtkCombo
     | | | `GtkStatusbar
     | | `GtkVBox
     | |   +GtkColorSelection
     | |   `GtkGammaCurve
     | +GtkButton
     | | +GtkOptionMenu
     | | `GtkToggleButton
     | |   `GtkCheckButton
     | |     `GtkRadioButton
     | +GtkCList
     |   `GtkCTree
     | +GtkFixed
     | +GtkList
     | +GtkMenuShell
     | | +GtkMenuBar
     | | `GtkMenu
     | +GtkNotebook
     | +GtkPaned
     | | +GtkHPaned
     | | `GtkVPaned
     | +GtkScrolledWindow
     | +GtkTable
     | +GtkToolbar
     | `GtkTree
     +GtkDrawingArea
     | `GtkCurve
     +GtkEditable
     | +GtkEntry
     | | `GtkSpinButton
     | `GtkText
     +GtkMisc
     | +GtkArrow
     | +GtkImage
     | +GtkLabel
     | | `GtkTipsQuery
     | `GtkPixmap
     +GtkPreview
     +GtkProgressBar
     +GtkRange
     | +GtkScale
     | | +GtkHScale
     | | `GtkVScale
     | `GtkScrollbar
     |   +GtkHScrollbar
     |   `GtkVScrollbar
     +GtkRuler
     | +GtkHRuler
     | `GtkVRuler
     `GtkSeparator
       +GtkHSeparator
       `GtkVSeparator

5.2 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:

int
main (int argc, char *argv[])
{
  GtkWidget *window;

  g_thread_init(NULL);
  gtk_init(&argc, &argv);

  window = create_window();
  gtk_widget_show(window);

  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  return(0);
}

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.

5.3 How to 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 a 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:

      GtkWidget       *widget;
      
      widget = gtk_widget_get_ancestor(w, GTK_TYPE_WINDOW);

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:

      GtkWidget       *hbox;
      hbox = gtk_widget_get_ancestor(w, GTK_TYPE_HBOX);

5.4 How do I find out about the selection of a GtkList?

Get the selection something like this:

GList *sel;
sel = GTK_LIST(list)->selection;

This is how GList is defined (quoting glist.h):

typedef struct _GList GList;

struct _GList
{
  gpointer data;
  GList *next;
  GList *prev;
};

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:

selection_mode          GTK_LIST()->selection contents
------------------------------------------------------

GTK_SELECTION_SINGLE)   selection is either NULL
                        or contains a GList* pointer
                        for a single selected item.

GTK_SELECTION_BROWSE)   selection is NULL if the list
                        contains no widgets, otherwise
                        it contains a GList* pointer
                        for one GList structure.
GTK_SELECTION_MULTIPLE) selection is NULL if no listitems
                        are selected or a a GList* pointer
                        for the first selected item. that
                        in turn points to a GList structure
                        for the second selected item and so
                        on

GTK_SELECTION_EXTENDED) selection is NULL.

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:

Upon Initialization:

{
        gchar           *list_items[]={
                                "Item0",
                                "Item1",
                                "foo",
                                "last Item",
                        };
        guint           nlist_items=sizeof(list_items)/sizeof(list_items[0]);
        GtkWidget       *list_item;
        guint           i;

        list=gtk_list_new();
        gtk_list_set_selection_mode(GTK_LIST(list), GTK_SELECTION_MULTIPLE);
        gtk_container_add(GTK_CONTAINER(AnyGtkContainer), list);
        gtk_widget_show (list);

        for (i = 0; i < nlist_items; i++)
        {
                list_item=gtk_list_item_new_with_label(list_items[i]);
                gtk_object_set_user_data(GTK_OBJECT(list_item), (gpointer)i);
                gtk_container_add(GTK_CONTAINER(list), list_item);
                gtk_widget_show(list_item);
        }
}

To get known about the selection:

{
        GList   *items;

        items=GTK_LIST(list)->selection;

        printf("Selected Items: ");
        while (items) {
                if (GTK_IS_LIST_ITEM(items->data))
                        printf("%d ", (guint) 
                gtk_object_get_user_data(items->data));
                items=items->next;
        }
        printf("\n");
}

5.5 How can I prevent redrawing and resizing while I change multiple widgets?

Old versions of GTK+ used to provide the gtk_container_enable_resize() and gtk_container_disable_resize() functions to enable or disable the resize while modifying widgets.

In the current version of GTK+, there is no more need for these functions, since GTK+ will only resize a widget during idle.

5.6 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:

      GTK_COMBO(combo_widget)->entry

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:

      void gtk_entry_set_editable(GtkEntry *entry, 
                                  gboolean editable);

Set the editable parameter to FALSE to disable typing into the entry.

5.7 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

      gtk_signal_connect(GTK_COMBO(cb)->entry,
                         "changed",
                         GTK_SIGNAL_FUNC(my_cb_change_handler),
                         NULL);

5.8 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:

gint
signal_handler_event(GtkWiget *widget, GdkEvenButton *event, gpointer func_data)
{
  if (GTK_IS_LIST_ITEM(widget) &&
       (event->type==GDK_2BUTTON_PRESS ||
        event->type==GDK_3BUTTON_PRESS) ) {
    printf("I feel %s clicked on button %d\",
           event->type==GDK_2BUTTON_PRESS ? "double" : "triple",
           event->button);
  }

  return FALSE;
}

And connect the handler to your object:

{
  /* list, list item init stuff */     

  gtk_signal_connect(GTK_OBJECT(list_item),
                     "button_press_event",
                     GTK_SIGNAL_FUNC(signal_handler_event),
                     NULL);

  /* and/or */

  gtk_signal_connect(GTK_OBJECT(list_item),
                     "button_release_event",
                     GTK_SIGNAL_FUNC(signal_handler_event),
                     NULL);

  /* something else */
}

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

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

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

For example,

  gtk_widget_add_events(window, GDK_KEY_RELEASE_MASK);

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.

5.11 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 it's own window - one possible candidate would be the viewport widget.

viewport = gtk_viewport (NULL, NULL);
gtk_widget_set_usize (viewport, 50, 25);
gtk_viewport_set_shadow_type (GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
gtk_widget_show(viewport);

label = gtk_label ("a really long label that won't fit");
gtk_container_add (GTK_CONTAINER(viewport), label);
gtk_widget_show (label);

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

5.12 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:

menuitem = gtk_menu_item_new();
gtk_menu_append(GTK_MENU(menu), menuitem);
gtk_widget_show(menuitem);

5.13 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:

menu_path = gtk_menu_factory_find (factory,  "<MyApp>/Help");
gtk_menu_item_right_justify(menu_path->widget);

If you do not use the MenuFactory, you should simply use:

gtk_menu_item_right_justify(my_menu_item);

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

  menubar1 = gtk_menu_bar_new ();
  gtk_object_set_data (GTK_OBJECT (window1), "menubar1", menubar1);
  gtk_widget_show (menubar1);
  gtk_box_pack_start (GTK_BOX (vbox1), menubar1, FALSE, FALSE, 0);

  file1 = gtk_menu_item_new_with_label ("");
  tmp_key = gtk_label_parse_uline (GTK_LABEL (GTK_BIN (file1)->child),
                                   _("_File"));
  gtk_widget_add_accelerator (file1, "activate_item", accel_group,
                              tmp_key, GDK_MOD1_MASK, 0);
  gtk_object_set_data (GTK_OBJECT (window1), "file1", file1);
  gtk_widget_show (file1);
  gtk_container_add (GTK_CONTAINER (menubar1), file1);

  file1_menu = gtk_menu_new ();
  file1_menu_accels = gtk_menu_ensure_uline_accel_group (GTK_MENU (file1_menu));
  gtk_object_set_data (GTK_OBJECT (window1), "file1_menu", file1_menu);
  gtk_menu_item_set_submenu (GTK_MENU_ITEM (file1), file1_menu);

  new1 = gtk_menu_item_new_with_label ("");
  tmp_key = gtk_label_parse_uline (GTK_LABEL (GTK_BIN (new1)->child),
                                   _("_New"));
  gtk_widget_add_accelerator (new1, "activate_item", file1_menu_accels,
                              tmp_key, 0, 0);
  gtk_object_set_data (GTK_OBJECT (window1), "new1", new1);
  gtk_widget_show (new1);
  gtk_container_add (GTK_CONTAINER (file1_menu), new1);

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

5.16 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:

while (gtk_events_pending())
        gtk_main_iteration();

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

5.17 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 powerfull interface to connect objects and data.

void gtk_object_set_data(GtkObject *object, const gchar *key, gpointer data);
gpointer gtk_object_get_data(GtkObject *object, const gchar *key);

Since a short example is better than any lengthy speech:

struct my_struct        p1,p2,*result;
GtkWidget               *w;

gtk_object_set_data(GTK_OBJECT(w),"p1 data",(gpointer)&p1);
gtk_object_set_data(GTK_OBJECT(w),"p2 data",(gpointer)&p2);

result = gtk_object_get_data(GTK_OBJECT(w),"p1 data");

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.

5.18 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:

5.19 How do I right (or otherwise) justify a label?

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:

void gtk_misc_set_alignment     (GtkMisc *misc,
                                gfloat xalign,
                                gfloat yalign);

where the xalign and yalign values are floats in [0.00;1.00].

GtkWidget       *label;

/* horizontal : left align, vertical : top */
gtk_misc_set_alignment(GTK_MISK(label), 0.0f, 0.0f);

/* horizontal : centered, vertical : centered */
gtk_misc_set_alignment(GTK_MISK(label), 0.5f, 0.5f);

/* horizontal : right align, vertical : bottom */
gtk_misc_set_alignment(GTK_MISK(label), 1.0f, 1.0f);

5.20 How could I get any widget position?

As Tim Janik pointed out, there are different cases, and each case requires a different solution.

5.21 How do I set the position/size of a widget/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 this function is the following:

void        gtk_window_set_policy           (GtkWindow *window,
                                             gint allow_shrink,
                                             gint allow_grow,
                                             gint auto_shrink);

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 will give the user will have the ability to make the window bigger. The default values for these parameters are:

allow_shrink = FALSE
allow_grow   = TRUE
auto_shrink  = FALSE

5.22 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 :

static gint button_press (GtkWidget *widget, GdkEvent *event)
{

    if (event->type == GDK_BUTTON_PRESS) {
        GdkEventButton *bevent = (GdkEventButton *) event; 
        gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
                        bevent->button, bevent->time);
        /* Tell calling code that we have handled this event; the buck
         * stops here. */
        return TRUE;
    }

    /* Tell calling code that we have not handled this event; pass it on. */
    return FALSE;
}

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

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

5.25 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:

style "text"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
}

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:

  GdkFont *font;
  font = gdk_font_load("-adobe-helvetica-medium-r-normal--*-140-*-*-*-*-*-*");

5.26 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:

  gtk_text_set_point(GTK_TEXT(text),
      gtk_editable_get_position(GTK_EDITABLE(text)));

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:

static void
insert_bar (GtkWidget *text)
{
  /* jump to cursor mark */
  gtk_text_set_point (GTK_TEXT (text),
      gtk_editable_get_position (GTK_EDITABLE  (text)));

  gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL,
     "bar", strlen ("bar"));
}

int
main (int argc, char *argv[])
{
  GtkWidget *window, *text;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  text = gtk_text_new (NULL, NULL);
  gtk_text_set_editable (GTK_TEXT (text), TRUE);
  gtk_container_add (GTK_CONTAINER (window), text);

  /* connect after everything else */
  gtk_signal_connect_after (GTK_OBJECT(text), "button_press_event",
    GTK_SIGNAL_FUNC (insert_bar), NULL);

  gtk_widget_show_all(window);
  gtk_main();

  return 0;
}

Now, if you really want to change the cursor position, you should use the gtk_editable_set_position() function.


Next Previous Contents