Hello World in Gtk+

It is traditional to write a simple "hello world" simple to show how a new language or framework application works. With this simple exercise, one can quickly see the major components of a program.

The Gtk+ equivalent of a hello world application is a program that displays a simple window. The window has "hello world" as its caption. Therefore, by compiling and running the application, one can have a full idea of how to create a bare bones program using the Gtk+ toolkit.

Here is a simple hello world program in Gtk+:

#include <gtk/gtk.h>

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 first thing done on main is to setup the Gtk+ system using the gtk_init function. Then, we create a window using gtk_window_new and set the title of the window to "hello world", using gtk_window_set _title.

The next line show how to attach an event handler to an event. We just need to call the gtk_signal_connect function, which receives as parameters the window, the name of the event, and the function to be invoked when it happens. The function used simply calls gtk_main_quit, and it is used to quit the application. Therefore, when the window is closed, the application will automatically finish.

Finally, the program displays the window making a call to gtk_widget_show. The next line calls the gtk_main function, which enters the main event loop for the application.

This simple program displays a Gtk+ window, and process correctly a single event. Real applications are much more complicated, but they are not very different from this one in structure. You need to initialize the widgets to handle the UI of the application and call the main event loop.

Tags: Gtk, programming, Linux, Unix, desktop, environment, hello, world
Article created on 2010-08-19 16:38:55

Post a comment