GTK+
The GIMP Toolkit

General
Introduction
Screenshots
Download
Mailing Lists
Language Bindings
Themes
Bug Tracker

Documentation
FAQ
GTK+-2.0 Tutorial
GTK+-1.2 Tutorial
API Reference
Published Books

Projects
Pango
GNOME
GTK+ for Win32
GTK+ on DirectFB
GTK+ for BeOS

Applications
GIMP
Abiword
Dia
Glade
GnuCash
Gnumeric

GNOME Software Map

Table of Contents
1. General Information下载
1.1. Note: This FAQ mainly covers GTK+ 1.2
1.2. Before anything else: the greetings
1.3. Authors
1.4. What is GTK+?
1.5. What is the + in GTK+?
1.6. Does the G in GTK+, GDK and GLib stand for?
1.7. Where is the documentation for GTK+?
1.8. Is there a mailing list (or mailing list archive) for GTK+?
1.9. How to get help with GTK+
1.10. How to report bugs in GTK+
1.11. Is there a Windows version of GTK+?
1.12. What applications have been written with GTK+?
1.13. I'm looking for an application to write in GTK+. How about an IRC client?
2. How to find, configure, install, and troubleshoot GTK+
2.1. What do I need to run GTK+?
2.2. Where can I get GTK+?
2.3. How do I configure/compile GTK+?
2.4. When compiling GTK+ I get an error like: make: file `Makefile' line 456: Syntax error
2.5. I've compiled and installed GTK+, but I can't get any programs to link with it! [GTK 2.x]
2.6. When installing a GTK+ application, configure reports that it can't find GTK. [GTK 2.x]
3. Development of GTK+
3.1. Whats this CVS thing that everyone keeps talking about, and how do I access it?
3.2. How can I contribute to GTK+?
3.3. How do I know if my patch got applied, and if not, why not?
3.4. What is the policy on incorporating new widgets into the library?
3.5. Is anyone working on bindings for languages other than C?
4. Development with GTK+: the begining
4.1. How do I get started?
4.2. How do I write security sensitive/SUID/SGID programs with GTK+? Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
4.3. I tried to compile a small Hello World of mine, but it failed. Any clue? [GTK 2.x]
4.4. What about using the make utility? [GTK 2.x]
4.5. I use the backquote stuff in my makefiles, but my make process failed.
4.6. I want to add some configure stuff, how could I do this?
4.7. I try to debug my GTK+ application with gdb, but it hangs my X server when I hit some breakpoint. Any Idea?
5. Development with GTK+: general questions
5.1. What widgets are in GTK?
5.2. Is GTK+ thread safe? How do I write multi-threaded GTK+ applications?
5.3. Why does this strange 'x io error' occur when I fork() in my GTK+ app?
5.4. Why don't the contents of a button move when the button is pressed? Here's a patch to make it work that way...
5.5. How do I identifiy a widgets top level window or other ancestor?
5.6. How do I get the Window ID of a GtkWindow?
5.7. How do I catch a double click event (in a list widget, for example)?
5.8. By the way, what are the differences between signals and events?
5.9. Data I pass to the delete_event (or other event) handler gets corrupted.
5.10. I have my signal connected to the the (whatever) event, but it seems I don't catch it. What's wrong?
5.11. I need to add a new signal to a GTK+ widget. Any idea?
5.12. Is it possible to get some text displayed which is truncated to fit inside its allocation?
5.13. How do I make my window modal? / How do I make a single window active?
5.14. Why doesn't my widget (e.g. progressbar) update?
5.15. How do I attach data to some GTK+ object/widget?
5.16. How do I remove the data I have attached to an object?
5.17. How do I reparent a widget?
5.18. How could I get any widgets position?
5.19. How do I set the size of a widget/window? How do I prevent the user resizing my window?
5.20. How do I add a popup menu to my GTK+ application?
5.21. How do I disable or enable a widget, such as a button?
5.22. Shouldn't the text argument in the gtk_clist_* functions be declared const?
5.23. How do I render pixels (image data) to the screen?
5.24. How do I create a pixmap without having my window being realized/shown?
5.25. How do I do drag-and-drop?
5.26. Why does GTK+/GLib leak memory?
6. Development with GTK+: widget specific questions
6.1. How do I find out about the selection of a GtkList?
6.2. How do I stop the column headings of a GtkCList disappearing when the list is scrolled?
6.3. I don't want the user of my applications to enter text into a GtkCombo. Any idea?
6.4. How do I catch a combo box change?
6.5. How can I define a separation line in a menu?
6.6. How can I right justify a menu, such as Help?
6.7. How do I add some underlined accelerators to menu items?
6.8. How can I retrieve the text from a GtkMenuItem?
6.9. How do I right (or otherwise) justify a GtkLabel?
6.10. How do I set the background color of a GtkLabel widget?
6.11. How do I set the color and font of a GtkLabel using a Resource File?
6.12. How do I configure Tooltips in a Resource File?
6.13. I can't add more than (something like) 2000 chars in a GtkEntry. What's wrong?
6.14. How do I make a GtkEntry widget activate on pressing the Return key?
6.15. How do I validate/limit/filter the input to a GtkEntry?
6.16. How do I use horizontal scrollbars with a GtkText widget?
6.17. How do I change the font of a GtkText widget?
6.18. How do I set the cursor position in a GtkText object?
7. About GDK
7.1. What is GDK?
7.2. How do I use color allocation?
8. About GLib
8.1. What is GLib?
8.2. How can I use the doubly linked lists?
8.3. Memory does not seem to be released when I free the list nodes I've allocated
8.4. Why use g_print, g_malloc, g_strdup and fellow glib functions?
8.5. What's a GScanner and how do I use one?
9. GTK+ FAQ Contributions, Maintainers and Copyright

Chapter 1. General Information


1.7. Where is the documentation for GTK+?

Where is the documentation for GTK+?

In the GTK+ distribution's doc/ directory you will find the reference material for both GTK and GDK, this FAQ and the GTK Tutorial.

In addition, you can find links to HTML versions of these documents by going to http://www.gtk.org/. A packaged version of the GTK Tutorial, with SGML, HTML, Postscript, DVI and text versions can be found in ftp://ftp.gtk.org/pub/gtk/tutorial

There are now a couple of books available that deal with programming GTK+, GDK and GNOME:


1.10. How to report bugs in GTK+

How to report bugs in GTK+

Bugs should be reported to the GNOME bug tracking system (http://bugzilla.gnome.org/). You will need to enter your email address and receive a password before you can use the system to register a new bug report.

There are a number of options to select and boxes to fill in when submitting a bug report. Please remember that the more information you give, the easier it will be to track the problem down. Extra information that may prove useful includes:

  • How to reproduce the bug.

    If you can reproduce it with the testgtk program that is built in the gtk/ subdirectory, that will be most convenient. Otherwise, please include a short test program that exhibits the behavior. As a last resort, you can also provide a pointer to a larger piece of software that can be downloaded.

    (Bugs that can be reproduced within the GIMP are almost as good as bugs that can be reproduced in testgtk. If you are reporting a bug found with the GIMP, please include the version number of the GIMP you are using)

  • If the bug was a crash, the exact text that was printed out when the crash occurred.

  • Further information such as stack traces may be useful, but are not necessary. If you do send a stack trace, and the error is an X error, it will be more useful if the stacktrace is produced running the test program with the --sync command line option.


1.12. What applications have been written with GTK+?

What applications have been written with GTK+?

A list of some GTK+ based application can be found on the GTK+ web server at http://www.gtk.org/apps/ and contains more than 350 applications.

Failing that, look for a project to work on for the GNOME project, http://www.gnome.org/ Write a game. Write something that is useful.

Some of these are:


Chapter 2. How to find, configure, install, and troubleshoot GTK+


Chapter 3. Development of GTK+

3.1. Whats this CVS thing that everyone keeps talking about, and how do I access it?

Whats this CVS thing that everyone keeps talking about, and how do I access it?

CVS is the Concurrent Version System and is a very popular means of version control for software projects. It is designed to allow multiple authors to be able to simultanously operate on the same source tree. This source tree is centrally maintained, but each developer has a local mirror of this repository that they make their changes to.

The GTK+ developers use a CVS repository to store the master copy of the current development version of GTK+. As such, people wishing to contribute patches to GTK+ should generate them against the CVS version. Normal people should use the packaged releases.

The CVS toolset is available as RPM packages from the usual RedHat sites. The latest version is available at http://download.cyclic.com/pub/

Anyone can download the latest CVS version of GTK+ by using anonymous access using the following steps:

  • In a bourne shell descendant (e.g. bash) type:

    CVSROOT=':pserver:[email protected]:/cvs/gnome'
    export CVSROOT

  • Next, the first time the source tree is checked out, a cvs login is needed.

    cvs login

    This will ask you for a password. There is no password for cvs.gimp.org, so just enter a carriage return.

  • To get the tree and place it in a subdir of your current working directory, issue the command:

    cvs -z3 get gtk+

    Note that with the GTK+ 1.1 tree, glib has been moved to a separate CVS module, so if you don't have glib installed you will need to get that as well:

    cvs -z3 get glib


3.5. Is anyone working on bindings for languages other than C?

Is anyone working on bindings for languages other than C?

The GTK+ home page (http://www.gtk.org/) presents a list of GTK+ bindings.


Chapter 4. Development with GTK+: the begining

4.1. How do I get started?

How do I get started?

So, after you have installed GTK+ there are a couple of things that can ease you into developing applications with it. There is the GTK+ Tutorial http://www.gtk.org/tutorial/, which is undergoing development. This will introduce you to writing applications using C.

The Tutorial doesn't (yet) contain information on all of the widgets that are in GTK+. For example code on how to use the basics of all the GTK+ widgets you should look at the file gtk/testgtk.c (and associated source files) within the GTK+ distribution. Looking at these examples will give you a good grounding on what the widgets can do.


4.6. I want to add some configure stuff, how could I do this?

I want to add some configure stuff, how could I do this?

To use autoconf/automake, you must first install the relevant packages. These are:

  • the m4 preprocessor v1.4 or better
  • autoconf v2.13 or better
  • automake v1.4 or better

You'll find these packages on the GNU main ftp server (ftp://ftp.gnu.org/) or on any GNU mirror.

In order to use the powerful autoconf/automake scheme, you must create a configure.in which may look like:

dnl Process this file with autoconf to produce a configure script.
dnl configure.in for a GTK+ based program

AC_INIT(myprg.c)dnl
AM_INIT_AUTOMAKE(mypkgname,0.0.1)dnl
AM_CONFIG_HEADER(config.h)dnl

dnl Checks for programs.
AC_PROG_CC dnl check for the c compiler
dnl you should add CFLAGS="" here, 'cos it is set to -g by PROG_CC

dnl Checks for libraries.
AM_PATH_GTK(1.2.0,,AC_MSG_ERROR(mypkgname 0.1 needs GTK))dnl

AC_OUTPUT(
	Makefile
)dnl

You must add a Makefile.am file:

bin_PROGRAMS    = myprg
myprg_SOURCES   = myprg.c foo.c bar.c
INCLUDES        = @GTK_CFLAGS@
LDADD           = @GTK_LIBS@
CLEANFILES      = *~
DISTCLEANFILES  = .deps/*.P

If your project contains more than one subdirectory, you'll have to create one Makefile.am in each directory plus a master Makefile.am which will look like:

SUBDIRS         = mydir1 mydir2 mydir3

then, to use these, simply type the following commands:

aclocal
autoheader
autoconf
automake --add-missing --include-deps --foreign 

For further information, you should look at the autoconf and the automake documentation (the shipped info files are really easy to understand, and there are plenty of web resources that deal with autoconf and automake).


Chapter 5. Development with GTK+: general questions

Table of Contents
5.1. What widgets are in GTK?
5.2. Is GTK+ thread safe? How do I write multi-threaded GTK+ applications?
5.3. Why does this strange 'x io error' occur when I fork() in my GTK+ app?
5.4. Why don't the contents of a button move when the button is pressed? Here's a patch to make it work that way...
5.5. How do I identifiy a widgets top level window or other ancestor?
5.6. How do I get the Window ID of a GtkWindow?
5.7. How do I catch a double click event (in a list widget, for example)?
5.8. By the way, what are the differences between signals and events?
5.9. Data I pass to the delete_event (or other event) handler gets corrupted.
5.10. I have my signal connected to the the (whatever) event, but it seems I don't catch it. What's wrong?
5.11. I need to add a new signal to a GTK+ widget. Any idea?
5.12. Is it possible to get some text displayed which is truncated to fit inside its allocation?
5.13. How do I make my window modal? / How do I make a single window active?
5.14. Why doesn't my widget (e.g. progressbar) update?
5.15. How do I attach data to some GTK+ object/widget?
5.16. How do I remove the data I have attached to an object?
5.17. How do I reparent a widget?
5.18. How could I get any widgets position?
5.19. How do I set the size of a widget/window? How do I prevent the user resizing my window?
5.20. How do I add a popup menu to my GTK+ application?
5.21. How do I disable or enable a widget, such as a button?
5.22. Shouldn't the text argument in the gtk_clist_* functions be declared const?
5.23. How do I render pixels (image data) to the screen?
5.24. How do I create a pixmap without having my window being realized/shown?
5.25. How do I do drag-and-drop?
5.26. Why does GTK+/GLib leak memory?

5.2. Is GTK+ thread safe? How do I write multi-threaded GTK+ applications?

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.

Erik Mouw contributed the following code example to illustrate how to use threads within GTK+ programs.

/*-------------------------------------------------------------------------
 * Filename:      gtk-thread.c
 * Version:       0.99.1
 * Copyright:     Copyright (C) 1999, Erik Mouw
 * Author:        Erik Mouw <[email protected]>
 * Description:   GTK threads example. 
 * Created at:    Sun Oct 17 21:27:09 1999
 * Modified by:   Erik Mouw <[email protected]>
 * Modified at:   Sun Oct 24 17:21:41 1999
 *-----------------------------------------------------------------------*/
/*
 * Compile with:
 *
 * cc -o gtk-thread gtk-thread.c `pkg-config gtk+-2.0 --cflags --libs gthread`
 *
 * Thanks to Sebastian Wilhelmi and Owen Taylor for pointing out some
 * bugs.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <gtk/gtk.h>
#include <glib.h>
#include <pthread.h>

#define YES_IT_IS    (1)
#define NO_IT_IS_NOT (0)

typedef struct 
{
  GtkWidget *label;
  int what;
} yes_or_no_args;

G_LOCK_DEFINE_STATIC (yes_or_no);
static volatile int yes_or_no = YES_IT_IS;

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

void *argument_thread(void *args)
{
  yes_or_no_args *data = (yes_or_no_args *)args;
  gboolean say_something;

  for(;;)
    {
      /* sleep a while */
      sleep(rand() / (RAND_MAX / 3) + 1);

      /* lock the yes_or_no_variable */
      G_LOCK(yes_or_no);

      /* do we have to say something? */
      say_something = (yes_or_no != data->what);

      if(say_something)
	{
	  /* set the variable */
	  yes_or_no = data->what;
	}

      /* Unlock the yes_or_no variable */
      G_UNLOCK(yes_or_no);

      if(say_something)
	{
	  /* get GTK thread lock */
	  gdk_threads_enter();

	  /* set label text */
	  if(data->what == YES_IT_IS)
	    gtk_label_set_text(GTK_LABEL(data->label), "O yes, it is!");
	  else
	    gtk_label_set_text(GTK_LABEL(data->label), "O no, it isn't!");

	  /* release GTK thread lock */
	  gdk_threads_leave();
	}
    }

  return(NULL);
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *label;
  yes_or_no_args yes_args, no_args;
  pthread_t no_tid, yes_tid;

  /* init threads */
  g_thread_init(NULL);

  /* init gtk */
  gtk_init(&argc, &argv);

  /* init random number generator */
  srand((unsigned int)time(NULL));

  /* create a window */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

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

  gtk_container_set_border_width(GTK_CONTAINER (window), 10);

  /* create a label */
  label = gtk_label_new("And now for something completely different ...");
  gtk_container_add(GTK_CONTAINER(window), label);
  
  /* show everything */
  gtk_widget_show(label);
  gtk_widget_show (window);

  /* create the threads */
  yes_args.label = label;
  yes_args.what = YES_IT_IS;
  pthread_create(&yes_tid, NULL, argument_thread, &yes_args);

  no_args.label = label;
  no_args.what = NO_IT_IS_NOT;
  pthread_create(&no_tid, NULL, argument_thread, &no_args);

  /* enter the GTK main loop */
  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  return(0);
}

5.3. Why does this strange 'x io error' occur when I fork() in my GTK+ app?

Why does this strange 'x io error' occur when I fork() in my GTK+ app?

This is not really a GTK+ problem, and the problem is not related to fork() either. If the 'x io error' occurs then you probably use the exit() function in order to exit from the child process.

When GDK opens an X display, it creates a socket file descriptor. When you use the exit() function, you implicitly close all the open file descriptors, and the underlying X library really doesn't like this.

The right function to use here is _exit().

Erik Mouw contributed the following code example to illustrate handling fork() and exit().

/*-------------------------------------------------------------------------
 * Filename:      gtk-fork.c
 * Version:       0.99.1
 * Copyright:     Copyright (C) 1999, Erik Mouw
 * Author:        Erik Mouw <[email protected]>
 * Description:   GTK+ fork example
 * Created at:    Thu Sep 23 21:37:55 1999
 * Modified by:   Erik Mouw <[email protected]>
 * Modified at:   Thu Sep 23 22:39:39 1999
 *-----------------------------------------------------------------------*/
/*
 * Compile with:
 *
 * cc -o gtk-fork gtk-fork.c `pkg-config gtk+-2.0 --cflags --libs`
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <gtk/gtk.h>

void sigchld_handler(int num)
{
  sigset_t set, oldset;
  pid_t pid;
  int status, exitstatus;

  /* block other incoming SIGCHLD signals */
  sigemptyset(&set);
  sigaddset(&set, SIGCHLD);
  sigprocmask(SIG_BLOCK, &set, &oldset);

  /* wait for child */
  while((pid = waitpid((pid_t)-1, &status, WNOHANG)) > 0)
    {
      if(WIFEXITED(status))
	{
	  exitstatus = WEXITSTATUS(status);

	  fprintf(stderr, 
		  "Parent: child exited, pid = %d, exit status = %d\n", 
		  (int)pid, exitstatus);
	}
      else if(WIFSIGNALED(status))
	{
	  exitstatus = WTERMSIG(status);

	  fprintf(stderr,
		  "Parent: child terminated by signal %d, pid = %d\n",
		  exitstatus, (int)pid);
	}
      else if(WIFSTOPPED(status))
	{
	  exitstatus = WSTOPSIG(status);

	  fprintf(stderr,
		  "Parent: child stopped by signal %d, pid = %d\n",
		  exitstatus, (int)pid);
	}
      else
	{
	  fprintf(stderr,
		  "Parent: child exited magically, pid = %d\n",
		  (int)pid);
	}
    }

  /* re-install the signal handler (some systems need this) */
  signal(SIGCHLD, sigchld_handler);
  
  /* and unblock it */
  sigemptyset(&set);
  sigaddset(&set, SIGCHLD);
  sigprocmask(SIG_UNBLOCK, &set, &oldset);
}

gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
{
  return(FALSE);
}

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

void fork_me(GtkWidget *widget, gpointer data)
{
  pid_t pid;

  pid = fork();

  if(pid == -1)
    {
      /* ouch, fork() failed */
      perror("fork");
      exit(-1);
    }
  else if(pid == 0)
    {
      /* child */
      fprintf(stderr, "Child: pid = %d\n", (int)getpid());

      execlp("ls", "ls", "-CF", "/", NULL);
      
      /* if exec() returns, there is something wrong */
      perror("execlp");

      /* exit child. note the use of _exit() instead of exit() */
      _exit(-1);
    }
  else
    {
      /* parent */
      fprintf(stderr, "Parent: forked a child with pid = %d\n", (int)pid);
    }
}

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

  gtk_init(&argc, &argv);

  /* the basic stuff: make a window and set callbacks for destroy and
   * delete events 
   */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

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

#if (GTK_MAJOR_VERSION == 1) && (GTK_MINOR_VERSION == 0)
  gtk_container_border_width(GTK_CONTAINER (window), 10);
#else  
  gtk_container_set_border_width(GTK_CONTAINER (window), 10);
#endif

  /* add a button to do something usefull */
  button = gtk_button_new_with_label("Fork me!");
          
  gtk_signal_connect(GTK_OBJECT (button), "clicked",
		     GTK_SIGNAL_FUNC(fork_me), NULL);

  gtk_container_add(GTK_CONTAINER(window), button);
          
  /* show everything */
  gtk_widget_show (button);
  gtk_widget_show (window);


  /* install a signal handler for SIGCHLD signals */
  signal(SIGCHLD, sigchld_handler);

  
  /* main loop */
  gtk_main ();

  exit(0);         
}

5.8. By the way, what are the differences between signals and events?

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.19. How do I set the size of a widget/window? How do I prevent the user resizing my window?

How do I set the size of a widget/window? How do I prevent the user resizing my 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 these functions are:

void gtk_widget_set_usize (GtkWidget *widget,
                           gint width,
                           gint height);

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

allow_shrink = FALSE
allow_grow   = TRUE
auto_shrink  = FALSE

The gtk_widget_set_usize() functions is not the easiest way to set a window size since you cannot decrease this window size with another call to this function unless you call it twice, as in:

     gtk_widget_set_usize(your_widget, -1, -1);
     gtk_widget_set_usize(your_widget, new_x_size, new_y_size);

Another way to set the size of and/or move a window is to use the gdk_window_move_resize() function which uses to work fine both to grow or to shrink the window:

     gdk_window_move_resize(window->window, 
                            x_pos, y_pos, 
                            x_size, y_size);

Chapter 6. Development with GTK+: widget specific questions

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

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:

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:

{
        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");
}

6.5. How can I define a separation line in a menu?

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_shell_append(GTK_MENU_SHELL(menu), menuitem);
gtk_widget_show(menuitem);

6.7. How do I add some underlined accelerators to menu items?

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

6.15. How do I validate/limit/filter the input to a GtkEntry?

How do I validate/limit/filter the input to a GtkEntry?

If you want to validate the text that a user enters into a GtkEntry widget you can attach to the "insert_text" signal of the entry, and modify the text within the callback function. The example below forces all characters to uppercase, and limits the range of characters to A-Z. Note that the entry is cast to an object of type GtkEditable, from which GtkEntry is derived.

#include <ctype.h>
#include <gtk/gtk.h>

void insert_text_handler (GtkEntry    *entry,
                          const gchar *text,
                          gint         length,
                          gint        *position,
                          gpointer     data)
{
  GtkEditable *editable = GTK_EDITABLE(entry);
  int i, count=0;
  gchar *result = g_new (gchar, length);

  for (i=0; i < length; i++) {
    if (!isalpha(text[i]))
      continue;
    result[count++] = islower(text[i]) ? toupper(text[i]) : text[i];
  }
  
  if (count > 0) {
    gtk_signal_handler_block_by_func (GTK_OBJECT (editable),
				      GTK_SIGNAL_FUNC (insert_text_handler),
				      data);
    gtk_editable_insert_text (editable, result, count, position);
    gtk_signal_handler_unblock_by_func (GTK_OBJECT (editable),
					GTK_SIGNAL_FUNC (insert_text_handler),
					data);
  }
  gtk_signal_emit_stop_by_name (GTK_OBJECT (editable), "insert_text");
  
  g_free (result);
}

int main (int   argc,
          char *argv[])
{
  GtkWidget *window;
  GtkWidget *entry;
  
  gtk_init (&argc, &argv);
  
  /* create a new window */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
  gtk_signal_connect(GTK_OBJECT (window), "delete_event",
		     (GtkSignalFunc) gtk_exit, NULL);
  
  entry = gtk_entry_new();
  gtk_signal_connect(GTK_OBJECT(entry), "insert_text",
		     GTK_SIGNAL_FUNC(insert_text_handler),
		     NULL);
  gtk_container_add(GTK_CONTAINER (window), entry);
  gtk_widget_show(entry);
  
  gtk_widget_show(window);
  
  gtk_main();
  return(0);
}

6.18. How do I set the cursor position in a GtkText object?

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.


Chapter 7. About GDK


7.2. How do I use color allocation?

How do I use color allocation?

One of the nice things about GDK is that it's based on top of Xlib; this is also a problem, especially in the area of color management. If you want to use color in your program (drawing a rectangle or such, your code should look something like this:

{
  GdkColor *color;
  int width, height;
  GtkWidget *widget;
  GdkGC *gc;

  ...
  
  /* first, create a GC to draw on */
  gc = gdk_gc_new(widget->window);

  /* find proper dimensions for rectangle */
  gdk_window_get_size(widget->window, &width, &height);

  /* the color we want to use */
  color = (GdkColor *)malloc(sizeof(GdkColor));
  
  /* red, green, and blue are passed values, indicating the RGB triple
   * of the color we want to draw. Note that the values of the RGB components
   * within the GdkColor are taken from 0 to 65535, not 0 to 255.
   */
  color->red = red * (65535/255);
  color->green = green * (65535/255);
  color->blue = blue * (65535/255);
  
  /* the pixel value indicates the index in the colormap of the color.
   * it is simply a combination of the RGB values we set earlier
   */
  color->pixel = (gulong)(red*65536 + green*256 + blue);

  /* However, the pixel valule is only truly valid on 24-bit (TrueColor)
   * displays. Therefore, this call is required so that GDK and X can
   * give us the closest color available in the colormap
   */
  gdk_color_alloc(gtk_widget_get_colormap(widget), color);

  /* set the foreground to our color */
  gdk_gc_set_foreground(gc, color);
  
  /* draw the rectangle */
  gdk_draw_rectangle(widget->window, gc, 1, 0, 0, width, height);

  ...
}

Chapter 8. About GLib


8.3. Memory does not seem to be released when I free the list nodes I've allocated

Memory does not seem to be released when I free the list nodes I've allocated

GLib tries to be "intelligent" on this special issue: it assumes that you are likely to reuse the objects, so caches the allocated memory. If you do not want to use this behavior, you'll probably want to set up a special allocator.

To quote Tim Janik:

"If you have a certain portion of code that uses *lots* of GLists or GNodes, and you know you'd better want to release all of them after a short while, you'd want to use a GAllocator. Pushing an allocator into g_list will make all subsequent glist operations private to that allocator's memory pool (and thus you have to take care to pop the allocator again, before making any external calls): "

GAllocator *allocator;
GList *list = NULL;
guint i;

/* set a new allocation pool for GList nodes */
allocator = g_allocator_new ("list heap", 1024);
g_list_push_allocator (allocator);

/* do some list operations */
for (i = 0; i < 4096; i++)
  list = g_list_prepend (list, NULL);
list = g_list_reverse (list);

/* beware to pop allocator befor calling external functions */
g_list_pop_allocator ();
gtk_label_set_text (GTK_LABEL (some_label), "some text");

/* and set our private glist pool again */
g_list_push_allocator (allocator);

/* do some list operations */
g_list_free (list);
list = NULL;
for (i = 0; i < 4096; i++)
  list = g_list_prepend (list, NULL);
  
/* and back out (while freeing all of the list nodes in our pool) */
g_list_pop_allocator ();
g_allocator_free (allocator);

8.5. What's a GScanner and how do I use one?

What's a GScanner and how do I use one?

A GScanner will tokenize your text, that is, it'll return an integer for every word or number that appears in its input stream, following certain (customizable) rules to perform this translation. You still need to write the parsing functions on your own though.

Here's a little test program supplied by Tim Janik that will parse

<SYMBOL> = <OPTIONAL-MINUS> <NUMBER> ;

constructs, while skipping "#\n" and "/**/" style comments.

#include <glib.h>

/* some test text to be fed into the scanner */
static const gchar *test_text =
( "ping = 5;\n"
  "/* slide in some \n"
  " * comments, just for the\n"
  " * fun of it \n"
  " */\n"
  "pong = -6; \n"
  "\n"
  "# the next value is a float\n"
  "zonk = 0.7;\n"
  "# redefine ping\n"
  "ping = - 0.5;\n" );

/* define enumeration values to be returned for specific symbols */
enum {
  SYMBOL_PING = G_TOKEN_LAST + 1,
  SYMBOL_PONG = G_TOKEN_LAST + 2,
  SYMBOL_ZONK = G_TOKEN_LAST + 3
};

/* symbol array */
static const struct {
  gchar *symbol_name;
  guint  symbol_token;
} symbols[] = {
  { "ping", SYMBOL_PING, },
  { "pong", SYMBOL_PONG, },
  { "zonk", SYMBOL_ZONK, },
  { NULL, 0, },
}, *symbol_p = symbols;

static gfloat ping = 0;
static gfloat pong = 0;
static gfloat zonk = 0;

static guint
parse_symbol (GScanner *scanner)
{
  guint symbol;
  gboolean negate = FALSE;

  /* expect a valid symbol */
  g_scanner_get_next_token (scanner);
  symbol = scanner->token;
  if (symbol < SYMBOL_PING ||
      symbol > SYMBOL_ZONK)
    return G_TOKEN_SYMBOL;

  /* expect '=' */
  g_scanner_get_next_token (scanner);
  if (scanner->token != '=')
    return '=';

  /* feature optional '-' */
  g_scanner_peek_next_token (scanner);
  if (scanner->next_token == '-')
    {
      g_scanner_get_next_token (scanner);
      negate = !negate;
    }

  /* expect a float (ints are converted to floats on the fly) */
  g_scanner_get_next_token (scanner);
  if (scanner->token != G_TOKEN_FLOAT)
    return G_TOKEN_FLOAT;

  /* make sure the next token is a ';' */
  if (g_scanner_peek_next_token (scanner) != ';')
    {
      /* not so, eat up the non-semicolon and error out */
      g_scanner_get_next_token (scanner);
      return ';';
    }

  /* assign value, eat the semicolon and exit successfully */
  switch (symbol)
    {
    case SYMBOL_PING:
      ping = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    case SYMBOL_PONG:
      pong = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    case SYMBOL_ZONK:
      zonk = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    }
  g_scanner_get_next_token (scanner);

  return G_TOKEN_NONE;
}

int
main (int argc, char *argv[])
{
  GScanner *scanner;
  guint expected_token;

  scanner = g_scanner_new (NULL);

  /* adjust lexing behaviour to suit our needs
   */
  /* convert non-floats (octal values, hex values...) to G_TOKEN_INT */
  scanner->config->numbers_2_int = TRUE;
  /* convert G_TOKEN_INT to G_TOKEN_FLOAT */
  scanner->config->int_2_float = TRUE;
  /* don't return G_TOKEN_SYMBOL, but the symbol's value */
  scanner->config->symbol_2_token = TRUE;

  /* load symbols into the scanner */
  while (symbol_p->symbol_name)
    {
      g_scanner_add_symbol (scanner,
                            symbol_p->symbol_name,
                            GINT_TO_POINTER (symbol_p->symbol_token));
      symbol_p++;
    }

  /* feed in the text */
  g_scanner_input_text (scanner, test_text, strlen (test_text));

  /* give the error handler an idea on how the input is named */
  scanner->input_name = "test text";

  /* scanning loop, we parse the input until its end is reached,
   * the scanner encountered a lexing error, or our sub routine came
   * across invalid syntax
   */
  do
    {
      expected_token = parse_symbol (scanner);
      
      g_scanner_peek_next_token (scanner);
    }
  while (expected_token == G_TOKEN_NONE &&
         scanner->next_token != G_TOKEN_EOF &&
         scanner->next_token != G_TOKEN_ERROR);

  /* give an error message upon syntax errors */
  if (expected_token != G_TOKEN_NONE)
    g_scanner_unexp_token (scanner, expected_token, NULL, "symbol", NULL, NULL, TRUE);

  /* finsish parsing */
  g_scanner_destroy (scanner);

  /* print results */
  g_print ("ping: %f\n", ping);
  g_print ("pong: %f\n", pong);
  g_print ("zonk: %f\n", zonk);
  
  return 0;
}

You need to understand that the scanner will parse its input and tokenize it, it is up to you to interpret these tokens, not define their types before they get parsed, e.g. watch gscanner parse a string:

"hi i am 17"
| | | |
| | | v
| | v TOKEN_INT, value: 17
| v TOKEN_IDENTIFIER, value: "am"
v TOKEN_CHAR, value: 'i'
TOKEN_IDENTIFIER, value: "hi"

If you configure the scanner with:

scanner->config->int_2_float = TRUE;
scanner->config->char_2_token = TRUE;
scanner->config->scan_symbols = TRUE;

and add "am" as a symbol with

g_scanner_add_symbol (scanner, "am", "symbol value");

GScanner will parse it as

"hi i am 17"
| | | |
| | | v
| | v TOKEN_FLOAT, value: 17.0 (automatic int->float conversion)
| | TOKEN_SYMBOL, value: "symbol value" (a successfull hash table lookup
| | turned a TOKEN_IDENTIFIER into a
| | TOKEN_SYMBOL and took over the
| v symbol's value)
v 'i' ('i' can be a valid token as well, as all chars >0 and <256)
TOKEN_IDENTIFIER, value: "hi"

You need to match the token sequence with your code, and if you encounter something that you don't want, you error out:

/* expect an identifier ("hi") */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_IDENTIFIER)
  return G_TOKEN_IDENTIFIER;
/* expect a token 'i' */
g_scanner_get_next_token (scanner);
if (scanner->token != 'i')
  return 'i';
/* expect a symbol ("am") */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_SYMBOL)
  return G_TOKEN_SYMBOL;
/* expect a float (17.0) */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_FLOAT)
  return G_TOKEN_FLOAT;

If you got past here, you have parsed "hi i am 17" and would have accepted "dooh i am 42" and "bah i am 0.75" as well, but you would have not accepted "hi 7 am 17" or "hi i hi 17".


Chapter 9. GTK+ FAQ Contributions, Maintainers and Copyright

If you would like to make a contribution to the FAQ, send either one of us an e-mail message with the exact text you think should be included (question and answer). With your help, this document can grow and become more useful!

This document is maintained by Tony Gale mailto:[email protected] Nathan Froyd mailto:[email protected], and Emmanuel Deloget mailto:[email protected]. This FAQ was created by Shawn T. Amundson mailto:[email protected] who continues to provide support. Contributions should be sent to Tony Gale mailto:[email protected]

The GTK+ FAQ is Copyright (C) 1997-2000 by Shawn T. Amundson, Tony Gale, Emmanuel Deloget and Nathan Froyd.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this document under the conditions for verbatim copying, provided that this copyright notice is included exactly as in the original, and that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this document into another language, under the above conditions for modified versions.

If you are intending to incorporate this document into a published work, please contact one of the maintainers, and we will make an effort to ensure that you have the most up to date information available.

There is no guarentee that this document lives up to its intended purpose. This is simply provided as a free resource. As such, the authors and maintainers of the information provided within can not make any guarentee that the information is even accurate.