Programming with GTK+

Let’s take an initial look inside a GTK+-based application. We recommend that you download and install GTK+ first so you can try this out. If you have a recent version of Linux, you may already have GTK+ installed.

Sample Program

In this section, we’ll run through Example 9-1, a quick “Hello World” program that’s a simple demonstration of a one-button window. When you click the button, “Hello World” is printed to your shell, and then the program exits. We’ve highlighted the program elements we’ll describe later on.

Example 9-1. GTK+ helloworld.c

#include <gtk/gtk.h>

/* This is a callback function. The data arguments are ignored
 * in this example. More on callbacks below. */
void hello( GtkWidget *widget,
            gpointer   data )
{
   g_print ("Hello World\n");
}

gint delete_event( GtkWidget *widget,
                   GdkEvent  *event,
                   gpointer   data )
{
   /* If you return FALSE in the "delete_event" signal handler,
    * GTK will emit the "destroy" signal. Returning TRUE means
    * you don't want the window to be destroyed.
    * This is useful for popping up 'are you sure you want to quit?'
    * type dialogs. */

   g_print ("delete event occurred\n"); /* Change TRUE to FALSE and the main window will be destroyed with * a "delete_event". */ return(TRUE); } /* Another callback */ void destroy( GtkWidget *widget, gpointer data ) { gtk_main_quit( ); } int main( int argc, char *argv[] ) { /* GtkWidget is the storage type for widgets */ GtkWidget *window; GtkWidget *button; /* This is called in all GTK applications. ...

Get Oracle and Open Source now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.