First things in GTK+

A basic GUI application functions by running an endless event, which handles each mouse movement, button click or keystroke. GTK+ simplifies this procedure by taking a step away from the event loop and defining a set of "signals", which more closely matches an event which has taken place to the object that that event corresponds to. Even the event loop is abstracted away from the user, by simply calling the function gtk_main(); which starts up the event loop, the details of which are hidden from the user.

In the case of a button in a window, for instance, the separate mouse movement events are replaced by a single "enter" signal, indicating the mouse has moved over the button. The event that says a mouse button was pressed is replaced by a signal that the button (the object in the window) was clicked.

Signals are processed by attaching a "callback" function to a given signal for any particular object. For example, after creating a new button,

button = gtk_button_new();
a callback function that acts when the button is pressed can be setup by calling
gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (ButtonPressed), NULL);
which connects the function "ButtonPressed" to the "clicked" signal that is generated when the button is pressed. The callback function, "ButtonPressed" in this case, may be defined as
void ButtonPressed( GtkWidget *widget,  gpointer   data )
           g_print ("Button was pressed!\n");
Note that the callback function has two arguments. The first identifies which object the signal was generated for, in this case, the button. The second argument is a pointer to any further data supplied to the callback function at the time the function was connected to the signal. In the example above, NULL was given, meaning there is in fact no extra data for this function.

Note that this function does not know which mouse button (if any) was used to click the application's button. In order to obtain this more detailed information, a different signal may be used, in this case the signal called "button_press_event" which refers to the actual event corresponding to the pressing of the mouse button. The callback function in this instance,

ButtonPressed_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
has an extra argument, a pointer to an "event" structure, which among other things identifies which mouse button was actually pressed.

Previous: GUI programming
Next: Putting things together
Back to index