Event Based Applications in Gtk+

Applications written in Gtk+ use a structure that is based on user events. An event is defined as an action occurring in the user interface that requires a response from the application. For example, when a user interface displays a button, something will happen when the button is clicked. The application must be notified that the button was clicked in order to activate the logic for that event.

Event based programming is essential for graphical applications. It allows applications to respond to events that are important to the functioning of the program. At the same time, irrelevant behavior is not part of the code, therefore reducing maintenance costs.

In Gtk+, the easiest way to defined event based applications is using the event/signal system. With Gtk+, one can define the signals that you want to respond to. Each signal is part of a widget, which makes it simple to determine the signals that we're interested on.

For example, consider a button widget. Every button has a number of pre-defined events, such as press, release, or activate. In order to use a button in our application, we just need to define code that will be executed when one of these events happen.

Here is an example from the hello world application:

static void destroy(GtkWidget *widget, gpointer data)
{
       gtk_main_quit ();
}

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

   gtk_init (&argc, &argv);

   /* create a new window */
   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
   gtk_window_set_title(GTK_WINDOW(window), "Hello World");

   gtk_signal_connect (GTK_OBJECT(window), "destroy",
         GTK_SIGNAL_FUNC (destroy), NULL);

   gtk_widget_show (window);

   gtk_main ();

   return 0;
}

The window widget (our main widget) has an associated event called "destroy". That event is called when the window is closed (for example, when the close button on the window caption is clicked). To respond to that event, we need to use the gtk_signal_connect, where the parameters are the object, the name of the event, and the function called when the event happens.

Event based applications require that we initially set the connection between events and code. Then, the program will just use those connections to call only the required code. In that way, the application is most of the time waiting for new events to be processed, instead of actively looking for things to do.

Tags: events, environment, desktop, Unix, Linux, programming, Gtk, Gnome
Article created on 2010-08-23 14:55:08

Post a comment