歡迎您光臨本站 註冊首頁

給GTK+初學者------英文版

←手機掃碼閱讀     火星人 @ 2014-03-25 , reply:0

GTK Tutorial

1. Introduction

  GTK (GIMP Toolkit) is a library for creating graphical user interfaces. It is licensed using the LGPL license, so you can develop open software, free software, or even commercial non-free software using GTK without having to spend anything for
licenses or royalties.

   It's called the GIMP toolkit because it was originally written for developing the GNU Image Manipulation Program (GIMP), but GTK has now been used in a large number of software projects, including the GNU Network Object Model Environment (GNOME)
project. GTK is built on top of GDK (GIMP Drawing Kit) which is basically a wrapper around the low-level functions for accessing the underlying windowing functions (Xlib in the case of the X windows system). The primary authors of GTK are:

  Peter Mattis petm@xcf.berkeley.edu

  Spencer Kimball spencer@xcf.berkeley.edu

  Josh MacDonald jmacd@xcf.berkeley.edu

   GTK is essentially an object oriented application programmers interface (API). Although written completely in C, it is implemented using the idea of classes and callback functions (pointers to functions).

   There is also a third component called GLib which contains a few replacements for some standard calls, as well as some additional functions for handling linked lists, etc. The replacement functions are used to increase GTK's portability, as some
of the functions implemented here are not available or are nonstandard on other unixes such as g_strerror(). Some also contain enhancements to the libc versions, such as g_malloc that has enhanced debugging utilities.

   This tutorial describes the C interface to GTK. There are GTK bindings for many other languages including C++, Guile, Perl, Python, TOM, Ada95, Objective C, Free Pascal, and Eiffel. If you intend to use another language's bindings to GTK, look at
that binding's documentation first. In some cases that documentation may describe some important conventions (which you should know first) and then refer you back to this tutorial. There are also some cross-platform APIs (such as wxWindows and V)
which use GTK as one of their target platforms; again, consult their documentation first.

  If you're developing your GTK application in C++, a few extra notes are in order. There's a C++ binding to GTK called GTK--, which provides a more C++-like interface to GTK; you should probably look into this instead. If you don't like that
approach for whatever reason, there are two alternatives for using GTK. First, you can use only the C subset of C++ when interfacing with GTK and then use the C interface as described in this tutorial. Second, you can use GTK and C++ together by
declaring all callbacks as static functions in C++ classes, and again calling GTK using its C interface. If you choose this last approach, you can include as the callback's data value a pointer to the object to be manipulated (the so-called "this"
value). Selecting between these options is simply a matter of preference, since in all three approaches you get C++ and GTK. None of these approaches requires the use of a specialized preprocessor, so no matter what you choose you can use standard C++
with GTK.

  This tutorial is an attempt to document as much as possible of GTK, but it is by no means complete. This tutorial assumes a good understanding of C, and how to create C programs. It would be a great benefit for the reader to have previous X
programming experience, but it shouldn't be necessary. If you are learning GTK as your first widget set, please comment on how you found this tutorial, and what you had trouble with. There are also C++, Objective C, ADA, Guile and other language
bindings available, but I don't follow these.

  This document is a "work in progress". Please look for updates on http://www.gtk.org/.

   I would very much like to hear of any problems you have learning GTK from this document, and would appreciate input as to how it may be improved. Please see the section on Contributing for further information.

2. Getting Started

  The first thing to do, of course, is download the GTK source and install it. You can always get the latest version from ftp.gtk.org in /pub/gtk. You can also view other sources of GTK information on http://www.gtk.org/. GTK uses GNU autoconf for
configuration. Once untar'd, type ./configure --help to see a list of options.

   The GTK source distribution also contains the complete source to all of the examples used in this tutorial, along with Makefiles to aid compilation.

  To begin our introduction to GTK, we'll start with the simplest program possible. This program will create a 200x200 pixel window and has no way of exiting except to be killed by using the shell.


/* example-start base base.c */
#include
int main( int argc,
char *argv[] )
{
GtkWidget *window;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_widget_show(window);
gtk_main ();
return(0);
}
/* example-end */

  You can compile the above program with gcc using:

  gcc base.c -o base `gtk-config --cflags --libs`

  The meaning of the unusual compilation options is explained below in Compiling Hello World.

   All programs will of course include gtk/gtk.h which declares the variables, functions, structures, etc. that will be used in your GTK application.

  The next line:


gtk_init (&argc, &argv);

  calls the function gtk_init(gint *argc, gchar ***argv) which will be called in all GTK applications. This sets up a few things for us such as the default visual and color map and then proceeds to call gdk_init(gint *argc, gchar ***argv). This
function initializes the library for use, sets up default signal handlers, and checks the arguments passed to your application on the command line, looking for one of the following:

  --gtk-module

  --g-fatal-warnings

  --gtk-debug

  --gtk-no-debug

  --gdk-debug

  --gdk-no-debug

  --display

  --sync

  --no-xshm

  --name

  --class

  It removes these from the argument list, leaving anything it does not recognize for your application to parse or ignore. This creates a set of standard arguments accepted by all GTK applications.

  The next two lines of code create and display a window.


window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_widget_show (window);

   The GTK_WINDOW_TOPLEVEL argument specifies that we want the window to undergo window manager decoration and placement. Rather than create a window of 0x0 size, a window without children is set to 200x200 by default so you can still manipulate it.

  The gtk_widget_show() function lets GTK know that we are done setting the attributes of this widget, and that it can display it.

  The last line enters the GTK main processing loop.

gtk_main ();

  gtk_main() is another call you will see in every GTK application. When control reaches this point, GTK will sleep waiting for X events (such as button or key presses), timeouts, or file IO notifications to occur. In our simple example, however,
events are ignored.

2.1 Hello World in GTK

  Now for a program with a widget (a button). It's the classic hello world a la GTK.


/* example-start helloworld helloworld.c */
#include
/* 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
");
}
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
");
/* 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. Arguments are parsed
* from the command line and are returned to the application. */
gtk_init(&argc, &argv);
/* create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* When the window is given the "delete_event" signal (this is given
* by the window manager, usually by the "close" option, or on the
* titlebar), we ask it to call the delete_event () function
* as defined above. The data passed to the callback
* function is NULL and is ignored in the callback function. */
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete_event), NULL);
/* Here we connect the "destroy" event to a signal handler.
* This event occurs when we call gtk_widget_destroy() on the window,
* or if we return FALSE in the "delete_event" callback. */
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (destroy), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Creates a new button with the label "Hello World". */
button = gtk_button_new_with_label ("Hello World");
/* When the button receives the "clicked" signal, it will call the
* function hello() passing it NULL as its argument.The hello()
* function is defined above. */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (hello), NULL);
/* This will cause the window to be destroyed by calling
* gtk_widget_destroy(window) when "clicked".Again, the destroy
* signal could come from here, or the window manager. */
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (gtk_widget_destroy),
GTK_OBJECT (window));
/* This packs the button into the window (a gtk container). */
gtk_container_add (GTK_CONTAINER (window), button);
/* The final step is to display this newly created widget. */
gtk_widget_show (button);
/* and the window */
gtk_widget_show (window);
/* All GTK applications must have a gtk_main(). Control ends here
* and waits for an event to occur (like a key press or
* mouse event). */
gtk_main ();
return(0);
}
/* example-end */

2.2 Compiling Hello World

  To compile use:


gcc -Wall -g helloworld.c -o helloworld `gtk-config --cflags`
`gtk-config --libs`

  This uses the program gtk-config, which comes with GTK. This program "knows" what compiler switches are needed to compile programs that use GTK. gtk-config --cflags will output a list of include directories for the compiler to look in, and
gtk-config --libs will output the list of libraries for the compiler to link with and the directories to find them in. In the above example they could have been combined into a single instance, such as `gtk-config --cflags --libs`.

  Note that the type of single quote used in the compile command above is significant.

  The libraries that are usually linked in are:

  The GTK library (-lgtk), the widget library, based on top of GDK.

  The GDK library (-lgdk), the Xlib wrapper.

  The gmodule library (-lgmodule), which is used to load run time extensions.

  The GLib library (-lglib), containing miscellaneous functions; only g_print() is used in this particular example. GTK is built on top of glib so you will always require this library. See the section on GLib for details.

  The Xlib library (-lX11) which is used by GDK.

  The Xext library (-lXext). This contains code for shared memory pixmaps and other X extensions.

  The math library (-lm). This is used by GTK for various purposes.

2.3 Theory of Signals and Callbacks

  Before we look in detail at helloworld, we'll discuss signals and callbacks. GTK is an event driven toolkit, which means it will sleep in gtk_main until an event occurs and control is passed to the appropriate function.

  This passing of control is done using the idea of "signals". (Note that these signals are not the same as the Unix system signals, and are not implemented using them, although the terminology is almost identical.) When an event occurs, such as the
press of a mouse button, the appropriate signal will be "emitted" by the widget that was pressed. This is how GTK does most of its useful work. There are signals that all widgets inherit, such as "destroy", and there are signals that are widget
specific, such as "toggled" on a toggle button.

  To make a button perform an action, we set up a signal handler to catch these signals and call the appropriate function. This is done by using a function such as:


gint gtk_signal_connect( GtkObject *object,
gchar *name,
GtkSignalFuncfunc,
gpointer func_data );

   where the first argument is the widget which will be emitting the signal, and the second the name of the signal you wish to catch. The third is the function you wish to be called when it is caught, and the fourth, the data you wish to have passed
to this function.

  The function specified in the third argument is called a "callback function", and should generally be of the form


void callback_func( GtkWidget *widget,
gpointer callback_data );

   where the first argument will be a pointer to the widget that emitted the signal, and the second a pointer to the data given as the last argument to the gtk_signal_connect() function as shown above.

   Note that the above form for a signal callback function declaration is only a general guide, as some widget specific signals generate different calling parameters. For example, the CList "select_row" signal provides both row and column parameters.

  Another call used in the helloworld example, is:


gint gtk_signal_connect_object( GtkObject *object,
gchar *name,
GtkSignalFuncfunc,
GtkObject *slot_object );

  gtk_signal_connect_object() is the same as gtk_signal_connect() except that the callback function only uses one argument, a pointer to a GTK object. So when using this function to connect signals, the callback should be of the form


void callback_func( GtkObject *object );

   where the object is usually a widget. We usually don't setup callbacks for gtk_signal_connect_object however. They are usually used to call a GTK function that accepts a single widget or object as an argument, as is the case in our helloworld
example.

   The purpose of having two functions to connect signals is simply to allow the callbacks to have a different number of arguments. Many functions in the GTK library accept only a single GtkWidget pointer as an argument, so you want to use the
gtk_signal_connect_object() for these, whereas for your functions, you may need to have additional data supplied to the callbacks.

2.4 Events

  In addition to the signal mechanism described above, there is a set of events that reflect the X event mechanism. Callbacks may also be attached to these events. These events are:


event
button_press_event
button_release_event
motion_notify_event
delete_event
destroy_event
expose_event
key_press_event
key_release_event
enter_notify_event
leave_notify_event
configure_event
focus_in_event
focus_out_event
map_event
unmap_event
property_notify_event
selection_clear_event
selection_request_event
selection_notify_event
proximity_in_event
proximity_out_event
drag_begin_event
drag_request_event
drag_end_event
drop_enter_event
drop_leave_event
drop_data_available_event
other_event

  In order to connect a callback function to one of these events, you use the function gtk_signal_connect, as described above, using one of the above event names as the name parameter. The callback function for events has a slightly different form
than that for signals:


void callback_func( GtkWidget *widget,
GdkEvent*event,
gpointer callback_data );

   GdkEvent is a C union structure whose type will depend upon which of the above events has occurred. In order for us to tell which event has been issued each of the possible alternatives has a type parameter which reflects the event being issued.
The other components of the event structure will depend upon the type of the event. Possible values for the type are:


GDK_NOTHING
GDK_DELETE
GDK_DESTROY
GDK_EXPOSE
GDK_MOTION_NOTIFY
GDK_BUTTON_PRESS
GDK_2BUTTON_PRESS
GDK_3BUTTON_PRESS
GDK_BUTTON_RELEASE
GDK_KEY_PRESS
GDK_KEY_RELEASE
GDK_ENTER_NOTIFY
GDK_LEAVE_NOTIFY
GDK_FOCUS_CHANGE
GDK_CONFIGURE
GDK_MAP
GDK_UNMAP
GDK_PROPERTY_NOTIFY
GDK_SELECTION_CLEAR
GDK_SELECTION_REQUEST
GDK_SELECTION_NOTIFY
GDK_PROXIMITY_IN
GDK_PROXIMITY_OUT
GDK_DRAG_BEGIN
GDK_DRAG_REQUEST
GDK_DROP_ENTER
GDK_DROP_LEAVE
GDK_DROP_DATA_AVAIL
GDK_CLIENT_EVENT
GDK_VISIBILITY_NOTIFY
GDK_NO_EXPOSE
GDK_OTHER_EVENT /* Deprecated, use filters instead */

  So, to connect a callback function to one of these events we would use something like:


gtk_signal_connect( GTK_OBJECT(button), "button_press_event",
GTK_SIGNAL_FUNC(button_press_callback),
NULL);

  This assumes that button is a Button widget. Now, when the mouse is over the button and a mouse button is pressed, the function button_press_callback will be called. This function may be declared as:


static gint button_press_callback( GtkWidget*widget,
GdkEventButton *event,
gpointerdata );

   Note that we can declare the second argument as type GdkEventButton as we know what type of event will occur for this function to be called.

   The value returned from this function indicates whether the event should be propagated further by the GTK event handling mechanism. Returning TRUE indicates that the event has been handled, and that it should not propagate further. Returning FALSE
continues the normal event handling. See the section on Advanced Event and Signal Handling for more details on this propagation process.

  For details on the GdkEvent data types, see the appendix entitled GDK Event Types.

2.5 Stepping Through Hello World

  Now that we know the theory behind this, let's clarify by walking through the example helloworld program.

   Here is the callback function that will be called when the button is "clicked". We ignore both the widget and the data in this example, but it is not hard to do things with them. The next example will use the data argument to tell us which button
was pressed.


void hello( GtkWidget *widget,
gpointer data )
{
g_print ("Hello World
");
}

   The next callback is a bit special. The "delete_event" occurs when the window manager sends this event to the application. We have a choice here as to what to do about these events. We can ignore them, make some sort of response, or simply quit
the application.

   The value you return in this callback lets GTK know what action to take. By returning TRUE, we let it know that we don't want to have the "destroy" signal emitted, keeping our application running. By returning FALSE, we ask that "destroy" be
emitted, which in turn will call our "destroy" signal handler.


gint delete_event( GtkWidget *widget,
GdkEvent*event,
gpointer data )
{
g_print ("delete event occurred
");
return (TRUE);
}

   Here is another callback function which causes the program to quit by calling gtk_main_quit(). This function tells GTK that it is to exit from gtk_main when control is returned to it.


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

  I assume you know about the main() function... yes, as with other applications, all GTK applications will also have one of these.


int main( int argc,
char *argv[] )

  This next part declares pointers to a structure of type GtkWidget. These are used below to create a window and a button.


GtkWidget *window;
GtkWidget *button;

  Here is our gtk_init again. As before, this initializes the toolkit, and parses the arguments found on the command line. Any argument it recognizes from the command line, it removes from the list, and modifies argc and argv to make it look like
they never existed, allowing your application to parse the remaining arguments.


gtk_init (&argc, &argv);

   Create a new window. This is fairly straightforward. Memory is allocated for the GtkWidget *window structure so it now points to a valid structure. It sets up a new window, but it is not displayed until we call gtk_widget_show(window) near the end
of our program.


window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  Here are two examples of connecting a signal handler to an object, in this case, the window. Here, the "delete_event" and "destroy" signals are caught. The first is emitted when we use the window manager to kill the window, or when we use the
gtk_widget_destroy() call passing in the window widget as the object to destroy. The second is emitted when, in the "delete_event" handler, we return FALSE.

   The GTK_OBJECT and GTK_SIGNAL_FUNC are macros that perform type casting and checking for us, as well as aid the readability of the code.


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

   This next function is used to set an attribute of a container object. This just sets the window so it has a blank area along the inside of it 10 pixels wide where no widgets will go. There are other similar functions which we will look at in the
section on Setting Widget Attributes

  And again, GTK_CONTAINER is a macro to perform type casting.


gtk_container_set_border_width (GTK_CONTAINER (window), 10);

   This call creates a new button. It allocates space for a new GtkWidget structure in memory, initializes it, and makes the button pointer point to it. It will have the label "Hello World" on it when displayed.


button = gtk_button_new_with_label ("Hello World");

  Here, we take this button, and make it do something useful. We attach a signal handler to it so when it emits the "clicked" signal, our hello() function is called. The data is ignored, so we simply pass in NULL to the hello() callback function.
Obviously, the "clicked" signal is emitted when we click the button with our mouse pointer.


gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (hello), NULL);

   We are also going to use this button to exit our program. This will illustrate how the "destroy" signal may come from either the window manager, or our program. When the button is "clicked", same as above, it calls the first hello() callback
function, and then this one in the order they are set up. You may have as many callback functions as you need, and all will be executed in the order you connected them. Because the gtk_widget_destroy() function accepts only a GtkWidget *widget as an
argument, we use the gtk_signal_connect_object() function here instead of straight gtk_signal_connect().


gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (gtk_widget_destroy),
GTK_OBJECT (window));

  This is a packing call, which will be explained in depth later on in Packing Widgets. But it is fairly easy to understand. It simply tells GTK that the button is to be placed in the window where it will be displayed. Note that a GTK container can
only contain one widget. There are other widgets, that are described later, which are designed to layout multiple widgets in various ways.


gtk_container_add (GTK_CONTAINER (window), button);

   Now we have everything set up the way we want it to be. With all the signal handlers in place, and the button placed in the window where it should be, we ask GTK to "show" the widgets on the screen. The window widget is shown last so the whole
window will pop up at once rather than seeing the window pop up, and then the button form inside of it. Although with such a simple example, you'd never notice.


gtk_widget_show (button);
gtk_widget_show (window);

  And of course, we call gtk_main() which waits for events to come from the X server and will call on the widgets to emit signals when these events come.


gtk_main ();

  And the final return. Control returns here after gtk_quit() is called.


return (0);

  Now, when we click the mouse button on a GTK button, the widget emits a "clicked" signal. In order for us to use this information, our program sets up a signal handler to catch that signal, which dispatches the function of our choice. In our
example, when the button we created is "clicked", the hello() function is called with a NULL argument, and then the next handler for this signal is called. This calls the gtk_widget_destroy() function, passing it the window widget as its argument,
destroying the window widget. This causes the window to emit the "destroy" signal, which is caught, and calls our destroy() callback function, which simply exits GTK.

   Another course of events is to use the window manager to kill the window, which will cause the "delete_event" to be emitted. This will call our "delete_event" handler. If we return TRUE here, the window will be left as is and nothing will happen.
Returning FALSE will cause GTK to emit the "destroy" signal which of course calls the "destroy" callback, exiting GTK.

3. Moving On

3.1 Data Types

   There are a few things you probably noticed in the previous examples that need explaining. The gint, gchar, etc. that you see are typedefs to int and char, respectively, that are part of the GLlib system. This is done to get around that nasty
dependency on the size of simple data types when doing calculations.

   A good example is "gint32" which will be typedef'd to a 32 bit integer for any given platform, whether it be the 64 bit alpha, or the 32 bit i386. The typedefs are very straightforward and intuitive. They are all defined in glib/glib.h (which gets
included from gtk.h).

   You'll also notice GTK's ability to use GtkWidget when the function calls for an Object. GTK is an object oriented design, and a widget is an object.

3.2 More on Signal Handlers

  Lets take another look at the gtk_signal_connect declaration.


gint gtk_signal_connect( GtkObject *object,
gchar *name,
GtkSignalFunc func,
gpointer func_data );

  Notice the gint return value? This is a tag that identifies your callback function. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached.

  This tag allows you to remove this callback from the list by using:


void gtk_signal_disconnect( GtkObject *object,gint id );

  So, by passing in the widget you wish to remove the handler from, and the tag returned by one of the signal_connect functions, you can disconnect a signal handler.

   You can also temporarily disable signal handlers with the gtk_signal_handler_block() and gtk_signal_handler_unblock() family of functions.


void gtk_signal_handler_block( GtkObject *object,guinthandler_id );
void gtk_signal_handler_block_by_func( GtkObject *object,
GtkSignalFuncfunc,gpointer data );
void gtk_signal_handler_block_by_data( GtkObject *object,
gpointer data );
void gtk_signal_handler_unblock( GtkObject *object,
guinthandler_id );
void gtk_signal_handler_unblock_by_func( GtkObject *object,
GtkSignalFuncfunc,gpointer data );
void gtk_signal_handler_unblock_by_data( GtkObject *object,
gpointer data);

3.3 An Upgraded Hello World

   Let's take a look at a slightly improved helloworld with better examples of callbacks. This will also introduce us to our next topic, packing widgets.


/* example-start helloworld2 helloworld2.c */
#include
/* Our new improved callback.The data passed to this function
* is printed to stdout. */
void callback( GtkWidget *widget,gpointer data )
{
g_print ("Hello again - %s was pressed
", (char *) data);
}
/* another callback */
gint delete_event( GtkWidget *widget,
GdkEvent*event,gpointer data )
{
gtk_main_quit();
return(FALSE);
}
int main( int argc,char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *button;
GtkWidget *box1;
/* This is called in all GTK applications. Arguments are parsed
* from the command line and are returned to the application. */
gtk_init (&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* This is a new call, which just sets the title of our
* new window to "Hello Buttons!" */
gtk_window_set_title (GTK_WINDOW (window), "Hello Buttons!");
/* Here we just set a handler for delete_event that immediately
* exits GTK. */
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete_event), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* We create a box to pack widgets into.This is described in detail
* in the "packing" section. The box is not really visible, it
* is just used as a tool to arrange widgets. */
box1 = gtk_hbox_new(FALSE, 0);
/* Put the box into the main window. */
gtk_container_add (GTK_CONTAINER (window), box1);
/* Creates a new button with the label "Button 1". */
button = gtk_button_new_with_label ("Button 1");
/* Now when the button is clicked, we call the "callback" function
* with a pointer to "button 1" as its argument */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
/* Instead of gtk_container_add, we pack this button into the invisible
* box, which has been packed into the window. */
gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
/* Always remember this step, this tells GTK that our preparation for
* this button is complete, and it can now be displayed. */
gtk_widget_show(button);
/* Do these same steps again to create a second button */
button = gtk_button_new_with_label ("Button 2");
/* Call the same callback function with a different argument,
* passing a pointer to "button 2" instead. */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
/* The order in which we show the buttons is not really important, but I
* recommend showing the window last, so it all pops up at once. */
gtk_widget_show(button);
gtk_widget_show(box1);
gtk_widget_show (window);
/* Rest in gtk_main and wait for the fun to begin! */
gtk_main ();
return(0);
}
/* example-end */

   Compile this program using the same linking arguments as our first example. You'll notice this time there is no easy way to exit the program, you have to use your window manager or command line to kill it. A good exercise for the reader would be
to insert a third "Quit" button that will exit the program. You may also wish to play with the options to gtk_box_pack_start() while reading the next section. Try resizing the window, and observe the behavior.

  Just as a side note, there is another useful define for gtk_window_new () - GTK_WINDOW_DIALOG. This interacts with the window manager a little differently and should be used for transient windows.

4. Packing Widgets

  When creating an application, you'll want to put more than one widget inside a window. Our first helloworld example only used one widget so we could simply use a gtk_container_add call to "pack" the widget into the window. But when you want to put
more than one widget into a window, how do you control where that widget is positioned? This is where packing comes in.

4.1 Theory of Packing Boxes

   Most packing is done by creating boxes as in the example above. These are invisible widget containers that we can pack our widgets into which come in two forms, a horizontal box, and a vertical box. When packing widgets into a horizontal box, the
objects are inserted horizontally from left to right or right to left depending on the call used. In a vertical box, widgets are packed from top to bottom or vice versa. You may use any combination of boxes inside or beside other boxes to create the
desired effect.

  To create a new horizontal box, we use a call to gtk_hbox_new(), and for vertical boxes, gtk_vbox_new(). The gtk_box_pack_start() and gtk_box_pack_end() functions are used to place objects inside of these containers. The gtk_box_pack_start()
function will start at the top and work its way down in a vbox, and pack left to right in an hbox. gtk_box_pack_end() will do the opposite, packing from bottom to top in a vbox, and right to left in an hbox. Using these functions allows us to right
justify or left justify our widgets and may be mixed in any way to achieve the desired effect. We will use gtk_box_pack_start() in most of our examples. An object may be another container or a widget. In fact, many widgets are actually containers
themselves, including the button, but we usually only use a label inside a button.

  By using these calls, GTK knows where you want to place your widgets so it can do automatic resizing and other nifty things. There are also a number of options as to how your widgets should be packed. As you can imagine, this method gives us a
quite a bit of flexibility when placing and creating widgets.

4.2 Details of Boxes

  Because of this flexibility, packing boxes in GTK can be confusing at first. There are a lot of options, and it's not immediately obvious how they all fit together. In the end, however, there are basically five different styles.

  Each line contains one horizontal box (hbox) with several buttons. The call to gtk_box_pack is shorthand for the call to pack each of the buttons into the hbox. Each of the buttons is packed into the hbox the same way (i.e., same arguments to the
gtk_box_pack_start() function).

  This is the declaration of the gtk_box_pack_start function.


void gtk_box_pack_start( GtkBox*box,
GtkWidget *child,
gint expand,
gint fill,
gint padding );

  The first argument is the box you are packing the object into, the second is the object. The objects will all be buttons for now, so we'll be packing buttons into boxes.

  The expand argument to gtk_box_pack_start() and gtk_box_pack_end() controls whether the widgets are laid out in the box to fill in all the extra space in the box so the box is expanded to fill the area allotted to it (TRUE); or the box is shrunk
to just fit the widgets (FALSE). Setting expand to FALSE will allow you to do right and left justification of your widgets. Otherwise, they will all expand to fit into the box, and the same effect could be achieved by using only one of
gtk_box_pack_start or gtk_box_pack_end.

   The fill argument to the gtk_box_pack functions control whether the extra space is allocated to the objects themselves (TRUE), or as extra padding in the box around these objects (FALSE). It only has an effect if the expand argument is also TRUE.

  When creating a new box, the function looks like this:


GtkWidget *gtk_hbox_new (gint homogeneous,
gint spacing);

  The homogeneous argument to gtk_hbox_new (and the same for gtk_vbox_new) controls whether each object in the box has the same size (i.e., the same width in an hbox, or the same height in a vbox). If it is set, the gtk_box_pack routines function
essentially as if the expand argument was always turned on.

  What's the difference between spacing (set when the box is created) and padding (set when elements are packed)? Spacing is added between objects, and padding is added on either side of an object. The following figure should make it clearer:

   Here is the code used to create the above images. I've commented it fairly heavily so I hope you won't have any problems following it. Compile it yourself and play with it.

4.3 Packing Demonstration Program


/* example-start packbox packbox.c */
#include
#include
#include "gtk/gtk.h"
gint delete_event( GtkWidget *widget,
GdkEvent*event,
gpointer data )
{
gtk_main_quit();
return(FALSE);
}
/* Make a new hbox filled with button-labels. Arguments for the
* variables we're interested are passed in to this function.
* We do not show the box, but do show everything inside. */
GtkWidget *make_box( gint homogeneous,
gint spacing,gint expand,gint fill,gint padding )
{
GtkWidget *box;
GtkWidget *button;
char padstr[80];
/* Create a new hbox with the appropriate homogeneous
* and spacing settings */
box = gtk_hbox_new (homogeneous, spacing);
/* Create a series of buttons with the appropriate settings */
button = gtk_button_new_with_label ("gtk_box_pack");
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
button = gtk_button_new_with_label ("(box,");
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
button = gtk_button_new_with_label ("button,");
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
/* Create a button with the label depending on the value of
* expand. */
if (expand == TRUE)
button = gtk_button_new_with_label ("TRUE,");
else
button = gtk_button_new_with_label ("FALSE,");
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
/* This is the same as the button creation for "expand"
* above, but uses the shorthand form. */
button = gtk_button_new_with_label (fill ? "TRUE," : "FALSE,");
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
sprintf (padstr, "%d);", padding);
button = gtk_button_new_with_label (padstr);
gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
gtk_widget_show (button);
return box;
}
int main( int argc,
char *argv[])
{
GtkWidget *window;
GtkWidget *button;
GtkWidget *box1;
GtkWidget *box2;
GtkWidget *separator;
GtkWidget *label;
GtkWidget *quitbox;
int which;
/* Our init, don't forget this! :) */
gtk_init (&argc, &argv);
if (argc != 2) {
fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.
");
/* This just does cleanup in GTK and exits with an exit status of 1. */
gtk_exit (1);
}
which = atoi (argv[1]);
/* Create our window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* You should always remember to connect the delete_event signal
* to the main window. This is very important for proper intuitive
* behavior */
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete_event), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* We create a vertical box (vbox) to pack the horizontal boxes into.
* This allows us to stack the horizontal boxes filled with buttons one
* on top of the other in this vbox. */
box1 = gtk_vbox_new (FALSE, 0);
/* which example to show. These correspond to the pictures above. */
switch (which) {
case 1:
/* create a new label. */
label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
/* Align the label to the left side.We'll discuss this function and
* others in the section on Widget Attributes. */
gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
/* Pack the label into the vertical box (vbox box1).Remember that
* widgets added to a vbox will be packed one on top of the other in
* order. */
gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
/* Show the label */
gtk_widget_show (label);
/* Call our make box function - homogeneous = FALSE, spacing = 0,
* expand = FALSE, fill = FALSE, padding = 0 */
box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Call our make box function - homogeneous = FALSE, spacing = 0,
* expand = TRUE, fill = FALSE, padding = 0 */
box2 = make_box (FALSE, 0, TRUE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (FALSE, 0, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Creates a separator, we'll learn more about these later,
* but they are quite simple. */
separator = gtk_hseparator_new ();
/* Pack the separator into the vbox. Remember each of these
* widgets is being packed into a vbox, so they'll be stacked
* vertically. */
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
gtk_widget_show (separator);
/* Create another new label, and show it. */
label = gtk_label_new ("gtk_hbox_new (TRUE, 0);");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
gtk_widget_show (label);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (TRUE, 0, TRUE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (TRUE, 0, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Another new separator. */
separator = gtk_hseparator_new ();
/* The last 3 arguments to gtk_box_pack_start are:
* expand, fill, padding. */
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
gtk_widget_show (separator);
break;
case 2:
/* Create a new label, remember box1 is a vbox as created
* near the beginning of main() */
label = gtk_label_new ("gtk_hbox_new (FALSE, 10);");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
gtk_widget_show (label);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (FALSE, 10, TRUE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (FALSE, 10, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
separator = gtk_hseparator_new ();
/* The last 3 arguments to gtk_box_pack_start are:
* expand, fill, padding. */
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
gtk_widget_show (separator);
label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
gtk_widget_show (label);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (FALSE, 0, TRUE, FALSE, 10);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* Args are: homogeneous, spacing, expand, fill, padding */
box2 = make_box (FALSE, 0, TRUE, TRUE, 10);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
separator = gtk_hseparator_new ();
/* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
gtk_widget_show (separator);
break;
case 3:
/* This demonstrates the ability to use gtk_box_pack_end() to
* right justify widgets. First, we create a new box as before. */
box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
/* Create the label that will be put at the end. */
label = gtk_label_new ("end");
/* Pack it using gtk_box_pack_end(), so it is put on the right
* side of the hbox created in the make_box() call. */
gtk_box_pack_end (GTK_BOX (box2), label, FALSE, FALSE, 0);
/* Show the label. */
gtk_widget_show (label);
/* Pack box2 into box1 (the vbox remember ? :) */
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
gtk_widget_show (box2);
/* A separator for the bottom. */
separator = gtk_hseparator_new ();
/* This explicitly sets the separator to 400 pixels wide by 5 pixels
* high. This is so the hbox we created will also be 400 pixels wide,
* and the "end" label will be separated from the other labels in the
* hbox. Otherwise, all the widgets in the hbox would be packed as
* close together as possible. */
gtk_widget_set_usize (separator, 400, 5);
/* pack the separator into the vbox (box1) created near the start
* of main() */
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
gtk_widget_show (separator);
}
/* Create another new hbox.. remember we can use as many as we need! */
quitbox = gtk_hbox_new (FALSE, 0);
/* Our quit button. */
button = gtk_button_new_with_label ("Quit");
/* Setup the signal to terminate the program when the button is clicked */
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (gtk_main_quit),
GTK_OBJECT (window));
/* Pack the button into the quitbox.
* The last 3 arguments to gtk_box_pack_start are:
* expand, fill, padding. */
gtk_box_pack_start (GTK_BOX (quitbox), button, TRUE, FALSE, 0);
/* pack the quitbox into the vbox (box1) */
gtk_box_pack_start (GTK_BOX (box1), quitbox, FALSE, FALSE, 0);
/* Pack the vbox (box1) which now contains all our widgets, into the
* main window. */
gtk_container_add (GTK_CONTAINER (window), box1);
/* And show everything left */
gtk_widget_show (button);
gtk_widget_show (quitbox);
gtk_widget_show (box1);
/* Showing the window last so everything pops up at once. */
gtk_widget_show (window);
/* And of course, our main function. */
gtk_main ();
/* Control returns here when gtk_main_quit() is called, but not when
* gtk_exit is used. */
return(0);
}
/* example-end */

4.4 Packing Using Tables

  Let's take a look at another way of packing - Tables. These can be extremely useful in certain situations.

  Using tables, we create a grid that we can place widgets in. The widgets may take up as many spaces as we specify.

  The first thing to look at, of course, is the gtk_table_new function:


GtkWidget *gtk_table_new( gint rows,
gint columns,
gint homogeneous );

  The first argument is the number of rows to make in the table, while the second, obviously, is the number of columns.

   The homogeneous argument has to do with how the table's boxes are sized. If homogeneous is TRUE, the table boxes are resized to the size of the largest widget in the table. If homogeneous is FALSE, the size of a table boxes is dictated by the
tallest widget in its same row, and the widest widget in its column.

  The rows and columns are laid out from 0 to n, where n was the number specified in the call to gtk_table_new. So, if you specify rows = 2 and columns = 2, the layout would look something like this:


012
0+----------+----------+
|||
1+----------+----------+
|||
2+----------+----------+

   Note that the coordinate system starts in the upper left hand corner. To place a widget into a box, use the following function:


void gtk_table_attach( GtkTable*table,
GtkWidget *child,
gint left_attach,
gint right_attach,
gint top_attach,
gint bottom_attach,
gint xoptions,
gint yoptions,
gint xpadding,
gint ypadding );

  The first argument ("table") is the table you've created and the second ("child") the widget you wish to place in the table.

  The left and right attach arguments specify where to place the widget, and how many boxes to use. If you want a button in the lower right table entry of our 2x2 table, and want it to fill that entry ONLY, left_attach would be = 1, right_attach =
2, top_attach = 1, bottom_attach = 2.

  Now, if you wanted a widget to take up the whole top row of our 2x2 table, you'd use left_attach = 0, right_attach = 2, top_attach = 0, bottom_attach = 1.

  The xoptions and yoptions are used to specify packing options and may be bitwise OR'ed together to allow multiple options.

  These options are:

  GTK_FILL - If the table box is larger than the widget, and GTK_FILL is specified, the widget will expand to use all the room available.

  GTK_SHRINK - If the table widget was allocated less space then was requested (usually by the user resizing the window), then the widgets would normally just be pushed off the bottom of the window and disappear. If GTK_SHRINK is specified, the
widgets will shrink with the table.

  GTK_EXPAND - This will cause the table to expand to use up any remaining space in the window.

  Padding is just like in boxes, creating a clear area around the widget specified in pixels.

  gtk_table_attach() has a LOT of options. So, there's a shortcut:


void gtk_table_attach_defaults( GtkTable*table,
GtkWidget *widget,
gint left_attach,
gint right_attach,
gint top_attach,
gint bottom_attach );

  The X and Y options default to GTK_FILL | GTK_EXPAND, and X and Y padding are set to 0. The rest of the arguments are identical to the previous function.

  We also have gtk_table_set_row_spacing() and gtk_table_set_col_spacing (). These places spacing between the rows at the specified row or column.


void gtk_table_set_row_spacing( GtkTable *table,
gintrow,
gintspacing );

  and


void gtk_table_set_col_spacing ( GtkTable *table,
gintcolumn,
gintspacing );

  Note that for columns, the space goes to the right of the column, and for rows, the space goes below the row.

  You can also set a consistent spacing of all rows and/or columns with:


void gtk_table_set_row_spacings( GtkTable *table,gintspacing );

  And,


void gtk_table_set_col_spacings( GtkTable *table,gintspacing );

  Note that with these calls, the last row and last column do not get any spacing.

4.5 Table Packing Example

   Here we make a window with three buttons in a 2x2 table. The first two buttons will be placed in the upper row. A third, quit button, is placed in the lower row, spanning both columns. Which means it should look something like this:

  Here's the source code:


/* example-start table table.c */
#include
/* Our callback.
* The data passed to this function is printed to stdout */
void callback( GtkWidget *widget,gpointer data )
{
g_print ("Hello again - %s was pressed
", (char *) data);
}
/* This callback quits the program */
gint delete_event( GtkWidget *widget,GdkEvent*event,gpointer data )
{
gtk_main_quit ();
return(FALSE);
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *button;
GtkWidget *table;
gtk_init (&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* Set the window title */
gtk_window_set_title (GTK_WINDOW (window), "Table");
/* Set a handler for delete_event that immediately
* exits GTK. */
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete_event), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 20);
/* Create a 2x2 table */
table = gtk_table_new (2, 2, TRUE);
/* Put the table in the main window */
gtk_container_add (GTK_CONTAINER (window), table);
/* Create first button */
button = gtk_button_new_with_label ("button 1");
/* When the button is clicked, we call the "callback" function
* with a pointer to "button 1" as its argument */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
/* Insert button 1 into the upper left quadrant of the table */
gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
gtk_widget_show (button);
/* Create second button */
button = gtk_button_new_with_label ("button 2");
/* When the button is clicked, we call the "callback" function
* with a pointer to "button 2" as its argument */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
/* Insert button 2 into the upper right quadrant of the table */
gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
gtk_widget_show (button);
/* Create "Quit" button */
button = gtk_button_new_with_label ("Quit");
/* When the button is clicked, we call the "delete_event" function
* and the program exits */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (delete_event), NULL);
/* Insert the quit button into the both
* lower quadrants of the table */
gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
gtk_widget_show (button);
gtk_widget_show (table);
gtk_widget_show (window);
gtk_main ();
return 0;
}
/* example-end */

5. Widget Overview

  The general steps to creating a widget in GTK are:

  gtk_*_new - one of various functions to create a new widget. These are all detailed in this section.

  Connect all signals and events we wish to use to the appropriate handlers.

  Set the attributes of the widget.

  Pack the widget into a container using the appropriate call such as gtk_container_add() or gtk_box_pack_start().

  gtk_widget_show() the widget.

  gtk_widget_show() lets GTK know that we are done setting the attributes of the widget, and it is ready to be displayed. You may also use gtk_widget_hide to make it disappear again. The order in which you show the widgets is not important, but I
suggest showing the window last so the whole window pops up at once rather than seeing the individual widgets come up on the screen as they're formed. The children of a widget (a window is a widget too) will not be displayed until the window itself is
shown using the gtk_widget_show() function.

5.1 Casting

   You'll notice as you go on that GTK uses a type casting system. This is always done using macros that both test the ability to cast the given item, and perform the cast. Some common ones you will see are:


GTK_WIDGET(widget)
GTK_OBJECT(object)
GTK_SIGNAL_FUNC(function)
GTK_CONTAINER(container)
GTK_WINDOW(window)
GTK_BOX(box)

   These are all used to cast arguments in functions. You'll see them in the examples, and can usually tell when to use them simply by looking at the function's declaration.

  As you can see below in the class hierarchy, all GtkWidgets are derived from the Object base class. This means you can use a widget in any place the function asks for an object - simply use the GTK_OBJECT() macro.

  For example:


gtk_signal_connect( GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC(callback_function), callback_data);

  This casts the button into an object, and provides a cast for the function pointer to the callback.

   Many widgets are also containers. If you look in the class hierarchy below, you'll notice that many widgets derive from the Container class. Any one of these widgets may be used with the GTK_CONTAINER macro to pass them to functions that ask for
containers.

  Unfortunately, these macros are not extensively covered in the tutorial, but I recommend taking a look through the GTK header files. It can be very educational. In fact, it's not difficult to learn how a widget works just by looking at the
function declarations.

5.2 Widget Hierarchy

  For your reference, here is the class hierarchy tree used to implement widgets.


GtkObject
+GtkWidget
| +GtkMisc
| | +GtkLabel
| | | +GtkAccelLabel
| | | `GtkTipsQuery
| | +GtkArrow
| | +GtkImage
| | `GtkPixmap
| +GtkContainer
| | +GtkBin
| | | +GtkAlignment
| | | +GtkFrame
| | | | `GtkAspectFrame
| | | +GtkButton
| | | | +GtkToggleButton
| | | | | `GtkCheckButton
| | | | | `GtkRadioButton
| | | | `GtkOptionMenu
| | | +GtkItem
| | | | +GtkMenuItem
| | | | | +GtkCheckMenuItem
| | | | | | `GtkRadioMenuItem
| | | | | `GtkTearoffMenuItem
| | | | +GtkListItem
| | | | `GtkTreeItem
| | | +GtkWindow
| | | | +GtkColorSelectionDialog
| | | | +GtkDialog
| | | | | `GtkInputDialog
| | | | +GtkDrawWindow
| | | | +GtkFileSelection
| | | | +GtkFontSelectionDialog
| | | | `GtkPlug
| | | +GtkEventBox
| | | +GtkHandleBox
| | | +GtkScrolledWindow
| | | `GtkViewport
| | +GtkBox
| | | +GtkButtonBox
| | | | +GtkHButtonBox
| | | | `GtkVButtonBox
| | | +GtkVBox
| | | | +GtkColorSelection
| | | | `GtkGammaCurve
| | | `GtkHBox
| | | +GtkCombo
| | | `GtkStatusbar
| | +GtkCList
| | | `GtkCTree
| | +GtkFixed
| | +GtkNotebook
| | | `GtkFontSelection
| | +GtkPaned
| | | +GtkHPaned
| | | `GtkVPaned
| | +GtkLayout
| | +GtkList
| | +GtkMenuShell
| | | +GtkMenuBar
| | | `GtkMenu
| | +GtkPacker
| | +GtkSocket
| | +GtkTable
| | +GtkToolbar
| | `GtkTree
| +GtkCalendar
| +GtkDrawingArea
| | `GtkCurve
| +GtkEditable
| | +GtkEntry
| | | `GtkSpinButton
| | `GtkText
| +GtkRuler
| | +GtkHRuler
| | `GtkVRuler
| +GtkRange
| | +GtkScale
| | | +GtkHScale
| | | `GtkVScale
| | `GtkScrollbar
| | +GtkHScrollbar
| | `GtkVScrollbar
| +GtkSeparator
| | +GtkHSeparator
| | `GtkVSeparator
| +GtkPreview
| `GtkProgress
| `GtkProgressBar
+GtkData
| +GtkAdjustment
| `GtkTooltips
`GtkItemFactory

5.3 Widgets Without Windows

   The following widgets do not have an associated window. If you want to capture events, you'll have to use the EventBox. See the section on the EventBox widget.


GtkAlignment
GtkArrow
GtkBin
GtkBox
GtkImage
GtkItem
GtkLabel
GtkPixmap
GtkScrolledWindow
GtkSeparator
GtkTable
GtkAspectFrame
GtkFrame
GtkVBox
GtkHBox
GtkVSeparator
GtkHSeparator

  We'll further our exploration of GTK by examining each widget in turn, creating a few simple functions to display them. Another good source is the testgtk.c program that comes with GTK. It can be found in gtk/testgtk.c.

6. The Button Widget

6.1 Normal Buttons

   We've almost seen all there is to see of the button widget. It's pretty simple. There are however two ways to create a button. You can use the gtk_button_new_with_label() to create a button with a label, or use gtk_button_new() to create a blank
button. It's then up to you to pack a label or pixmap into this new button. To do this, create a new box, and then pack your objects into this box using the usual gtk_box_pack_start, and then use gtk_container_add to pack the box into the button.

   Here's an example of using gtk_button_new to create a button with a picture and a label in it. I've broken up the code to create a box from the rest so you can use it in your programs. There are further examples of using pixmaps later in the
tutorial.


/* example-start buttons buttons.c */
#include
/* Create a new hbox with an image and a label packed into it
* and return the box. */
GtkWidget *xpm_label_box( GtkWidget *parent,
gchar *xpm_filename,
gchar *label_text )
{
GtkWidget *box1;
GtkWidget *label;
GtkWidget *pixmapwid;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
/* Create box for xpm and label */
box1 = gtk_hbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (box1), 2);
/* Get the style of the button to get the
* background color. */
style = gtk_widget_get_style(parent);
/* Now on to the xpm stuff */
pixmap = gdk_pixmap_create_from_xpm (parent->window, &mask,
&style->bg[GTK_STATE_NORMAL],
xpm_filename);
pixmapwid = gtk_pixmap_new (pixmap, mask);
/* Create a label for the button */
label = gtk_label_new (label_text);
/* Pack the pixmap and label into the box */
gtk_box_pack_start (GTK_BOX (box1),
pixmapwid, FALSE, FALSE, 3);
gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
gtk_widget_show(pixmapwid);
gtk_widget_show(label);
return(box1);
}
/* Our usual callback function */
void callback( GtkWidget *widget,
gpointer data )
{
g_print ("Hello again - %s was pressed
", (char *) data);
}
int main( int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *button;
GtkWidget *box1;
gtk_init (&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
/* It's a good idea to do this for all windows. */
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_exit), NULL);
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (gtk_exit), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_widget_realize(window);
/* Create a new button */
button = gtk_button_new ();
/* Connect the "clicked" signal of the button to our callback */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
/* This calls our box creating function */
box1 = xpm_label_box(window, "info.xpm", "cool button");
/* Pack and show all our widgets */
gtk_widget_show(box1);
gtk_container_add (GTK_CONTAINER (button), box1);
gtk_widget_show(button);
gtk_container_add (GTK_CONTAINER (window), button);
gtk_widget_show (window);
/* Rest in gtk_main and wait for the fun to begin! */
gtk_main ();
return(0);
}
/* example-end */

  The xpm_label_box function could be used to pack xpm's and labels into any widget that can be a container.

   Notice in xpm_label_box how there is a call to gtk_widget_get_style. Every widget has a "style", consisting of foreground and background colors for a variety of situations, font selection, and other graphics data relevant to a widget. These style
values are defaulted in each widget, and are required by many GDK function calls, such as gdk_pixmap_create_from_xpm, which here is given the "normal" background color. The style data of widgets may be customized, using GTK's rc files.

   Also notice the call to gtk_widget_realize after setting the window's border width. This function uses GDK to create the X windows related to the widget. The function is automatically called when you invoke gtk_widget_show for a widget, and so has
not been shown in earlier examples. But the call to gdk_pixmap_create_from_xpm requires that its window argument refer to a real X window, so it is necessary to realize the widget before this GDK call.

  The Button widget has the following signals:

  pressed - emitted when pointer button is pressed within Button widget

  released - emitted when pointer button is released within Button widget

  clicked - emitted when pointer button is pressed and then released within Button widget

  enter - emitted when pointer enters Button widget

  leave - emitted when pointer leaves Button widget

6.2 Toggle Buttons

  Toggle buttons are derived from normal buttons and are very similar, except they will always be in one of two states, alternated by a click. They may be depressed, and when you click again, they will pop back up. Click again, and they will pop
back down.

  Toggle buttons are the basis for check buttons and radio buttons, as such, many of the calls used for toggle buttons are inherited by radio and check buttons. I will point these out when we come to them.

  Creating a new toggle button:


GtkWidget *gtk_toggle_button_new( void );
GtkWidget *gtk_toggle_button_new_with_label( gchar *label );

  As you can imagine, these work identically to the normal button widget calls. The first creates a blank toggle button, and the second, a button with a label widget already packed into it.

  To retrieve the state of the toggle widget, including radio and check buttons, we use a construct as shown in our example below. This tests the state of the toggle, by accessing the active field of the toggle widget's structure, after first using
the GTK_TOGGLE_BUTTON macro to cast the widget pointer into a toggle widget pointer. The signal of interest to us emitted by toggle buttons (the toggle button, check button, and radio button widgets) is the "toggled" signal. To check the state of
these buttons, set up a signal handler to catch the toggled signal, and access the structure to determine its state. The callback will look something like:


void toggle_button_callback (GtkWidget *widget, gpointer data)
{
if (GTK_TOGGLE_BUTTON (widget)->active)
{
/* If control reaches here, the toggle button is down */
} else {
/* If control reaches here, the toggle button is up */
}
}

  To force the state of a toggle button, and its children, the radio and check buttons, use this function:


void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
gint state );

  The above call can be used to set the state of the toggle button, and its children the radio and check buttons. Passing in your created button as the first argument, and a TRUE or FALSE for the second state argument to specify whether it should be
down (depressed) or up (released). Default is up, or FALSE.

  Note that when you use the gtk_toggle_button_set_active() function, and the state is actually changed, it causes the "clicked" signal to be emitted from the button.


void gtk_toggle_button_toggled (GtkToggleButton *toggle_button);
This simply toggles the button, and emits the "toggled" signal.

6.3 Check Buttons

   Check buttons inherit many properties and functions from the the toggle buttons above, but look a little different. Rather than being buttons with text inside them, they are small squares with the text to the right of them. These are often used
for toggling options on and off in applications.

  The two creation functions are similar to those of the normal button.


GtkWidget *gtk_check_button_new( void );
GtkWidget *gtk_check_button_new_with_label ( gchar *label );

  The new_with_label function creates a check button with a label beside it.

  Checking the state of the check button is identical to that of the toggle button.

6.4 Radio Buttons

   Radio buttons are similar to check buttons except they are grouped so that only one may be selected/depressed at a time. This is good for places in your application where you need to select from a short list of options.

  Creating a new radio button is done with one of these calls:


GtkWidget *gtk_radio_button_new( GSList *group );
GtkWidget *gtk_radio_button_new_with_label( GSList *group,
gchar*label );

   You'll notice the extra argument to these calls. They require a group to perform their duty properly. The first call to gtk_radio_button_new_with_label or gtk_radio_button_new_with_label should pass NULL as the first argument. Then create a group
using:


GSList *gtk_radio_button_group( GtkRadioButton *radio_button );

   The important thing to remember is that gtk_radio_button_group must be called for each new button added to the group, with the previous button passed in as an argument. The result is then passed into the next call to gtk_radio_button_new or
gtk_radio_button_new_with_label. This allows a chain of buttons to be established. The example below should make this clear.

  You can shorten this slightly by using the following syntax, which removes the need for a variable to hold the list of buttons. This form is used in the example to create the third button:


button2 = gtk_radio_button_new_with_label(
gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
"button2");

  It is also a good idea to explicitly set which button should be the default depressed button with:


void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
gint state );

  This is described in the section on toggle buttons, and works in exactly the same way. Once the radio buttons are grouped together, only one of the group may be active at a time. If the user clicks on one radio button, and then on another, the
first radio button will first emit a "toggled" signal (to report becoming inactive), and then the second will emit its "toggled" signal (to report becoming active).

  The following example creates a radio button group with three buttons.


/* example-start radiobuttons radiobuttons.c */
#include
#include
gint close_application( GtkWidget *widget,
GdkEvent*event,
gpointer data )
{
gtk_main_quit();
return(FALSE);
}
int main( int argc,
char *argv[] )
{
GtkWidget *window = NULL;
GtkWidget *box1;
GtkWidget *box2;
GtkWidget *button;
GtkWidget *separator;
GSList *group;
gtk_init(&argc,&argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC(close_application),
NULL);
gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
gtk_container_set_border_width (GTK_CONTAINER (window), 0);
box1 = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), box1);
gtk_widget_show (box1);
box2 = gtk_vbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
button = gtk_radio_button_new_with_label (NULL, "button1");
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
gtk_widget_show (button);
group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
button = gtk_radio_button_new_with_label(group, "button2");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
gtk_widget_show (button);
button = gtk_radio_button_new_with_label(
gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
"button3");
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
gtk_widget_show (button);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
gtk_widget_show (separator);
box2 = gtk_vbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
gtk_widget_show (box2);
button = gtk_button_new_with_label ("close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC(close_application),
GTK_OBJECT (window));
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
gtk_widget_grab_default (button);
gtk_widget_show (button);
gtk_widget_show (window);
gtk_main();
return(0);
}
/* example-end */

7. Adjustments

   GTK has various widgets that can be visually adjusted by the user using the mouse or the keyboard, such as the range widgets, described in the Range Widgets section. There are also a few widgets that display some adjustable portion of a larger
area of data, such as the text widget and the viewport widget.

  Obviously, an application needs to be able to react to changes the user makes in range widgets. One way to do this would be to have each widget emit its own type of signal when its adjustment changes, and either pass the new value to the signal
handler, or require it to look inside the widget's data structure in order to ascertain the value. But you may also want to connect the adjustments of several widgets together, so that adjusting one adjusts the others. The most obvious example of this
is connecting a scrollbar to a panning viewport or a scrolling text area. If each widget has its own way of setting or getting the adjustment value, then the programmer may have to write their own signal handlers to translate between the output of one
widget's signal and the "input" of another's adjustment setting function.

  GTK solves this problem using the Adjustment object, which is not a widget but a way for widgets to store and pass adjustment information in an abstract and flexible form. The most obvious use of Adjustment is to store the configuration parameters
and values of range widgets, such as scrollbars and scale controls. However, since Adjustments are derived from Object, they have some special powers beyond those of normal data structures. Most importantly, they can emit signals, just like widgets,
and these signals can be used not only to allow your program to react to user input on adjustable widgets, but also to propagate adjustment values transparently between adjustable widgets.

   You will see how adjustments fit in when you see the other widgets that incorporate them: Progress Bars, Viewports, Scrolled Windows, and others.

7.1 Creating an Adjustment

  Many of the widgets which use adjustment objects do so automatically, but some cases will be shown in later examples where you may need to create one yourself. You create an adjustment using:


GtkObject *gtk_adjustment_new( gfloat value,
gfloat lower,gfloat upper,gfloat step_increment,
gfloat page_increment,gfloat page_size );

   The value argument is the initial value you want to give to the adjustment, usually corresponding to the topmost or leftmost position of an adjustable widget. The lower argument specifies the lowest value which the adjustment can hold. The
step_increment argument specifies the "smaller" of the two increments by which the user can change the value, while the page_increment is the "larger" one. The page_size argument usually corresponds somehow to the visible area of a panning widget. The
upper argument is used to represent the bottom most or right most coordinate in a panning widget's child. Therefore it is not always the largest number that value can take, since the page_size of such widgets is usually non-zero.

7.2 Using Adjustments the Easy Way

   The adjustable widgets can be roughly divided into those which use and require specific units for these values and those which treat them as arbitrary numbers. The group which treats the values as arbitrary numbers includes the range widgets
(scrollbars and scales, the progress bar widget, and the spin button widget). These widgets are all the widgets which are typically "adjusted" directly by the user with the mouse or keyboard. They will treat the lower and upper values of an adjustment
as a range within which the user can manipulate the adjustment's value. By default, they will only modify the value of an adjustment.

  The other group includes the text widget, the viewport widget, the compound list widget, and the scrolled window widget. All of these widgets use pixel values for their adjustments. These are also all widgets which are typically "adjusted"
indirectly using scrollbars. While all widgets which use adjustments can either create their own adjustments or use ones you supply, you'll generally want to let this particular category of widgets create its own adjustments. Usually, they will
eventually override all the values except the value itself in whatever adjustments you give them, but the results are, in general, undefined (meaning, you'll have to read the source code to find out, and it may be different from widget to widget).

  Now, you're probably thinking, since text widgets and viewports insist on setting everything except the value of their adjustments, while scrollbars will only touch the adjustment's value, if you share an adjustment object between a scrollbar and
a text widget, manipulating the scrollbar will automagically adjust the text widget? Of course it will! Just like this:


/* creates its own adjustments */
text = gtk_text_new (NULL, NULL);
/* uses the newly-created adjustment for the scrollbar as well */
vscrollbar = gtk_vscrollbar_new (GTK_TEXT(text)->vadj);

7.3 Adjustment Internals

  Ok, you say, that's nice, but what if I want to create my own handlers to respond when the user adjusts a range widget or a spin button, and how do I get at the value of the adjustment in these handlers? To answer these questions and more, let's
start by taking a look at struct _GtkAdjustment itself:


struct _GtkAdjustment
{
GtkData data;
gfloat lower;
gfloat upper;
gfloat value;
gfloat step_increment;
gfloat page_increment;
gfloat page_size;
};

  The first thing you should know is that there aren't any handy- dandy macros or accessor functions for getting the value out of an Adjustment, so you'll have to (horror of horrors) do it like a real C programmer. Don't worry - the GTK_ADJUSTMENT
(Object) macro does run-time type checking (as do all the GTK type-casting macros, actually).

  Since, when you set the value of an adjustment, you generally want the change to be reflected by every widget that uses this adjustment, GTK provides this convenience function to do this:


void gtk_adjustment_set_value( GtkAdjustment *adjustment,
gfloat value );

  As mentioned earlier, Adjustment is a subclass of Object just like all the various widgets, and thus it is able to emit signals. This is, of course, why updates happen automagically when you share an adjustment object between a scrollbar and
another adjustable widget; all adjustable widgets connect signal handlers to their adjustment's value_changed signal, as can your program. Here's the definition of this signal in struct _GtkAdjustmentClass:


void (* value_changed) (GtkAdjustment *adjustment);

   The various widgets that use the Adjustment object will emit this signal on an adjustment whenever they change its value. This happens both when user input causes the slider to move on a range widget, as well as when the program explicitly changes
the value with gtk_adjustment_set_value(). So, for example, if you have a scale widget, and you want to change the rotation of a picture whenever its value changes, you would create a callback like this:


void cb_rotate_picture (GtkAdjustment *adj, GtkWidget *picture)
{
set_picture_rotation (picture, adj->value);
...

  and connect it to the scale widget's adjustment like this:


gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
GTK_SIGNAL_FUNC (cb_rotate_picture), picture);

   What about when a widget reconfigures the upper or lower fields of its adjustment, such as when a user adds more text to a text widget? In this case, it emits the changed signal, which looks like this:


void (* changed) (GtkAdjustment *adjustment);

  Range widgets typically connect a handler to this signal, which changes their appearance to reflect the change - for example, the size of the slider in a scrollbar will grow or shrink in inverse proportion to the difference between the lower and
upper values of its adjustment.

  You probably won't ever need to attach a handler to this signal, unless you're writing a new type of range widget. However, if you change any of the values in a Adjustment directly, you should emit this signal on it to reconfigure whatever widgets
are using it, like this:


gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");
Now go forth and adjust!

8. Range Widgets

   The category of range widgets includes the ubiquitous scrollbar widget and the less common "scale" widget. Though these two types of widgets are generally used for different purposes, they are quite similar in function and implementation. All
range widgets share a set of common graphic elements, each of which has its own X window and receives events. They all contain a "trough" and a "slider" (what is sometimes called a "thumbwheel" in other GUI environments). Dragging the slider with the
pointer moves it back and forth within the trough, while clicking in the trough advances the slider towards the location of the click, either completely, or by a designated amount, depending on which mouse button is used.

  As mentioned in Adjustments above, all range widgets are associated with an adjustment object, from which they calculate the length of the slider and its position within the trough. When the user manipulates the slider, the range widget will
change the value of the adjustment.

8.1 Scrollbar Widgets

  These are your standard, run-of-the- mill scrollbars. These should be used only for scrolling some other widget, such as a list, a text box, or a viewport (and it's generally easier to use the scrolled window widget in most cases). For other
purposes, you should use scale widgets, as they are friendlier and more featureful.

   There are separate types for horizontal and vertical scrollbars. There really isn't much to say about these. You create them with the following functions, defined in and :


GtkWidget *gtk_hscrollbar_new( GtkAdjustment *adjustment );
GtkWidget *gtk_vscrollbar_new( GtkAdjustment *adjustment );

  and that's about it (if you don't believe me, look in the header files!). The adjustment argument can either be a pointer to an existing Adjustment, or NULL, in which case one will be created for you. Specifying NULL might actually be useful in
this case, if you wish to pass the newly-created adjustment to the constructor function of some other widget which will configure it for you, such as a text widget.

8.2 Scale Widgets

   Scale widgets are used to allow the user to visually select and manipulate a value within a specific range. You might want to use a scale widget, for example, to adjust the magnification level on a zoomed preview of a picture, or to control the
brightness of a color, or to specify the number of minutes of inactivity before a screensaver takes over the screen.

Creating a Scale Widget

  As with scrollbars, there are separate widget types for horizontal and vertical scale widgets. (Most programmers seem to favour horizontal scale widgets.) Since they work essentially the same way, there's no need to treat them separately here. The
following functions, defined in and , create vertical and horizontal scale widgets, respectively:


GtkWidget *gtk_vscale_new( GtkAdjustment *adjustment );
GtkWidget *gtk_hscale_new( GtkAdjustment *adjustment );

   The adjustment argument can either be an adjustment which has already been created with gtk_adjustment_new(), or NULL, in which case, an anonymous Adjustment is created with all of its values set to 0.0 (which isn't very useful in this case). In
order to avoid confusing yourself, you probably want to create your adjustment with a page_size of 0.0 so that its upper value actually corresponds to the highest value the user can select. (If you're already thoroughly confused, read the section on
Adjustments again for an explanation of what exactly adjustments do and how to create and manipulate them.)


Functions and Signals (well, functions, at least)

   Scale widgets can display their current value as a number beside the trough. The default behaviour is to show the value, but you can change this with this function:


void gtk_scale_set_draw_value( GtkScale *scale,
gintdraw_value );

  As you might have guessed, draw_value is either TRUE or FALSE, with predictable consequences for either one.

   The value displayed by a scale widget is rounded to one decimal point by default, as is the value field in its GtkAdjustment. You can change this with:


void gtk_scale_set_digits( GtkScale *scale,
gint digits );

   where digits is the number of decimal places you want. You can set digits to anything you like, but no more than 13 decimal places will actually be drawn on screen.

  Finally, the value can be drawn in different positions relative to the trough:


void gtk_scale_set_value_pos( GtkScale*scale,
GtkPositionTypepos );

  The argument pos is of type GtkPositionType, which is defined in < gtk/gtkenums.h>, and can take one of the following values:


GTK_POS_LEFT
GTK_POS_RIGHT
GTK_POS_TOP
GTK_POS_BOTTOM

  If you position the value on the "side" of the trough (e.g., on the top or bottom of a horizontal scale widget), then it will follow the slider up and down the trough.

  All the preceding functions are defined in . The header files for all GTK widgets are automatically included when you include . But you should look over the header files of all widgets that interest you,

8.3 Common Range Functions

  The Range widget class is fairly complicated internally, but, like all the "base class" widgets, most of its complexity is only interesting if you want to hack on it. Also, almost all of the functions and signals it defines are only really used in
writing derived widgets. There are, however, a few useful functions that are defined in and will work on all range widgets.

Setting the Update Policy

   The "update policy" of a range widget defines at what points during user interaction it will change the value field of its Adjustment and emit the "value_changed" signal on this Adjustment. The update policies, defined in as type
enum GtkUpdateType, are:

  GTK_UPDATE_POLICY_CONTINUOUS - This is the default. The "value_changed" signal is emitted continuously, i.e., whenever the slider is moved by even the tiniest amount.

  GTK_UPDATE_POLICY_DISCONTINUOUS - The "value_changed" signal is only emitted once the slider has stopped moving and the user has released the mouse button.

  GTK_UPDATE_POLICY_DELAYED - The "value_changed" signal is emitted when the user releases the mouse button, or if the slider stops moving for a short period of time.

   The update policy of a range widget can be set by casting it using the GTK_RANGE (Widget) macro and passing it to this function:


void gtk_range_set_update_policy( GtkRange*range,GtkUpdateTypepolicy) ;

Getting and Setting Adjustments

  Getting and setting the adjustment for a range widget "on the fly" is done, predictably, with:


GtkAdjustment* gtk_range_get_adjustment( GtkRange *range );
void gtk_range_set_adjustment( GtkRange*range,GtkAdjustment *adjustment );

  gtk_range_get_adjustment() returns a pointer to the adjustment to which range is connected.

  gtk_range_set_adjustment() does absolutely nothing if you pass it the adjustment that range is already using, regardless of whether you changed any of its fields or not. If you pass it a new Adjustment, it will unreference the old one if it exists
(possibly destroying it), connect the appropriate signals to the new one, and call the private function gtk_range_adjustment_changed(), which will (or at least, is supposed to...) recalculate the size and/or position of the slider and redraw if
necessary. As mentioned in the section on adjustments, if you wish to reuse the same Adjustment, when you modify its values directly, you should emit the "changed" signal on it, like this:


gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");

8.4 Key and Mouse bindings

   All of the GTK range widgets react to mouse clicks in more or less the same way. Clicking button-1 in the trough will cause its adjustment's page_increment to be added or subtracted from its value, and the slider to be moved accordingly. Clicking
mouse button-2 in the trough will jump the slider to the point at which the button was clicked. Clicking any button on a scrollbar's arrows will cause its adjustment's value to change step_increment at a time.

  It may take a little while to get used to, but by default, scrollbars as well as scale widgets can take the keyboard focus in GTK. If you think your users will find this too confusing, you can always disable this by unsetting the GTK_CAN_FOCUS
flag on the scrollbar, like this:


GTK_WIDGET_UNSET_FLAGS (scrollbar, GTK_CAN_FOCUS);

  The key bindings (which are, of course, only active when the widget has focus) are slightly different between horizontal and vertical range widgets, for obvious reasons. They are also not quite the same for scale widgets as they are for
scrollbars, for somewhat less obvious reasons (possibly to avoid confusion between the keys for horizontal and vertical scrollbars in scrolled windows, where both operate on the same area).

Vertical Range Widgets

   All vertical range widgets can be operated with the up and down arrow keys, as well as with the Page Up and Page Down keys. The arrows move the slider up and down by step_increment, while Page Up and Page Down move it by page_increment.

   The user can also move the slider all the way to one end or the other of the trough using the keyboard. With the VScale widget, this is done with the Home and End keys, whereas with the VScrollbar widget, this is done by typing Control-Page Up and
Control-Page Down.

Horizontal Range Widgets

   The left and right arrow keys work as you might expect in these widgets, moving the slider back and forth by step_increment. The Home and End keys move the slider to the ends of the trough. For the HScale widget, moving the slider by
page_increment is accomplished with Control-Left and Control-Right, while for HScrollbar, it's done with Control-Home and Control-End.

8.5 Example

   This example is a somewhat modified version of the "range controls" test from testgtk.c. It basically puts up a window with three range widgets all connected to the same adjustment, and a couple of controls for adjusting some of the parameters
mentioned above and in the section on adjustments, so you can see how they affect the way these widgets work for the user.


/* example-start rangewidgets rangewidgets.c */
#include
GtkWidget *hscale, *vscale;
void cb_pos_menu_select( GtkWidget *item,GtkPositionTypepos )
{
/* Set the value position on both scale widgets */
gtk_scale_set_value_pos (GTK_SCALE (hscale), pos);
gtk_scale_set_value_pos (GTK_SCALE (vscale), pos);
}
void cb_update_menu_select( GtkWidget *item,GtkUpdateTypepolicy )
{
/* Set the update policy for both scale widgets */
gtk_range_set_update_policy (GTK_RANGE (hscale), policy);
gtk_range_set_update_policy (GTK_RANGE (vscale), policy);
}
void cb_digits_scale( GtkAdjustment *adj )
{
/* Set the number of decimal places to which adj->value is rounded */
gtk_scale_set_digits (GTK_SCALE (hscale), (gint) adj->value);
gtk_scale_set_digits (GTK_SCALE (vscale), (gint) adj->value);
}
void cb_page_size( GtkAdjustment *get,GtkAdjustment *set )
{
/* Set the page size and page increment size of the sample
* adjustment to the value specified by the "Page Size" scale */
set->page_size = get->value;
set->page_increment = get->value;
/* Now emit the "changed" signal to reconfigure all the widgets that
* are attached to this adjustment */
gtk_signal_emit_by_name (GTK_OBJECT (set), "changed");
}
void cb_draw_value( GtkToggleButton *button )
{
/* Turn the value display on the scale widgets off or on depending
*on the state of the checkbutton */
gtk_scale_set_draw_value (GTK_SCALE (hscale), button->active);
gtk_scale_set_draw_value (GTK_SCALE (vscale), button->active);
}
/* Convenience functions */
GtkWidget *make_menu_item(gchar *name,GtkSignalFunccallback,gpointer data )
{
GtkWidget *item;
item = gtk_menu_item_new_with_label (name);
gtk_signal_connect (GTK_OBJECT (item), "activate",
callback, data);
gtk_widget_show (item);
return(item);
}
void scale_set_default_values( GtkScale *scale )
{
gtk_range_set_update_policy (GTK_RANGE (scale),GTK_UPDATE_CONTINUOUS);
gtk_scale_set_digits (scale, 1);
gtk_scale_set_value_pos (scale, GTK_POS_TOP);
gtk_scale_set_draw_value (scale, TRUE);
}
/* makes the sample window */
void create_range_controls( void )
{
GtkWidget *window;
GtkWidget *box1, *box2, *box3;
GtkWidget *button;
GtkWidget *scrollbar;
GtkWidget *separator;
GtkWidget *opt, *menu, *item;
GtkWidget *label;
GtkWidget *scale;
GtkObject *adj1, *adj2;
/* Standard window-creating stuff */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
gtk_window_set_title (GTK_WINDOW (window), "range controls");
box1 = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), box1);
gtk_widget_show (box1);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
/* value, lower, upper, step_increment, page_increment, page_size */
/* Note that the page_size value only makes a difference for
* scrollbar widgets, and the highest value you'll get is actually
* (upper - page_size). */
adj1 = gtk_adjustment_new (0.0, 0.0, 101.0, 0.1, 1.0, 1.0);
vscale = gtk_vscale_new (GTK_ADJUSTMENT (adj1));
scale_set_default_values (GTK_SCALE (vscale));
gtk_box_pack_start (GTK_BOX (box2), vscale, TRUE, TRUE, 0);
gtk_widget_show (vscale);
box3 = gtk_vbox_new (FALSE, 10);
gtk_box_pack_start (GTK_BOX (box2), box3, TRUE, TRUE, 0);
gtk_widget_show (box3);
/* Reuse the same adjustment */
hscale = gtk_hscale_new (GTK_ADJUSTMENT (adj1));
gtk_widget_set_usize (GTK_WIDGET (hscale), 200, 30);
scale_set_default_values (GTK_SCALE (hscale));
gtk_box_pack_start (GTK_BOX (box3), hscale, TRUE, TRUE, 0);
gtk_widget_show (hscale);
/* Reuse the same adjustment again */
scrollbar = gtk_hscrollbar_new (GTK_ADJUSTMENT (adj1));
/* Notice how this causes the scales to always be updated
* continuously when the scrollbar is moved */
gtk_range_set_update_policy (GTK_RANGE (scrollbar),GTK_UPDATE_CONTINUOUS);
gtk_box_pack_start (GTK_BOX (box3), scrollbar, TRUE, TRUE, 0);
gtk_widget_show (scrollbar);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
/* A checkbutton to control whether the value is displayed or not */
button = gtk_check_button_new_with_label("Display value on scale widgets");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
gtk_signal_connect (GTK_OBJECT (button), "toggled",
GTK_SIGNAL_FUNC(cb_draw_value), NULL);
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
gtk_widget_show (button);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
/* An option menu to change the position of the value */
label = gtk_label_new ("Scale Value Position:");
gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
gtk_widget_show (label);
opt = gtk_option_menu_new();
menu = gtk_menu_new();
item = make_menu_item ("Top",
GTK_SIGNAL_FUNC(cb_pos_menu_select),
GINT_TO_POINTER (GTK_POS_TOP));
gtk_menu_append (GTK_MENU (menu), item);
item = make_menu_item ("Bottom", GTK_SIGNAL_FUNC (cb_pos_menu_select),
GINT_TO_POINTER (GTK_POS_BOTTOM));
gtk_menu_append (GTK_MENU (menu), item);
item = make_menu_item ("Left", GTK_SIGNAL_FUNC (cb_pos_menu_select),
GINT_TO_POINTER (GTK_POS_LEFT));
gtk_menu_append (GTK_MENU (menu), item);
item = make_menu_item ("Right", GTK_SIGNAL_FUNC (cb_pos_menu_select),
GINT_TO_POINTER (GTK_POS_RIGHT));
gtk_menu_append (GTK_MENU (menu), item);
gtk_option_menu_set_menu (GTK_OPTION_MENU (opt), menu);
gtk_box_pack_start (GTK_BOX (box2), opt, TRUE, TRUE, 0);
gtk_widget_show (opt);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
/* Yet another option menu, this time for the update policy of the
* scale widgets */
label = gtk_label_new ("Scale Update Policy:");
gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
gtk_widget_show (label);
opt = gtk_option_menu_new();
menu = gtk_menu_new();
item = make_menu_item ("Continuous",
GTK_SIGNAL_FUNC (cb_update_menu_select),
GINT_TO_POINTER (GTK_UPDATE_CONTINUOUS));
gtk_menu_append (GTK_MENU (menu), item);
item = make_menu_item ("Discontinuous",
GTK_SIGNAL_FUNC (cb_update_menu_select),
GINT_TO_POINTER (GTK_UPDATE_DISCONTINUOUS));
gtk_menu_append (GTK_MENU (menu), item);
item = make_menu_item ("Delayed",
GTK_SIGNAL_FUNC (cb_update_menu_select),
GINT_TO_POINTER (GTK_UPDATE_DELAYED));
gtk_menu_append (GTK_MENU (menu), item);
gtk_option_menu_set_menu (GTK_OPTION_MENU (opt), menu);
gtk_box_pack_start (GTK_BOX (box2), opt, TRUE, TRUE, 0);
gtk_widget_show (opt);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
/* An HScale widget for adjusting the number of digits on the
* sample scales. */
label = gtk_label_new ("Scale Digits:");
gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
gtk_widget_show (label);
adj2 = gtk_adjustment_new (1.0, 0.0, 5.0, 1.0, 1.0, 0.0);
gtk_signal_connect (GTK_OBJECT (adj2), "value_changed",
GTK_SIGNAL_FUNC (cb_digits_scale), NULL);
scale = gtk_hscale_new (GTK_ADJUSTMENT (adj2));
gtk_scale_set_digits (GTK_SCALE (scale), 0);
gtk_box_pack_start (GTK_BOX (box2), scale, TRUE, TRUE, 0);
gtk_widget_show (scale);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
box2 = gtk_hbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
/* And, one last HScale widget for adjusting the page size of the
* scrollbar. */
label = gtk_label_new ("Scrollbar Page Size:");
gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
gtk_widget_show (label);
adj2 = gtk_adjustment_new (1.0, 1.0, 101.0, 1.0, 1.0, 0.0);
gtk_signal_connect (GTK_OBJECT (adj2), "value_changed",
GTK_SIGNAL_FUNC (cb_page_size), adj1);
scale = gtk_hscale_new (GTK_ADJUSTMENT (adj2));
gtk_scale_set_digits (GTK_SCALE (scale), 0);
gtk_box_pack_start (GTK_BOX (box2), scale, TRUE, TRUE, 0);
gtk_widget_show (scale);
gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
gtk_widget_show (box2);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
gtk_widget_show (separator);
box2 = gtk_vbox_new (FALSE, 10);
gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
gtk_widget_show (box2);
button = gtk_button_new_with_label ("Quit");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
gtk_widget_grab_default (button);
gtk_widget_show (button);
gtk_widget_show (window);
}
int main( int argc,
char *argv[] )
{
gtk_init(&argc, &argv);
create_range_controls();
gtk_main();
return(0);
}
/* example-end */

   You will notice that the program does not call gtk_signal_connect for the "delete_event", but only for the "destroy" signal. This will still perform the desired function, because an unhandled "delete_event" will result in a "destroy" signal being
given to the window.

9. Miscellaneous Widgets

9.1 Labels

  Labels are used a lot in GTK, and are relatively simple. Labels emit no signals as they do not have an associated X window. If you need to catch signals, or do clipping, place it inside a EventBox widget or a Button widget.

  To create a new label, use:


GtkWidget *gtk_label_new( char *str );

  The sole argument is the string you wish the label to display.

  To change the label's text after creation, use the function:


void gtk_label_set_text( GtkLabel *label,char *str );

  The first argument is the label you created previously (cast using the GTK_LABEL() macro), and the second is the new string.

   The space needed for the new string will be automatically adjusted if needed. You can produce multi-line labels by putting line breaks in the label string.

  To retrieve the current string, use:


void gtk_label_get( GtkLabel*label,char **str );

  The first argument is the label you've created, and the second, the return for the string. Do not free the return string, as it is used internally by GTK.

  The label text can be justified using:


void gtk_label_set_justify( GtkLabel *label,
GtkJustificationjtype );

  Values for jtype are:

  GTK_JUSTIFY_LEFT

  GTK_JUSTIFY_RIGHT

  GTK_JUSTIFY_CENTER (the default)

  GTK_JUSTIFY_FILL

  The label widget is also capable of line wrapping the text automatically. This can be activated using:


void gtk_label_set_line_wrap (GtkLabel *label,gbooleanwrap);

  The wrap argument takes a TRUE or FALSE value.

  If you want your label underlined, then you can set a pattern on the label:


void gtk_label_set_pattern (GtkLabel*label,const gchar *pattern);

   The pattern argument indicates how the underlining should look. It consists of a string of underscore and space characters. An underscore indicates that the corresponding character in the label should be underlined. For example, the string

  "__ __"

  would underline the first two characters and eight and ninth characters.

   Below is a short example to illustrate these functions. This example makes use of the Frame widget to better demonstrate the label styles. You can ignore this for now as the Frame widget is explained later on.


/* example-start label label.c */
#include
int main( int argc,
char *argv[] )
{
static GtkWidget *window = NULL;
GtkWidget *hbox;
GtkWidget *vbox;
GtkWidget *frame;
GtkWidget *label;
/* Initialise GTK */
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
gtk_window_set_title (GTK_WINDOW (window), "Label");
vbox = gtk_vbox_new (FALSE, 5);
hbox = gtk_hbox_new (FALSE, 5);
gtk_container_add (GTK_CONTAINER (window), hbox);
gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (window), 5);
frame = gtk_frame_new ("Normal Label");
label = gtk_label_new ("This is a Normal label");
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
frame = gtk_frame_new ("Multi-line Label");
label = gtk_label_new ("This is a Multi-line label.
Second line
"
"Third line");
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
frame = gtk_frame_new ("Left Justified Label");
label = gtk_label_new ("This is a Left-Justified
"
"Multi-line label.
Thirdline");
gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
frame = gtk_frame_new ("Right Justified Label");
label = gtk_label_new ("This is a Right-Justified
Multi-line label.
"
"Fourth line, (j/k)");
gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
vbox = gtk_vbox_new (FALSE, 5);
gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0);
frame = gtk_frame_new ("Line wrapped label");
label = gtk_label_new ("This is an example of a line-wrapped label.It "
"should not be taking up the entire " /* big space to test spacing */
"width allocated to it, but automatically "
"wraps the words to fit."
"The time has come, for all good men, to come to "
"the aid of their party."
"The sixth sheik's six sheep's sick.
"
" It supports multiple paragraphs correctly, "
"andcorrectly adds "
"manyextraspaces. ");
gtk_label_set_line_wrap (GTK_LABEL (label), TRUE);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
frame = gtk_frame_new ("Filled, wrapped label");
label = gtk_label_new ("This is an example of a line-wrapped, filled label."
"It should be taking "
"up the entirewidth allocated to it."
"Here is a sentence to prove "
"my point.Here is another sentence. "
"Here comes the sun, do de do de do.
"
"This is a new paragraph.
"
"This is another newer, longer, better "
"paragraph.It is coming to an end, "
"unfortunately.");
gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_FILL);
gtk_label_set_line_wrap (GTK_LABEL (label), TRUE);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
frame = gtk_frame_new ("Underlined label");
label = gtk_label_new ("This label is underlined!
"
"This one is underlined in quite a funky fashion");
gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
gtk_label_set_pattern (GTK_LABEL (label),
"_________________________ _ _________ _ ______ __ _______ ___");
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
gtk_widget_show_all (window);
gtk_main ();
return(0);
}
/* example-end */

9.2 Arrows

  The Arrow widget draws an arrowhead, facing in a number of possible directions and having a number of possible styles. It can be very useful when placed on a button in many applications. Like the Label widget, it emits no signals.

  There are only two functions for manipulating an Arrow widget:


GtkWidget *gtk_arrow_new( GtkArrowType arrow_type,
GtkShadowTypeshadow_type );
void gtk_arrow_set( GtkArrow*arrow,
GtkArrowType arrow_type,GtkShadowTypeshadow_type );

   The first creates a new arrow widget with the indicated type and appearance. The second allows these values to be altered retrospectively. The arrow_type argument may take one of the following values:

  GTK_ARROW_UP

  GTK_ARROW_DOWN

  GTK_ARROW_LEFT

  GTK_ARROW_RIGHT

   These values obviously indicate the direction in which the arrow will point. The shadow_type argument may take one of these values:

  GTK_SHADOW_IN

  GTK_SHADOW_OUT (the default)

  GTK_SHADOW_ETCHED_IN

  GTK_SHADOW_ETCHED_OUT

  Here's a brief example to illustrate their use.


/* example-start arrow arrow.c */
#include
/* Create an Arrow widget with the specified parameters
* and pack it into a button */
GtkWidget *create_arrow_button( GtkArrowTypearrow_type,
GtkShadowType shadow_type )
{
GtkWidget *button;
GtkWidget *arrow;
button = gtk_button_new();
arrow = gtk_arrow_new (arrow_type, shadow_type);
gtk_container_add (GTK_CONTAINER (button), arrow);
gtk_widget_show(button);
gtk_widget_show(arrow);
return(button);
}
int main( int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *button;
GtkWidget *box;
/* Initialize the toolkit */
gtk_init (&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Arrow Buttons");
/* It's a good idea to do this for all windows. */
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create a box to hold the arrows/buttons */
box = gtk_hbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (box), 2);
gtk_container_add (GTK_CONTAINER (window), box);
/* Pack and show all our widgets */
gtk_widget_show(box);
button = create_arrow_button(GTK_ARROW_UP, GTK_SHADOW_IN);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
button = create_arrow_button(GTK_ARROW_DOWN, GTK_SHADOW_OUT);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
button = create_arrow_button(GTK_ARROW_LEFT, GTK_SHADOW_ETCHED_IN);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
button = create_arrow_button(GTK_ARROW_RIGHT, GTK_SHADOW_ETCHED_OUT);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
gtk_widget_show (window);
/* Rest in gtk_main and wait for the fun to begin! */
gtk_main ();
return(0);
}
/* example-end */

9.3 The Tooltips Object

   These are the little text strings that pop up when you leave your pointer over a button or other widget for a few seconds. They are easy to use, so I will just explain them without giving an example. If you want to see some code, take a look at
the testgtk.c program distributed with GTK.

  Widgets that do not receive events (widgets that do not have their own window) will not work with tooltips.

   The first call you will use creates a new tooltip. You only need to do this once for a set of tooltips as the GtkTooltips object this function returns can be used to create multiple tooltips.


GtkTooltips *gtk_tooltips_new( void );

  Once you have created a new tooltip, and the widget you wish to use it on, simply use this call to set it:


void gtk_tooltips_set_tip( GtkTooltips *tooltips,
GtkWidget *widget,const gchar *tip_text,const gchar *tip_private );

  The first argument is the tooltip you've already created, followed by the widget you wish to have this tooltip pop up for, and the text you wish it to say. The last argument is a text string that can be used as an identifier when using
GtkTipsQuery to implement context sensitive help. For now, you can set it to NULL.

  Here's a short example:


GtkTooltips *tooltips;
GtkWidget *button;
..
..
..
tooltips = gtk_tooltips_new ();
button = gtk_button_new_with_label ("button 1");
..
..
..
gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);

  There are other calls that can be used with tooltips. I will just list them with a brief description of what they do.


void gtk_tooltips_enable( GtkTooltips *tooltips );

  Enable a disabled set of tooltips.


void gtk_tooltips_disable( GtkTooltips *tooltips );

  Disable an enabled set of tooltips.


void gtk_tooltips_set_delay( GtkTooltips *tooltips,gint delay );

   Sets how many milliseconds you have to hold your pointer over the widget before the tooltip will pop up. The default is 500 milliseconds (half a second).


void gtk_tooltips_set_colors( GtkTooltips *tooltips,
GdkColor*background,GdkColor*foreground );

  Set the foreground and background color of the tooltips.

  And that's all the functions associated with tooltips. More than you'll ever want to know :-)

9.4 Progress Bars

   Progress bars are used to show the status of an operation. They are pretty easy to use, as you will see with the code below. But first lets start out with the calls to create a new progress bar.

  There are two ways to create a progress bar, one simple that takes no arguments, and one that takes an Adjustment object as an argument. If the former is used, the progress bar creates its own adjustment object.


GtkWidget *gtk_progress_bar_new( void );
GtkWidget *gtk_progress_bar_new_with_adjustment(GtkAdjustment *adjustment);

   The second method has the advantage that we can use the adjustment object to specify our own range parameters for the progress bar.

  The adjustment of a progress object can be changed dynamically using:


void gtk_progress_set_adjustment( GtkProgress *progress,
GtkAdjustment *adjustment );

  Now that the progress bar has been created we can use it.


void gtk_progress_bar_update( GtkProgressBar *pbar,gfloatpercentage );

  The first argument is the progress bar you wish to operate on, and the second argument is the amount "completed", meaning the amount the progress bar has been filled from 0-100%. This is passed to the function as a real number ranging from 0 to 1.

   GTK v1.2 has added new functionality to the progress bar that enables it to display its value in different ways, and to inform the user of its current value and its range.

  A progress bar may be set to one of a number of orientations using the function


void gtk_progress_bar_set_orientation( GtkProgressBar *pbar,
GtkProgressBarOrientation orientation );

  The orientation argument may take one of the following values to indicate the direction in which the progress bar moves:

  GTK_PROGRESS_LEFT_TO_RIGHT

  GTK_PROGRESS_RIGHT_TO_LEFT

  GTK_PROGRESS_BOTTOM_TO_TOP

  GTK_PROGRESS_TOP_TO_BOTTOM

  When used as a measure of how far a process has progressed, the ProgressBar can be set to display its value in either a continuous or discrete mode. In continuous mode, the progress bar is updated for each value. In discrete mode, the progress bar
is updated in a number of discrete blocks. The number of blocks is also configurable.

  The style of a progress bar can be set using the following function.


void gtk_progress_bar_set_bar_style( GtkProgressBar*pbar,
GtkProgressBarStylestyle );

  The style parameter can take one of two values:

  GTK_PROGRESS_CONTINUOUS

  GTK_PROGRESS_DISCRETE

  The number of discrete blocks can be set by calling


void gtk_progress_bar_set_discrete_blocks( GtkProgressBar *pbar,
guint blocks );

  As well as indicating the amount of progress that has occured, the progress bar may be set to just indicate that there is some activity. This can be useful in situations where progress cannot be measured against a value range. Activity mode is not
effected by the bar style that is described above, and overrides it. This mode is either TRUE or FALSE, and is selected by the following function.


void gtk_progress_set_activity_mode( GtkProgress *progress,
guintactivity_mode );

  The step size of the activity indicator, and the number of blocks are set using the following functions.


void gtk_progress_bar_set_activity_step( GtkProgressBar *pbar,
guint step );
void gtk_progress_bar_set_activity_blocks( GtkProgressBar *pbar,
guint blocks );

  When in continuous mode, the progress bar can also display a configurable text string within its trough, using the following function.


void gtk_progress_set_format_string(GtkProgress *progress,gchar *format);

   The format argument is similiar to one that would be used in a C printf statement. The following directives may be used within the format string:

  %p - percentage

  %v - value

  %l - lower range value

  %u - upper range value

  The displaying of this text string can be toggled using:


void gtk_progress_set_show_text( GtkProgress *progress,gint show_text );

  The show_text argument is a boolean TRUE/FALSE value. The appearance of the text can be modified further using:


void gtk_progress_set_text_alignment( GtkProgress *progress,
gfloat x_align,gfloat y_align );

   The x_align and y_align arguments take values between 0.0 and 1.0. Their values indicate the position of the text string within the trough. Values of 0.0 for both would place the string in the top left hand corner; values of 0.5 (the default)
centres the text, and values of 1.0 places the text in the lower right hand corner.

   The current text setting of a progress object can be retrieved using the current or a specified adjustment value using the following two functions. The character string returned by these functions should be freed by the application (using the
g_free() function). These functions return the formatted string that would be displayed within the trough.


gchar *gtk_progress_get_current_text( GtkProgress *progress );
gchar *gtk_progress_get_text_from_value( GtkProgress *progress,
gfloat value );

  There is yet another way to change the range and value of a progress object using the following function:


void gtk_progress_configure( GtkProgress*progress,
gfloatvalue,gfloatmin,gfloatmax );

  This function provides quite a simple interface to the range and value of a progress object.

  The remaining functions can be used to get and set the current value of a progess object in various types and formats:


void gtk_progress_set_percentage( GtkProgress *progress,
gfloat percentage );
void gtk_progress_set_value( GtkProgress *progress,
gfloat value );
gfloat gtk_progress_get_value( GtkProgress *progress );
gfloat gtk_progress_get_current_percentage( GtkProgress *progress );
gfloat gtk_progress_get_percentage_from_value( GtkProgress *progress,
gfloat value );

   These functions are pretty self explanatory. The last function uses the the adjustment of the specified progess object to compute the percentage value of the given range value.

  Progress Bars are usually used with timeouts or other such functions (see section on Timeouts, I/O and Idle Functions) to give the illusion of multitasking. All will employ the gtk_progress_bar_update function in the same manner.

  Here is an example of the progress bar, updated using timeouts. This code also shows you how to reset the Progress Bar.


/* example-start progressbar progressbar.c */
#include
typedef struct _ProgressData {
GtkWidget *window;
GtkWidget *pbar;
int timer;
} ProgressData;
/* Update the value of the progress bar so that we get
* some movement */
gint progress_timeout( gpointer data )
{
gfloat new_val;
GtkAdjustment *adj;
/* Calculate the value of the progress bar using the
* value range set in the adjustment object */
new_val = gtk_progress_get_value( GTK_PROGRESS(data) ) + 1;
adj = GTK_PROGRESS (data)->adjustment;
if (new_val > adj->upper)
new_val = adj->lower;
/* Set the new value */
gtk_progress_set_value (GTK_PROGRESS (data), new_val);
/* As this is a timeout function, return TRUE so that it
* continues to get called */
return(TRUE);
}
/* Callback that toggles the text display within the progress
* bar trough */
void toggle_show_text( GtkWidget*widget,
ProgressData *pdata )
{
gtk_progress_set_show_text (GTK_PROGRESS (pdata->pbar),
GTK_TOGGLE_BUTTON (widget)->active);
}
/* Callback that toggles the activity mode of the progress
* bar */
void toggle_activity_mode( GtkWidget*widget,ProgressData *pdata )
{
gtk_progress_set_activity_mode (GTK_PROGRESS (pdata->pbar),
GTK_TOGGLE_BUTTON (widget)->active);
}
/* Callback that toggles the continuous mode of the progress
* bar */
void set_continuous_mode( GtkWidget*widget,ProgressData *pdata )
{
gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
GTK_PROGRESS_CONTINUOUS);
}
/* Callback that toggles the discrete mode of the progress
* bar */
void set_discrete_mode( GtkWidget*widget,
ProgressData *pdata )
{
gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
GTK_PROGRESS_DISCRETE);
}
/* Clean up allocated memory and remove the timer */
void destroy_progress( GtkWidget *widget,ProgressData *pdata)
{
gtk_timeout_remove (pdata->timer);
pdata->timer = 0;
pdata->window = NULL;
g_free(pdata);
gtk_main_quit();
}
int main( int argc,
char *argv[])
{
ProgressData *pdata;
GtkWidget *align;
GtkWidget *separator;
GtkWidget *table;
GtkAdjustment *adj;
GtkWidget *button;
GtkWidget *check;
GtkWidget *vbox;
gtk_init (&argc, &argv);
/* Allocate memory for the data that is passwd to the callbacks */
pdata = g_malloc( sizeof(ProgressData) );
pdata->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_policy (GTK_WINDOW (pdata->window), FALSE, FALSE, TRUE);
gtk_signal_connect (GTK_OBJECT (pdata->window), "destroy",
GTK_SIGNAL_FUNC (destroy_progress),
pdata);
gtk_window_set_title (GTK_WINDOW (pdata->window), "GtkProgressBar");
gtk_container_set_border_width (GTK_CONTAINER (pdata->window), 0);
vbox = gtk_vbox_new (FALSE, 5);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
gtk_container_add (GTK_CONTAINER (pdata->window), vbox);
gtk_widget_show(vbox);
/* Create a centering alignment object */
align = gtk_alignment_new (0.5, 0.5, 0, 0);
gtk_box_pack_start (GTK_BOX (vbox), align, FALSE, FALSE, 5);
gtk_widget_show(align);
/* Create a Adjusment object to hold the range of the
* progress bar */
adj = (GtkAdjustment *) gtk_adjustment_new (0, 1, 150, 0, 0, 0);
/* Create the GtkProgressBar using the adjustment */
pdata->pbar = gtk_progress_bar_new_with_adjustment (adj);
/* Set the format of the string that can be displayed in the
* trough of the progress bar:
* %p - percentage
* %v - value
* %l - lower range value
* %u - upper range value */
gtk_progress_set_format_string (GTK_PROGRESS (pdata->pbar),
"%v from [%l-%u] (=%p%%)");
gtk_container_add (GTK_CONTAINER (align), pdata->pbar);
gtk_widget_show(pdata->pbar);
/* Add a timer callback to update the value of the progress bar */
pdata->timer = gtk_timeout_add (100, progress_timeout, pdata->pbar);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
gtk_widget_show(separator);
/* rows, columns, homogeneous */
table = gtk_table_new (2, 3, FALSE);
gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0);
gtk_widget_show(table);
/* Add a check button to select displaying of the trough text */
check = gtk_check_button_new_with_label ("Show text");
gtk_table_attach (GTK_TABLE (table), check, 0, 1, 0, 1,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (check), "clicked",
GTK_SIGNAL_FUNC (toggle_show_text),
pdata);
gtk_widget_show(check);
/* Add a check button to toggle activity mode */
check = gtk_check_button_new_with_label ("Activity mode");
gtk_table_attach (GTK_TABLE (table), check, 0, 1, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (check), "clicked",
GTK_SIGNAL_FUNC (toggle_activity_mode),
pdata);
gtk_widget_show(check);
separator = gtk_vseparator_new ();
gtk_table_attach (GTK_TABLE (table), separator, 1, 2, 0, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_widget_show(separator);
/* Add a radio button to select continuous display mode */
button = gtk_radio_button_new_with_label (NULL, "Continuous");
gtk_table_attach (GTK_TABLE (table), button, 2, 3, 0, 1,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (set_continuous_mode),
pdata);
gtk_widget_show (button);
/* Add a radio button to select discrete display mode */
button = gtk_radio_button_new_with_label(
gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
"Discrete");
gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (set_discrete_mode),
pdata);
gtk_widget_show (button);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
gtk_widget_show(separator);
/* Add a button to exit the program */
button = gtk_button_new_with_label ("close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) gtk_widget_destroy,GTK_OBJECT (pdata->window));
gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
/* This makes it so the button is the default. */
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
/* This grabs this button to be the default button. Simply hitting
* the "Enter" key will cause this button to activate. */
gtk_widget_grab_default (button);
gtk_widget_show(button);
gtk_widget_show (pdata->window);
gtk_main ();
return(0);
}
/* example-end */

9.5 Dialogs

  The Dialog widget is very simple, and is actually just a window with a few things pre-packed into it for you. The structure for a Dialog is:


struct GtkDialog
{
GtkWindow window;
GtkWidget *vbox;
GtkWidget *action_area;
};

  So you see, it simply creates a window, and then packs a vbox into the top, which contains a separator and then an hbox called the "action_area".

  The Dialog widget can be used for pop-up messages to the user, and other similar tasks. It is really basic, and there is only one function for the dialog box, which is:


GtkWidget *gtk_dialog_new( void );

  So to create a new dialog box, use,


GtkWidget *window;
window = gtk_dialog_new ();

  This will create the dialog box, and it is now up to you to use it. You could pack a button in the action_area by doing something like this:


button = ...
gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area),
button, TRUE, TRUE, 0);
gtk_widget_show (button);

  And you could add to the vbox area by packing, for instance, a label in it, try something like this:


label = gtk_label_new ("Dialogs are groovy");
gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox),
label, TRUE, TRUE, 0);
gtk_widget_show (label);

  As an example in using the dialog box, you could put two buttons in the action_area, a Cancel button and an Ok button, and a label in the vbox area, asking the user a question or giving an error etc. Then you could attach a different signal to
each of the buttons and perform the operation the user selects.

   If the simple functionality provided by the default vertical and horizontal boxes in the two areas doesn't give you enough control for your application, then you can simply pack another layout widget into the boxes provided. For example, you could
pack a table into the vertical box.

9.6 Pixmaps

   Pixmaps are data structures that contain pictures. These pictures can be used in various places, but most commonly as icons on the X desktop, or as cursors.

  A pixmap which only has 2 colors is called a bitmap, and there are a few additional routines for handling this common special case.

  To understand pixmaps, it would help to understand how X window system works. Under X, applications do not need to be running on the same computer that is interacting with the user. Instead, the various applications, called "clients", all
communicate with a program which displays the graphics and handles the keyboard and mouse. This program which interacts directly with the user is called a "display server" or "X server." Since the communication might take place over a network, it's
important to keep some information with the X server. Pixmaps, for example, are stored in the memory of the X server. This means that once pixmap values are set, they don't need to keep getting transmitted over the network; instead a command is sent
to "display pixmap number XYZ here." Even if you aren't using X with GTK currently, using constructs such as Pixmaps will make your programs work acceptably under X.

  To use pixmaps in GTK, we must first build a GdkPixmap structure using routines from the GDK layer. Pixmaps can either be created from in-memory data, or from data read from a file. We'll go through each of the calls to create a pixmap.


GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
gchar *data,gint width,gint height );

  This routine is used to create a single-plane pixmap (2 colors) from data in memory. Each bit of the data represents whether that pixel is off or on. Width and height are in pixels. The GdkWindow pointer is to the current window, since a pixmap's
resources are meaningful only in the context of the screen where it is to be displayed.


GdkPixmap *gdk_pixmap_create_from_data( GdkWindow *window,
gchar *data,gint width,gint height,gint depth,GdkColor*fg,GdkColor*bg );

  This is used to create a pixmap of the given depth (number of colors) from the bitmap data specified. fg and bg are the foreground and background color to use.


GdkPixmap *gdk_pixmap_create_from_xpm( GdkWindow *window,
GdkBitmap**mask,GdkColor*transparent_color,const gchar *filename );

   XPM format is a readable pixmap representation for the X Window System. It is widely used and many different utilities are available for creating image files in this format. The file specified by filename must contain an image in that format and
it is loaded into the pixmap structure. The mask specifies which bits of the pixmap are opaque. All other bits are colored using the color specified by transparent_color. An example using this follows below.


GdkPixmap *gdk_pixmap_create_from_xpm_d( GdkWindow*window,
GdkBitmap **mask,GdkColor *transparent_color,gchar **data );

   Small images can be incorporated into a program as data in the XPM format. A pixmap is created using this data, instead of reading it from a file. An example of such data is


/* XPM */
static const char * xpm_data[] = {
"16 16 3 1",
" c None",
".c #000000000000",
"Xc #FFFFFFFFFFFF",
"",
" ...... ",
" .XXX.X.",
" .XXX.XX. ",
" .XXX.XXX.",
" .XXX.....",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .........",
"",
""};

  When we're done using a pixmap and not likely to reuse it again soon, it is a good idea to release the resource using gdk_pixmap_unref(). Pixmaps should be considered a precious resource, because they take up memory in the end-user's X server
process. Even though the X client you write may run on a powerful "server" computer, the user may be running the X server on a small personal computer.

  Once we've created a pixmap, we can display it as a GTK widget. We must create a GTK pixmap widget to contain the GDK pixmap. This is done using


GtkWidget *gtk_pixmap_new( GdkPixmap *pixmap,GdkBitmap *mask );

  The other pixmap widget calls are


guint gtk_pixmap_get_type( void );
voidgtk_pixmap_set( GtkPixmap*pixmap,GdkPixmap*val,GdkBitmap*mask );
voidgtk_pixmap_get( GtkPixmap*pixmap,
GdkPixmap **val,GdkBitmap **mask);

  gtk_pixmap_set is used to change the pixmap that the widget is currently managing. Val is the pixmap created using GDK.

  The following is an example of using a pixmap in a button.


/* example-start pixmap pixmap.c */
#include
/* XPM data of Open-File icon */
static const char * xpm_data[] = {
"16 16 3 1",
" c None",
".c #000000000000",
"Xc #FFFFFFFFFFFF",
"",
" ...... ",
" .XXX.X.",
" .XXX.XX. ",
" .XXX.XXX.",
" .XXX.....",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .XXXXXXX.",
" .........",
"",
""};
/* when invoked (via signal delete_event), terminates the application.*/
gint close_application( GtkWidget *widget,GdkEvent*event,gpointer data )
{
gtk_main_quit();
return(FALSE);
}
/* is invoked when the button is clicked.It just prints a message.*/
void button_clicked( GtkWidget *widget,gpointer data )
{
g_print( "button clicked
" );
}
int main( int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window, *pixmapwid, *button;
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkStyle *style;
/* create the main window, and attach delete_event signal to terminating
the application */
gtk_init( &argc, &argv );
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
gtk_signal_connect( GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (close_application), NULL );
gtk_container_set_border_width( GTK_CONTAINER (window), 10 );
gtk_widget_show( window );
/* now for the pixmap from gdk */
style = gtk_widget_get_style( window );
pixmap = gdk_pixmap_create_from_xpm_d( window->window,&mask,
&style->bg[GTK_STATE_NORMAL],
(gchar **)xpm_data );
/* a pixmap widget to contain the pixmap */
pixmapwid = gtk_pixmap_new( pixmap, mask );
gtk_widget_show( pixmapwid );
/* a button to contain the pixmap widget */
button = gtk_button_new();
gtk_container_add( GTK_CONTAINER(button), pixmapwid );
gtk_container_add( GTK_CONTAINER(window), button );
gtk_widget_show( button );
gtk_signal_connect( GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC(button_clicked), NULL );
/* show the window */
gtk_main ();
return 0;
}
/* example-end */

  To load a file from an XPM data file called icon0.xpm in the current directory, we would have created the pixmap thus


/* load a pixmap from a file */
pixmap = gdk_pixmap_create_from_xpm( window->window, &mask,
&style->bg[GTK_STATE_NORMAL],
"./icon0.xpm" );
pixmapwid = gtk_pixmap_new( pixmap, mask );
gtk_widget_show( pixmapwid );
gtk_container_add( GTK_CONTAINER(window), pixmapwid );

   A disadvantage of using pixmaps is that the displayed object is always rectangular, regardless of the image. We would like to create desktops and applications with icons that have more natural shapes. For example, for a game interface, we would
like to have round buttons to push. The way to do this is using shaped windows.

   A shaped window is simply a pixmap where the background pixels are transparent. This way, when the background image is multi-colored, we don't overwrite it with a rectangular, non-matching border around our icon. The following example displays a
full wheelbarrow image on the desktop.


/* example-start wheelbarrow wheelbarrow.c */
#include
/* XPM */
static char * WheelbarrowFull_xpm[] = {
"48 48 64 1",
" c None",
".c #DF7DCF3CC71B",
"Xc #965875D669A6",
"oc #71C671C671C6",
"Oc #A699A289A699",
"+c #965892489658",
"@c #8E38410330C2",
"#c #D75C7DF769A6",
"$c #F7DECF3CC71B",
"%c #96588A288E38",
"&c #A69992489E79",
"*c #8E3886178E38",
"=c #104008200820",
"-c #596510401040",
";c #C71B30C230C2",
":c #C71B9A699658",
">c #618561856185",
",c #20811C712081",
" "1c #861720812081",
"2c #DF7D4D344103",
"3c #79E769A671C6",
"4c #861782078617",
"5c #41033CF34103",
"6c #000000000000",
"7c #49241C711040",
"8c #492445144924",
"9c #082008200820",
"0c #69A618611861",
"qc #B6DA71C65144",
"wc #410330C238E3",
"ec #CF3CBAEAB6DA",
"rc #71C6451430C2",
"tc #EFBEDB6CD75C",
"yc #28A208200820",
"uc #186110401040",
"ic #596528A21861",
"pc #71C661855965",
"ac #A69996589658",
"sc #30C228A230C2",
"dc #BEFBA289AEBA",
"fc #596545145144",
"gc #30C230C230C2",
"hc #8E3882078617",
"jc #208118612081",
"kc #38E30C300820",
"lc #30C2208128A2",
"zc #38E328A238E3",
"xc #514438E34924",
"cc #618555555965",
"vc #30C2208130C2",
"bc #38E328A230C2",
"nc #28A228A228A2",
"mc #41032CB228A2",
"Mc #104010401040",
"Nc #492438E34103",
"Bc #28A2208128A2",
"Vc #A699596538E3",
"Cc #30C21C711040",
"Zc #30C218611040",
"Ac #965865955965",
"Sc #618534D32081",
"Dc #38E31C711040",
"Fc #082000000820",
"",
".XoO",
" +@#$%o&",
" *=-;#::o+",
" >,<12#:34",
" 45671#:X3",
" +89<02qwo",
"e*>,67;ro ",
"ty> 459@>+&&",
"$2u+> "%$;=**3:.Xa.dfg>",
"Oh$;ya *3d.a8j,Xe.d3g8+ ",
" Oh$;ka*3d$a8lz,,xxc:.e3g54 ",
"Oh$;kO *pd$%svbzz,sxxxxfX..&wn> ",
" Oh$@mO*3dthwlsslszjzxxxxxxx3:td8M4 ",
"Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B* ",
" Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5& ",
"Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM*",
" OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
"2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
":,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
" +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
"*#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
" p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
" OA1 "3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
" @26MvzxNzvlbwfpdettttttttttt.c,n&",
" *;16=lsNwwNwgsvslbwwvccc3pcfu "p;<69BvwwsszslllbBlllllllu<5+ ",
"OS0y6FBlvvvzvzss,u=Blllj=54 ",
" c1-699Blvlllllu7k96MMMg4 ",
" *10y8n6FjvllllB<166668 ",
"S-kg+>666 "p71=4 m69996kD8Z-66698&&",
"&i0ycm6n4 ogk17,0<6666g ",
" N-k-<> >=01-kuu666>",
" ,6ky&&46-10ul,66,",
" Ou0<> o66y "*kk5 >66By7=xu664 ",
" < " *>> +66uv,zN666* ",
"566,xxj669",
"4666FF666>",
" >966666M ",
"oM6668+ ",
"*4",
"",
""};
/* When invoked (via signal delete_event), terminates the application */
gint close_application( GtkWidget *widget,
GdkEvent*event,
gpointer data )
{
gtk_main_quit();
return(FALSE);
}
int main (int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window, *pixmap, *fixed;
GdkPixmap *gdk_pixmap;
GdkBitmap *mask;
GtkStyle *style;
GdkGC *gc;
/* Create the main window, and attach delete_event signal to terminate
* the application.Note that the main window will not have a titlebar
* since we're making it a popup. */
gtk_init (&argc, &argv);
window = gtk_window_new( GTK_WINDOW_POPUP );
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (close_application), NULL);
gtk_widget_show (window);
/* Now for the pixmap and the pixmap widget */
style = gtk_widget_get_default_style();
gc = style->black_gc;
gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
&style->bg[GTK_STATE_NORMAL],
WheelbarrowFull_xpm );
pixmap = gtk_pixmap_new( gdk_pixmap, mask );
gtk_widget_show( pixmap );
/* To display the pixmap, we use a fixed widget to place the pixmap */
fixed = gtk_fixed_new();
gtk_widget_set_usize( fixed, 200, 200 );
gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
gtk_container_add( GTK_CONTAINER(window), fixed );
gtk_widget_show( fixed );
/* This masks out everything except for the image itself */
gtk_widget_shape_combine_mask( window, mask, 0, 0 );
/* show the window */
gtk_widget_set_uposition( window, 20, 400 );
gtk_widget_show( window );
gtk_main ();
return(0);
}
/* example-end */

  To make the wheelbarrow image sensitive, we could attach the button press event signal to make it do something. The following few lines would make the picture sensitive to a mouse button being pressed which makes the application terminate.


gtk_widget_set_events( window,
gtk_widget_get_events( window ) |
GDK_BUTTON_PRESS_MASK );
gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
GTK_SIGNAL_FUNC(close_application), NULL );

9.7 Rulers

   Ruler widgets are used to indicate the location of the mouse pointer in a given window. A window can have a vertical ruler spanning across the width and a horizontal ruler spanning down the height. A small triangular indicator on the ruler shows
the exact location of the pointer relative to the ruler.

  A ruler must first be created. Horizontal and vertical rulers are created using


GtkWidget *gtk_hruler_new( void );/* horizontal ruler */
GtkWidget *gtk_vruler_new( void );/* vertical ruler */

  Once a ruler is created, we can define the unit of measurement. Units of measure for rulers can beGTK_PIXELS, GTK_INCHES or GTK_CENTIMETERS. This is set using


void gtk_ruler_set_metric( GtkRuler*ruler,GtkMetricTypemetric );

  The default measure is GTK_PIXELS.


gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );

   Other important characteristics of a ruler are how to mark the units of scale and where the position indicator is initially placed. These are set for a ruler using


void gtk_ruler_set_range( GtkRuler *ruler,
gfloatlower,gfloatupper,gfloatposition,gfloatmax_size );

  The lower and upper arguments define the extent of the ruler, and max_size is the largest possible number that will be displayed. Position defines the initial position of the pointer indicator within the ruler.

  A vertical ruler can span an 800 pixel wide window thus


gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);

  The markings displayed on the ruler will be from 0 to 800, with a number for every 100 pixels. If instead we wanted the ruler to range from 7 to 16, we would code


gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);

   The indicator on the ruler is a small triangular mark that indicates the position of the pointer relative to the ruler. If the ruler is used to follow the mouse pointer, the motion_notify_event signal should be connected to the motion_notify_event
method of the ruler. To follow all mouse movements within a window area, we would use


#define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
(GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
GTK_OBJECT(ruler) );

   The following example creates a drawing area with a horizontal ruler above it and a vertical ruler to the left of it. The size of the drawing area is 600 pixels wide by 400 pixels high. The horizontal ruler spans from 7 to 13 with a mark every 100
pixels, while the vertical ruler spans from 0 to 400 with a mark every 100 pixels. Placement of the drawing area and the rulers is done using a table.


/* example-start rulers rulers.c */
#include
#define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
#define XSIZE600
#define YSIZE400
/* This routine gets control when the close button is clicked */
gint close_application( GtkWidget *widget,
GdkEvent*event,
gpointer data )
{
gtk_main_quit();
return(FALSE);
}
/* The main routine */
int main( int argc,
char *argv[] ) {
GtkWidget *window, *table, *area, *hrule, *vrule;
/* Initialize GTK and create the main window */
gtk_init( &argc, &argv );
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC( close_application ), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create a table for placing the ruler and the drawing area */
table = gtk_table_new( 3, 2, FALSE );
gtk_container_add( GTK_CONTAINER(window), table );
area = gtk_drawing_area_new();
gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK |
GDK_POINTER_MOTION_HINT_MASK );
/* The horizontal ruler goes on top. As the mouse moves across the
* drawing area, a motion_notify_event is passed to the
* appropriate event handler for the ruler. */
hrule = gtk_hruler_new();
gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
(GtkSignalFunc)EVENT_METHOD(hrule,
motion_notify_event),
GTK_OBJECT(hrule) );
/*GTK_WIDGET_CLASS(GTK_OBJECT(hrule)->klass)->motion_notify_event,*/
gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
/* The vertical ruler goes on the left. As the mouse moves across
* the drawing area, a motion_notify_event is passed to the
* appropriate event handler for the ruler. */
vrule = gtk_vruler_new();
gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
(GtkSignalFunc)
GTK_WIDGET_CLASS(GTK_OBJECT(vrule)->klass)->
motion_notify_event,
GTK_OBJECT(vrule) );
gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
/* Now show everything */
gtk_widget_show( area );
gtk_widget_show( hrule );
gtk_widget_show( vrule );
gtk_widget_show( table );
gtk_widget_show( window );
gtk_main();
return(0);
}
/* example-end */

9.8 Statusbars

   Statusbars are simple widgets used to display a text message. They keep a stack of the messages pushed onto them, so that popping the current message will re-display the previous text message.

   In order to allow different parts of an application to use the same statusbar to display messages, the statusbar widget issues Context Identifiers which are used to identify different "users". The message on top of the stack is the one displayed,
no matter what context it is in. Messages are stacked in last-in-first-out order, not context identifier order.

  A statusbar is created with a call to:


GtkWidget *gtk_statusbar_new( void );

  A new Context Identifier is requested using a call to the following function with a short textual description of the context:


guint gtk_statusbar_get_context_id( GtkStatusbar *statusbar,
const gchar*context_description );

  There are three functions that can operate on statusbars:


guint gtk_statusbar_push( GtkStatusbar *statusbar,
guint context_id,gchar*text );
void gtk_statusbar_pop( GtkStatusbar *statusbar)
guint context_id );
void gtk_statusbar_remove( GtkStatusbar *statusbar,
guint context_id,guint message_id );

  The first, gtk_statusbar_push, is used to add a new message to the statusbar. It returns a Message Identifier, which can be passed later to the function gtk_statusbar_remove to remove the message with the given Message and Context Identifiers from
the statusbar's stack.

  The function gtk_statusbar_pop removes the message highest in the stack with the given Context Identifier.

  The following example creates a statusbar and two buttons, one for pushing items onto the statusbar, and one for popping the last item back off.


/* example-start statusbar statusbar.c */
#include
#include
GtkWidget *status_bar;
void push_item( GtkWidget *widget,gpointer data )
{
static int count = 1;
char buff[20];
g_snprintf(buff, 20, "Item %d", count++);
gtk_statusbar_push( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data), buff);
return;
}
void pop_item( GtkWidget *widget,gpointer data )
{
gtk_statusbar_pop( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data) );
return;
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *vbox;
GtkWidget *button;
gint context_id;
gtk_init (&argc, &argv);
/* create a new window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
gtk_signal_connect(GTK_OBJECT (window), "delete_event",
(GtkSignalFunc) gtk_exit, NULL);
vbox = gtk_vbox_new(FALSE, 1);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_widget_show(vbox);
status_bar = gtk_statusbar_new();
gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
gtk_widget_show (status_bar);
context_id = gtk_statusbar_get_context_id(
GTK_STATUSBAR(status_bar), "Statusbar example");
button = gtk_button_new_with_label("push item");
gtk_signal_connect(GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC (push_item), GINT_TO_POINTER(context_id) );
gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
gtk_widget_show(button);
button = gtk_button_new_with_label("pop last item");
gtk_signal_connect(GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC (pop_item), GINT_TO_POINTER(context_id) );
gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
gtk_widget_show(button);
/* always display the window as the last step so it all splashes on
* the screen at once. */
gtk_widget_show(window);
gtk_main ();
return 0;
}
/* example-end */

9.9 Text Entries

   The Entry widget allows text to be typed and displayed in a single line text box. The text may be set with function calls that allow new text to replace, prepend or append the current contents of the Entry widget.

  There are two functions for creating Entry widgets:


GtkWidget *gtk_entry_new( void );
GtkWidget *gtk_entry_new_with_max_length( guint16 max );

  The first just creates a new Entry widget, whilst the second creates a new Entry and sets a limit on the length of the text within the Entry.

  There are several functions for altering the text which is currently within the Entry widget.


void gtk_entry_set_text( GtkEntry*entry,const gchar *text );
void gtk_entry_append_text( GtkEntry*entry,const gchar *text );
void gtk_entry_prepend_text( GtkEntry*entry,const gchar *text );

  The function gtk_entry_set_text sets the contents of the Entry widget, replacing the current contents. The functions gtk_entry_append_text and gtk_entry_prepend_text allow the current contents to be appended and prepended to.

  The next function allows the current insertion point to be set.


void gtk_entry_set_position( GtkEntry *entry,gintposition );

   The contents of the Entry can be retrieved by using a call to the following function. This is useful in the callback functions described below.


gchar *gtk_entry_get_text( GtkEntry *entry );

  The value returned by this function is used internally, and must not be freed using either free() or g_free()

  If we don't want the contents of the Entry to be changed by someone typing into it, we can change its editable state.


void gtk_entry_set_editable( GtkEntry *entry,gbooleaneditable );

   The function above allows us to toggle the editable state of the Entry widget by passing in a TRUE or FALSE value for the editable argument.

   If we are using the Entry where we don't want the text entered to be visible, for example when a password is being entered, we can use the following function, which also takes a boolean flag.


void gtk_entry_set_visibility( GtkEntry *entry,gbooleanvisible );

   A region of the text may be set as selected by using the following function. This would most often be used after setting some default text in an Entry, making it easy for the user to remove it.


void gtk_entry_select_region( GtkEntry *entry,gintstart,gintend );

  If we want to catch when the user has entered text, we can connect to the activate or changed signal. Activate is raised when the user hits the enter key within the Entry widget. Changed is raised when the text changes at all, e.g., for every
character entered or removed.

  The following code is an example of using an Entry widget.


/* example-start entry entry.c */
#include
#include
void enter_callback( GtkWidget *widget,GtkWidget *entry )
{
gchar *entry_text;
entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
printf("Entry contents: %s
", entry_text);
}
void entry_toggle_editable( GtkWidget *checkbutton,
GtkWidget *entry )
{
gtk_entry_set_editable(GTK_ENTRY(entry),
GTK_TOGGLE_BUTTON(checkbutton)->active);
}
void entry_toggle_visibility( GtkWidget *checkbutton,
GtkWidget *entry )
{
gtk_entry_set_visibility(GTK_ENTRY(entry),
GTK_TOGGLE_BUTTON(checkbutton)->active);
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *vbox, *hbox;
GtkWidget *entry;
GtkWidget *button;
GtkWidget *check;
gtk_init (&argc, &argv);
/* create a new window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
gtk_signal_connect(GTK_OBJECT (window), "delete_event",
(GtkSignalFunc) gtk_exit, NULL);
vbox = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), vbox);
gtk_widget_show (vbox);
entry = gtk_entry_new_with_max_length (50);
gtk_signal_connect(GTK_OBJECT(entry), "activate",
GTK_SIGNAL_FUNC(enter_callback),
entry);
gtk_entry_set_text (GTK_ENTRY (entry), "hello");
gtk_entry_append_text (GTK_ENTRY (entry), " world");
gtk_entry_select_region (GTK_ENTRY (entry),
0, GTK_ENTRY(entry)->text_length);
gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
gtk_widget_show (entry);
hbox = gtk_hbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (vbox), hbox);
gtk_widget_show (hbox);
check = gtk_check_button_new_with_label("Editable");
gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
gtk_signal_connect (GTK_OBJECT(check), "toggled",
GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE);
gtk_widget_show (check);
check = gtk_check_button_new_with_label("Visible");
gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
gtk_signal_connect (GTK_OBJECT(check), "toggled",
GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE);
gtk_widget_show (check);
button = gtk_button_new_with_label ("Close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC(gtk_exit),
GTK_OBJECT (window));
gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
gtk_widget_grab_default (button);
gtk_widget_show (button);
gtk_widget_show(window);
gtk_main();
return(0);
}
/* example-end */

9.10 Spin Buttons

   The Spin Button widget is generally used to allow the user to select a value from a range of numeric values. It consists of a text entry box with up and down arrow buttons attached to the side. Selecting one of the buttons causes the value to
"spin" up and down the range of possible values. The entry box may also be edited directly to enter a specific value.

   The Spin Button allows the value to have zero or a number of decimal places and to be incremented/decremented in configurable steps. The action of holding down one of the buttons optionally results in an acceleration of change in the value
according to how long it is depressed.

   The Spin Button uses an Adjustment object to hold information about the range of values that the spin button can take. This makes for a powerful Spin Button widget.

  Recall that an adjustment widget is created with the following function, which illustrates the information that it holds:


GtkObject *gtk_adjustment_new( gfloat value,gfloat lower,gfloat upper,
gfloat step_increment,gfloat page_increment,gfloat page_size );

  These attributes of an Adjustment are used by the Spin Button in the following way:

  value: initial value for the Spin Button

  lower: lower range value

  upper: upper range value

  step_increment: value to increment/decrement when pressing mouse button 1 on a button

  page_increment: value to increment/decrement when pressing mouse button 2 on a button

  page_size: unused

  Additionally, mouse button 3 can be used to jump directly to the upper or lower values when used to select one of the buttons. Lets look at how to create a Spin Button:


GtkWidget *gtk_spin_button_new( GtkAdjustment *adjustment,
gfloat climb_rate,guintdigits );

   The climb_rate argument take a value between 0.0 and 1.0 and indicates the amount of acceleration that the Spin Button has. The digits argument specifies the number of decimal places to which the value will be displayed.

  A Spin Button can be reconfigured after creation using the following function:


void gtk_spin_button_configure( GtkSpinButton *spin_button,
GtkAdjustment *adjustment,gfloat climb_rate,guintdigits );

   The spin_button argument specifies the Spin Button widget that is to be reconfigured. The other arguments are as specified above.

  The adjustment can be set and retrieved independantly using the following two functions:


void gtk_spin_button_set_adjustment( GtkSpinButton*spin_button,
GtkAdjustment*adjustment );
GtkAdjustment *gtk_spin_button_get_adjustment( GtkSpinButton *spin_button );

  The number of decimal places can also be altered using:


void gtk_spin_button_set_digits( GtkSpinButton *spin_button,guintdigits);

  The value that a Spin Button is currently displaying can be changed using the following function:


void gtk_spin_button_set_value( GtkSpinButton *spin_button,gfloat value );

  The current value of a Spin Button can be retrieved as either a floating point or integer value with the following functions:


gfloat gtk_spin_button_get_value_as_float( GtkSpinButton *spin_button );
gint gtk_spin_button_get_value_as_int( GtkSpinButton *spin_button );

  If you want to alter the value of a Spin Value relative to its current value, then the following function can be used:


void gtk_spin_button_spin( GtkSpinButton *spin_button,
GtkSpinTypedirection,gfloat increment );

  The direction parameter can take one of the following values:

  GTK_SPIN_STEP_FORWARD

  GTK_SPIN_STEP_BACKWARD
1

  GTK_SPIN_PAGE_FORWARD

  GTK_SPIN_PAGE_BACKWARD

  GTK_SPIN_HOME

  GTK_SPIN_END

  GTK_SPIN_USER_DEFINED

  This function packs in quite a bit of functionality, which I will attempt to clearly explain. Many of these settings use values from the Adjustment object that is associated with a Spin Button.

   GTK_SPIN_STEP_FORWARD and GTK_SPIN_STEP_BACKWARD change the value of the Spin Button by the amount specified by increment, unless increment is equal to 0, in which case the value is changed by the value of step_increment in theAdjustment.

  GTK_SPIN_PAGE_FORWARD and GTK_SPIN_PAGE_BACKWARD simply alter the value of the Spin Button by increment.

  GTK_SPIN_HOME sets the value of the Spin Button to the bottom of the Adjustments range.

  GTK_SPIN_END sets the value of the Spin Button to the top of the Adjustments range.

  GTK_SPIN_USER_DEFINED simply alters the value of the Spin Button by the specified amount.

   We move away from functions for setting and retreving the range attributes of the Spin Button now, and move onto functions that effect the appearance and behaviour of the Spin Button widget itself.

   The first of these functions is used to constrain the text box of the Spin Button such that it may only contain a numeric value. This prevents a user from typing anything other than numeric values into the text box of a Spin Button:


void gtk_spin_button_set_numeric( GtkSpinButton *spin_button,
gboolean numeric );

  You can set whether a Spin Button will wrap around between the upper and lower range values with the following function:


void gtk_spin_button_set_wrap( GtkSpinButton *spin_button,
gboolean wrap );

   You can set a Spin Button to round the value to the nearest step_increment, which is set within the Adjustment object used with the Spin Button. This is accomplished with the following function:


void gtk_spin_button_set_snap_to_ticks( GtkSpinButton*spin_button,
gbooleansnap_to_ticks );

  The update policy of a Spin Button can be changed with the following function:


void gtk_spin_button_set_update_policy( GtkSpinButton*spin_button,
GtkSpinButtonUpdatePolicy policy );

  The possible values of policy are either GTK_UPDATE_ALWAYS or GTK_UPDATE_IF_VALID.

   These policies affect the behavior of a Spin Button when parsing inserted text and syncing its value with the values of the Adjustment.

   In the case of GTK_UPDATE_IF_VALID the Spin Button only value gets changed if the text input is a numeric value that is within the range specified by the Adjustment. Otherwise the text is reset to the current value.

  In case of GTK_UPDATE_ALWAYS we ignore errors while converting text into a numeric value.

  The appearance of the buttons used in a Spin Button can be changed using the following function:


void gtk_spin_button_set_shadow_type( GtkSpinButton *spin_button,
GtkShadowTypeshadow_type );

  As usual, the shadow_type can be one of:

  GTK_SHADOW_IN

  GTK_SHADOW_OUT

  GTK_SHADOW_ETCHED_IN

  GTK_SHADOW_ETCHED_OUT

  Finally, you can explicitly request that a Spin Button update itself:


void gtk_spin_button_update( GtkSpinButton*spin_button );

  It's example time again.


/* example-start spinbutton spinbutton.c */
#include
#include
static GtkWidget *spinner1;
void toggle_snap( GtkWidget *widget,
GtkSpinButton *spin )
{
gtk_spin_button_set_snap_to_ticks (spin, GTK_TOGGLE_BUTTON
(widget)->active);
}
void toggle_numeric( GtkWidget *widget,
GtkSpinButton *spin )
{
gtk_spin_button_set_numeric (spin, GTK_TOGGLE_BUTTON (widget)->active);
}
void change_digits( GtkWidget *widget,
GtkSpinButton *spin )
{
gtk_spin_button_set_digits (GTK_SPIN_BUTTON (spinner1),
gtk_spin_button_get_value_as_int (spin));
}
void get_value( GtkWidget *widget,
gpointer data )
{
gchar buf[32];
GtkLabel *label;
GtkSpinButton *spin;
spin = GTK_SPIN_BUTTON (spinner1);
label = GTK_LABEL (gtk_object_get_user_data (GTK_OBJECT (widget)));
if (GPOINTER_TO_INT (data) == 1)
sprintf (buf, "%d", gtk_spin_button_get_value_as_int (spin));
else
sprintf (buf, "%0.*f", spin->digits,
gtk_spin_button_get_value_as_float (spin));
gtk_label_set_text (label, buf);
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *frame;
GtkWidget *hbox;
GtkWidget *main_vbox;
GtkWidget *vbox;
GtkWidget *vbox2;
GtkWidget *spinner2;
GtkWidget *spinner;
GtkWidget *button;
GtkWidget *label;
GtkWidget *val_label;
GtkAdjustment *adj;
/* Initialise GTK */
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit),
NULL);
gtk_window_set_title (GTK_WINDOW (window), "Spin Button");
main_vbox = gtk_vbox_new (FALSE, 5);
gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 10);
gtk_container_add (GTK_CONTAINER (window), main_vbox);
frame = gtk_frame_new ("Not accelerated");
gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
gtk_container_add (GTK_CONTAINER (frame), vbox);
/* Day, month, year spinners */
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 5);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
label = gtk_label_new ("Day :");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 31.0, 1.0,
5.0, 0.0);
spinner = gtk_spin_button_new (adj, 0, 0);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), TRUE);
gtk_spin_button_set_shadow_type (GTK_SPIN_BUTTON (spinner),
GTK_SHADOW_OUT);
gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
label = gtk_label_new ("Month :");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 12.0, 1.0,
5.0, 0.0);
spinner = gtk_spin_button_new (adj, 0, 0);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), TRUE);
gtk_spin_button_set_shadow_type (GTK_SPIN_BUTTON (spinner),
GTK_SHADOW_ETCHED_IN);
gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
label = gtk_label_new ("Year :");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
adj = (GtkAdjustment *) gtk_adjustment_new (1998.0, 0.0, 2100.0,
1.0, 100.0, 0.0);
spinner = gtk_spin_button_new (adj, 0, 0);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), FALSE);
gtk_spin_button_set_shadow_type (GTK_SPIN_BUTTON (spinner),
GTK_SHADOW_IN);
gtk_widget_set_usize (spinner, 55, 0);
gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
frame = gtk_frame_new ("Accelerated");
gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
gtk_container_add (GTK_CONTAINER (frame), vbox);
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
label = gtk_label_new ("Value :");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
adj = (GtkAdjustment *) gtk_adjustment_new (0.0, -10000.0, 10000.0,
0.5, 100.0, 0.0);
spinner1 = gtk_spin_button_new (adj, 1.0, 2);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner1), TRUE);
gtk_widget_set_usize (spinner1, 100, 0);
gtk_box_pack_start (GTK_BOX (vbox2), spinner1, FALSE, TRUE, 0);
vbox2 = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
label = gtk_label_new ("Digits :");
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
adj = (GtkAdjustment *) gtk_adjustment_new (2, 1, 5, 1, 1, 0);
spinner2 = gtk_spin_button_new (adj, 0.0, 0);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner2), TRUE);
gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
GTK_SIGNAL_FUNC (change_digits),
(gpointer) spinner2);
gtk_box_pack_start (GTK_BOX (vbox2), spinner2, FALSE, TRUE, 0);
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
button = gtk_check_button_new_with_label ("Snap to 0.5-ticks");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (toggle_snap),
spinner1);
gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
button = gtk_check_button_new_with_label ("Numeric only input mode");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (toggle_numeric),
spinner1);
gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
val_label = gtk_label_new ("");
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
button = gtk_button_new_with_label ("Value as Int");
gtk_object_set_user_data (GTK_OBJECT (button), val_label);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (get_value),
GINT_TO_POINTER (1));
gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
button = gtk_button_new_with_label ("Value as Float");
gtk_object_set_user_data (GTK_OBJECT (button), val_label);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (get_value),
GINT_TO_POINTER (2));
gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (vbox), val_label, TRUE, TRUE, 0);
gtk_label_set_text (GTK_LABEL (val_label), "0");
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, TRUE, 0);
button = gtk_button_new_with_label ("Close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (gtk_widget_destroy),
GTK_OBJECT (window));
gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
gtk_widget_show_all (window);
/* Enter the event loop */
gtk_main ();
return(0);
}
/* example-end */

9.11 Combo Box

   The combo box is another fairly simple widget that is really just a collection of other widgets. From the user's point of view, the widget consists of a text entry box and a pull down menu from which the user can select one of a set of predefined
entries. Alternatively, the user can type a different option directly into the text box.

  The following extract from the structure that defines a Combo Box identifies several of the components:


struct _GtkCombo {
GtkHBox hbox;
GtkWidget *entry;
GtkWidget *button;
GtkWidget *popup;
GtkWidget *popwin;
GtkWidget *list;
...};

  As you can see, the Combo Box has two principal parts that you really care about: an entry and a list.

  First off, to create a combo box, use:


GtkWidget *gtk_combo_new( void );

  Now, if you want to set the string in the entry section of the combo box, this is done by manipulating the entry widget directly:


gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), "My String.");

  To set the values in the popdown list, one uses the function:


void gtk_combo_set_popdown_strings( GtkCombo *combo,GList*strings );

  Before you can do this, you have to assemble a GList of the strings that you want. GList is a linked list implementation that is part of GLib, a library supporing GTK. For the moment, the quick and dirty explanation is that you need to set up a
GList pointer, set it equal to NULL, then append strings to it with


GList *g_list_append( GList *glist, gpointer data );

   It is important that you set the initial GList pointer to NULL. The value returned from the g_list_append function must be used as the new pointer to the GList.

  Here's a typical code segment for creating a set of options:


GList *glist=NULL;
glist = g_list_append(glist, "String 1");
glist = g_list_append(glist, "String 2");
glist = g_list_append(glist, "String 3");
glist = g_list_append(glist, "String 4");
gtk_combo_set_popdown_strings( GTK_COMBO(combo), glist) ;

   The combo widget makes a copy of the strings passed to it in the glist structure. As a result, you need to make sure you free the memory used by the list if that is appropriate for your application.

   At this point you have a working combo box that has been set up. There are a few aspects of its behavior that you can change. These are accomplished with the functions:


void gtk_combo_set_use_arrows( GtkCombo *combo,gintval );
void gtk_combo_set_use_arrows_always( GtkCombo *combo,gintval );
void gtk_combo_set_case_sensitive( GtkCombo *combo,gintval );

  gtk_combo_set_use_arrows() lets the user change the value in the entry using the up/down arrow keys. This doesn't bring up the list, but rather replaces the current text in the entry with the next list entry (up or down, as your key choice
indicates). It does this by searching in the list for the item corresponding to the current value in the entry and selecting the previous/next item accordingly. Usually in an entry the arrow keys are used to change focus (you can do that anyway using
TAB). Note that when the current item is the last of the list and you press arrow-down it changes the focus (the same applies with the first item and arrow-up).

  If the current value in the entry is not in the list, then the function of gtk_combo_set_use_arrows() is disabled.

  gtk_combo_set_use_arrows_always() similarly allows the use the the up/down arrow keys to cycle through the choices in the dropdown list, except that it wraps around the values in the list, completely disabling the use of the up and down arrow keys
for changing focus.

  gtk_combo_set_case_sensitive() toggles whether or not GTK searches for entries in a case sensitive manner. This is used when the Combo widget is asked to find a value from the list using the current entry in the text box. This completion can be
performed in either a case sensitive or insensitive manner, depending upon the use of this function. The Combo widget can also simply complete the current entry if the user presses the key combination MOD-1 and "Tab". MOD-1 is often mapped to the
"Alt" key, by the xmodmap utility. Note, however that some window managers also use this key combination, which will override its use within GTK.

  Now that we have a combo box, tailored to look and act how we want it, all that remains is being able to get data from the combo box. This is relatively straightforward. The majority of the time, all you are going to care about getting data from
is the entry. The entry is accessed simply by GTK_ENTRY(GTK_COMBO(combo)->entry). The two principal things that you are going to want to do with it are attach to the activate signal, which indicates that the user has pressed the Return or Enter key,
and read the text. The first is accomplished using something like:


gtk_signal_connect(GTK_OBJECT(GTK_COMB(combo)->entry), "activate",
GTK_SIGNAL_FUNC (my_callback_function), my_data);

  Getting the text at any arbitrary time is accomplished by simply using the entry function:


gchar *gtk_entry_get_text(GtkEntry *entry);

  Such as:


char *string;
string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
That's about all there is to it. There is a function
void gtk_combo_disable_activate(GtkCombo *combo);

   that will disable the activate signal on the entry widget in the combo box. Personally, I can't think of why you'd want to use it, but it does exist.

9.12 Calendar

   The Calendar widget is an effective way to display and retrieve monthly date related information. It is a very simple widget to create and work with.

  Creating a GtkCalendar widget is a simple as:


GtkWidget *gtk_calendar_new();

   There might be times where you need to change a lot of information within this widget and the following functions allow you to make multiple change to a Calendar widget without the user seeing multiple on-screen updates.


void gtk_calendar_freeze( GtkCalendar *Calendar );
void gtk_calendar_thaw( GtkCalendar *Calendar );

  They work just like the freeze/thaw functions of every other widget.

   The Calendar widget has a few options that allow you to change the way the widget both looks and operates by using the function


void gtk_calendar_display_options( GtkCalendar *calendar,
GtkCalendarDisplayOptionsflags );

  The flags argument can be formed by combining either of the following five options using the logical bitwise OR (|) operation:

  GTK_CALENDAR_SHOW_HEADING - this option specifies that the month and year should be shown when drawing the calendar.

  GTK_CALENDAR_SHOW_DAY_NAMES - this option specifies that the three letter descriptions should be displayed for each day (eg MON,TUE...).

  GTK_CALENDAR_NO_MONTH_CHANGE - this option states that the user should not and can not change the currently displayed month. This can be good if you only need to display a particular month such as if you are displaying 12 calendar widgets for
every month in a particular year.

  GTK_CALENDAR_SHOW_WEEK_NUMBERS - this option specifies that the number for each week should be displayed down the left side of the calendar. (eg. Jan 1 = Week 1,Dec 31 = Week 52).

  GTK_CALENDAR_WEEK_START_MONDAY - this option states that the calander week will start on Monday instead of Sunday which is the default. This only affects the order in which days are displayed from left to right.

  The following functions are used to set the the currently displayed date:


gint gtk_calendar_select_month( GtkCalendar *calendar,
guintmonth,guintyear );
void gtk_calendar_select_day( GtkCalendar *calendar,guintday );

  The return value from gtk_calendar_select_month() is a boolean value indicating whether the selection was successful.

  With gtk_calendar_select_day() the specified day number is selected within the current month, if that is possible. A day value of 0 will deselect any current selection.

  In addition to having a day selected, any number of days in the month may be "marked". A marked day is highlighted within the calendar display. The following functions are provided to manipulate marked days:


gint gtk_calendar_mark_day( GtkCalendar *calendar,guintday);
gint gtk_calendar_unmark_day( GtkCalendar *calendar,guintday);
void gtk_calendar_clear_marks( GtkCalendar *calendar);

   The currently marked days are stored within an array within the GtkCalendar structure. This array is 31 elements long so to test whether a particular day is currently marked, you need to access the corresponding element of the array (don't forget
in C that array elements are numbered 0 to n-1). For example:


GtkCalendar *calendar;
calendar = gtk_calendar_new();
...
/* Is day 7 marked? */
if (calendar->marked_date[7-1])
/* day is marked */

  Note that marks are persistent across month and year changes.

  The final Calendar widget function is used to retrieve the currently selected date, month and/or year.


void gtk_calendar_get_date( GtkCalendar *calendar,
guint *year,guint *month,guint *day );

  This function requires you to pass the addresses of guint variables, into which the result will be placed. Passing NULL as a value will result in the corresponding value not being returned.

   The Calendar widget can generate a number of signals indicating date selection and change. The names of these signals are self explanatory, and are:


month_changed
day_selected
day_selected_double_click
prev_month
next_month
prev_year
next_year

  That just leaves us with the need to put all of this together into example code.


/* example-start calendar calendar.c */
/*
* Copyright (C) 1998 Cesar Miquel, Shawn T. Amundson, Mattias Gr?lund
* Copyright (C) 2000 Tony Gale
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include
#include
#include
#include
#define DEF_PAD 10
#define DEF_PAD_SMALL 5
#define TM_YEAR_BASE 1900
typedef struct _CalendarData {
GtkWidget *flag_checkboxes[5];
gbooleansettings[5];
gchar *font;
GtkWidget *font_dialog;
GtkWidget *window;
GtkWidget *prev2_sig;
GtkWidget *prev_sig;
GtkWidget *last_sig;
GtkWidget *month;
} CalendarData;
enum {
calendar_show_header,
calendar_show_days,
calendar_month_change,
calendar_show_week,
calendar_monday_first
};
/*
* GtkCalendar
*/
void calendar_date_to_string( CalendarData *data,
char *buffer,
gintbuff_len )
{
struct tm tm;
time_t time;
memset (&tm, 0, sizeof (tm));
gtk_calendar_get_date (GTK_CALENDAR(data->window),
&tm.tm_year, &tm.tm_mon, &tm.tm_mday);
tm.tm_year -= TM_YEAR_BASE;
time = mktime(&tm);
strftime (buffer, buff_len-1, "%x", gmtime(&time));
}
void calendar_set_signal_strings( char *sig_str,
CalendarData *data)
{
gchar *prev_sig;
gtk_label_get (GTK_LABEL (data->prev_sig), &prev_sig);
gtk_label_set (GTK_LABEL (data->prev2_sig), prev_sig);
gtk_label_get (GTK_LABEL (data->last_sig), &prev_sig);
gtk_label_set (GTK_LABEL (data->prev_sig), prev_sig);
gtk_label_set (GTK_LABEL (data->last_sig), sig_str);
}
void calendar_month_changed( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "month_changed: ";
calendar_date_to_string (data, buffer+15, 256-15);
calendar_set_signal_strings (buffer, data);
}
void calendar_day_selected( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "day_selected: ";
calendar_date_to_string (data, buffer+14, 256-14);
calendar_set_signal_strings (buffer, data);
}
void calendar_day_selected_double_click( GtkWidget*widget,
CalendarData *data )
{
struct tm tm;
char buffer[256] = "day_selected_double_click: ";
calendar_date_to_string (data, buffer+27, 256-27);
calendar_set_signal_strings (buffer, data);
memset (&tm, 0, sizeof (tm));
gtk_calendar_get_date (GTK_CALENDAR(data->window),
&tm.tm_year, &tm.tm_mon, &tm.tm_mday);
tm.tm_year -= TM_YEAR_BASE;
if(GTK_CALENDAR(data->window)->marked_date[tm.tm_mday-1] == 0) {
gtk_calendar_mark_day(GTK_CALENDAR(data->window),tm.tm_mday);
} else {
gtk_calendar_unmark_day(GTK_CALENDAR(data->window),tm.tm_mday);
}
}
void calendar_prev_month( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "prev_month: ";
calendar_date_to_string (data, buffer+12, 256-12);
calendar_set_signal_strings (buffer, data);
}
void calendar_next_month( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "next_month: ";
calendar_date_to_string (data, buffer+12, 256-12);
calendar_set_signal_strings (buffer, data);
}
void calendar_prev_year( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "prev_year: ";
calendar_date_to_string (data, buffer+11, 256-11);
calendar_set_signal_strings (buffer, data);
}
void calendar_next_year( GtkWidget*widget,
CalendarData *data )
{
char buffer[256] = "next_year: ";
calendar_date_to_string (data, buffer+11, 256-11);
calendar_set_signal_strings (buffer, data);
}
void calendar_set_flags( CalendarData *calendar )
{
gint i;
gint options=0;
for (i=0;i<5;i++)
if (calendar->settings)
{
options=options + (1< }
if (calendar->window)
gtk_calendar_display_options (GTK_CALENDAR (calendar->window), options);
}
void calendar_toggle_flag( GtkWidget*toggle,
CalendarData *calendar )
{
gint i;
gint j;
j=0;
for (i=0; i<5; i++)
if (calendar->flag_checkboxes == toggle)
j = i;
calendar->settings[j]=!calendar->settings[j];
calendar_set_flags(calendar);
}
void calendar_font_selection_ok( GtkWidget*button,
CalendarData *calendar )
{
GtkStyle *style;
GdkFont*font;
calendar->font = gtk_font_selection_dialog_get_font_name(
GTK_FONT_SELECTION_DIALOG (calendar->font_dialog));
if (calendar->window)
{
font = gtk_font_selection_dialog_get_font(GTK_FONT_SELECTION_DIALOG
(calendar->font_dialog));
if (font)
{
style = gtk_style_copy (gtk_widget_get_style (calendar->window));
gdk_font_unref (style->font);
style->font = font;
gdk_font_ref (style->font);
gtk_widget_set_style (calendar->window, style);
}
}
}
void calendar_select_font( GtkWidget*button,CalendarData *calendar )
{
GtkWidget *window;
if (!calendar->font_dialog) {
window = gtk_font_selection_dialog_new ("Font Selection Dialog");
g_return_if_fail(GTK_IS_FONT_SELECTION_DIALOG(window));
calendar->font_dialog = window;
gtk_window_position (GTK_WINDOW (window), GTK_WIN_POS_MOUSE);
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_widget_destroyed),
&calendar->font_dialog);
gtk_signal_connect (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG
(window)->ok_button),
"clicked", GTK_SIGNAL_FUNC(calendar_font_selection_ok),
calendar);
gtk_signal_connect_object (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG
(window)->cancel_button),
"clicked",
GTK_SIGNAL_FUNC (gtk_widget_destroy),
GTK_OBJECT (calendar->font_dialog));
}
window=calendar->font_dialog;
if (!GTK_WIDGET_VISIBLE (window))
gtk_widget_show (window);
else
gtk_widget_destroy (window);
}
void create_calendar()
{
GtkWidget *window;
GtkWidget *vbox, *vbox2, *vbox3;
GtkWidget *hbox;
GtkWidget *hbbox;
GtkWidget *calendar;
GtkWidget *toggle;
GtkWidget *button;
GtkWidget *frame;
GtkWidget *separator;
GtkWidget *label;
GtkWidget *bbox;
static CalendarData calendar_data;
gint i;
struct {
char *label;
} flags[] =
{
{ "Show Heading" },
{ "Show Day Names" },
{ "No Month Change" },
{ "Show Week Numbers" },
{ "Week Start Monday" }
};
calendar_data.window = NULL;
calendar_data.font = NULL;
calendar_data.font_dialog = NULL;
for (i=0; i<5; i++) {
calendar_data.settings=0;
}
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "GtkCalendar Example");
gtk_container_border_width (GTK_CONTAINER (window), 5);
gtk_signal_connect(GTK_OBJECT(window), "destroy",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
gtk_signal_connect(GTK_OBJECT(window), "delete-event",
GTK_SIGNAL_FUNC(gtk_false),
NULL);
gtk_window_set_policy(GTK_WINDOW(window), FALSE, FALSE, TRUE);
vbox = gtk_vbox_new(FALSE, DEF_PAD);
gtk_container_add (GTK_CONTAINER (window), vbox);
/*
* The top part of the window, Calendar, flags and fontsel.
*/
hbox = gtk_hbox_new(FALSE, DEF_PAD);
gtk_box_pack_start (GTK_BOX(vbox), hbox, TRUE, TRUE, DEF_PAD);
hbbox = gtk_hbutton_box_new();
gtk_box_pack_start(GTK_BOX(hbox), hbbox, FALSE, FALSE, DEF_PAD);
gtk_button_box_set_layout(GTK_BUTTON_BOX(hbbox), GTK_BUTTONBOX_SPREAD);
gtk_button_box_set_spacing(GTK_BUTTON_BOX(hbbox), 5);
/* Calendar widget */
frame = gtk_frame_new("Calendar");
gtk_box_pack_start(GTK_BOX(hbbox), frame, FALSE, TRUE, DEF_PAD);
calendar=gtk_calendar_new();
calendar_data.window = calendar;
calendar_set_flags(&calendar_data);
gtk_calendar_mark_day ( GTK_CALENDAR(calendar), 19);
gtk_container_add( GTK_CONTAINER( frame), calendar);
gtk_signal_connect (GTK_OBJECT (calendar), "month_changed",
GTK_SIGNAL_FUNC (calendar_month_changed),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "day_selected",
GTK_SIGNAL_FUNC (calendar_day_selected),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "day_selected_double_click",
GTK_SIGNAL_FUNC (calendar_day_selected_double_click),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "prev_month",
GTK_SIGNAL_FUNC (calendar_prev_month),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "next_month",
GTK_SIGNAL_FUNC (calendar_next_month),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "prev_year",
GTK_SIGNAL_FUNC (calendar_prev_year),
&calendar_data);
gtk_signal_connect (GTK_OBJECT (calendar), "next_year",
GTK_SIGNAL_FUNC (calendar_next_year),
&calendar_data);
separator = gtk_vseparator_new ();
gtk_box_pack_start (GTK_BOX (hbox), separator, FALSE, TRUE, 0);
vbox2 = gtk_vbox_new(FALSE, DEF_PAD);
gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, DEF_PAD);
/* Build the Right frame with the flags in */
frame = gtk_frame_new("Flags");
gtk_box_pack_start(GTK_BOX(vbox2), frame, TRUE, TRUE, DEF_PAD);
vbox3 = gtk_vbox_new(TRUE, DEF_PAD_SMALL);
gtk_container_add(GTK_CONTAINER(frame), vbox3);
for (i = 0; i < 5; i++)
{
toggle = gtk_check_button_new_with_label(flags.label);
gtk_signal_connect (GTK_OBJECT (toggle),
"toggled",
GTK_SIGNAL_FUNC(calendar_toggle_flag),
&calendar_data);
gtk_box_pack_start (GTK_BOX (vbox3), toggle, TRUE, TRUE, 0);
calendar_data.flag_checkboxes=toggle;
}
/* Build the right font-button */
button = gtk_button_new_with_label("Font...");
gtk_signal_connect (GTK_OBJECT (button),
"clicked",
GTK_SIGNAL_FUNC(calendar_select_font),
&calendar_data);
gtk_box_pack_start (GTK_BOX (vbox2), button, FALSE, FALSE, 0);
/*
*Build the Signal-event part.
*/
frame = gtk_frame_new("Signal events");
gtk_box_pack_start(GTK_BOX(vbox), frame, TRUE, TRUE, DEF_PAD);
vbox2 = gtk_vbox_new(TRUE, DEF_PAD_SMALL);
gtk_container_add(GTK_CONTAINER(frame), vbox2);
hbox = gtk_hbox_new (FALSE, 3);
gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
label = gtk_label_new ("Signal:");
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
calendar_data.last_sig = gtk_label_new ("");
gtk_box_pack_start (GTK_BOX (hbox), calendar_data.last_sig,
FALSE, TRUE, 0);
hbox = gtk_hbox_new (FALSE, 3);
gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
label = gtk_label_new ("Previous signal:");
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
calendar_data.prev_sig = gtk_label_new ("");
gtk_box_pack_start (GTK_BOX (hbox), calendar_data.prev_sig,
FALSE, TRUE, 0);
hbox = gtk_hbox_new (FALSE, 3);
gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
label = gtk_label_new ("Second previous signal:");
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
calendar_data.prev2_sig = gtk_label_new ("");
gtk_box_pack_start (GTK_BOX (hbox), calendar_data.prev2_sig,
FALSE, TRUE, 0);
bbox = gtk_hbutton_box_new ();
gtk_box_pack_start (GTK_BOX (vbox), bbox, FALSE, FALSE, 0);
gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END);
button = gtk_button_new_with_label ("Close");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (gtk_main_quit),
NULL);
gtk_container_add (GTK_CONTAINER (bbox), button);
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
gtk_widget_grab_default (button);
gtk_widget_show_all(window);
}
int main(int argc,
char *argv[] )
{
gtk_set_locale ();
gtk_init (&argc, &argv);
create_calendar();
gtk_main();
return(0);
}
/* example-end */

9.13 Color Selection

  The color selection widget is, not surprisingly, a widget for interactive selection of colors. This composite widget lets the user select a color by manipulating RGB (Red, Green, Blue) and HSV (Hue, Saturation, Value) triples. This is done either
by adjusting single values with sliders or entries, or by picking the desired color from a hue-saturation wheel/value bar. Optionally, the opacity of the color can also be set.

  The color selection widget currently emits only one signal, "color_changed", which is emitted whenever the current color in the widget changes, either when the user changes it or if it's set explicitly through gtk_color_selection_set_color().

   Lets have a look at what the color selection widget has to offer us. The widget comes in two flavours: gtk_color_selection and gtk_color_selection_dialog.


GtkWidget *gtk_color_selection_new( void );

   You'll probably not be using this constructor directly. It creates an orphan ColorSelection widget which you'll have to parent yourself. The ColorSelection widget inherits from the VBox widget.


GtkWidget *gtk_color_selection_dialog_new( const gchar *title );

   This is the most common color selection constructor. It creates a ColorSelectionDialog. It consists of a Frame containing a ColorSelection widget, an HSeparator and an HBox with three buttons, "Ok", "Cancel" and "Help". You can reach these buttons
by accessing the "ok_button", "cancel_button" and "help_button" widgets in the ColorSelectionDialog structure, (i.e., GTK_COLOR_SELECTION_DIALOG(colorseldialog)->ok_button)).


void gtk_color_selection_set_update_policy( GtkColorSelection *colorsel,
GtkUpdateTypepolicy );

   This function sets the update policy. The default policy is GTK_UPDATE_CONTINUOUS which means that the current color is updated continuously when the user drags the sliders or presses the mouse and drags in the hue-saturation wheel or value bar.
If you experience performance problems, you may want to set the policy to GTK_UPDATE_DISCONTINUOUS or GTK_UPDATE_DELAYED.


void gtk_color_selection_set_opacity( GtkColorSelection *colorsel,
gint use_opacity );

  The color selection widget supports adjusting the opacity of a color (also known as the alpha channel). This is disabled by default. Calling this function with use_opacity set to TRUE enables opacity. Likewise, use_opacity set to FALSE will
disable opacity.


void gtk_color_selection_set_color( GtkColorSelection *colorsel,
gdouble *color );

   You can set the current color explicitly by calling this function with a pointer to an array of colors (gdouble). The length of the array depends on whether opacity is enabled or not. Position 0 contains the red component, 1 is green, 2 is blue
and opacity is at position 3 (only if opacity is enabled, see gtk_color_selection_set_opacity()). All values are between 0.0 and 1.0.


void gtk_color_selection_get_color( GtkColorSelection *colorsel,
gdouble *color );

  When you need to query the current color, typically when you've received a "color_changed" signal, you use this function. Color is a pointer to the array of colors to fill in. See the gtk_color_selection_set_color() function for the description of
this array.

   Here's a simple example demonstrating the use of the ColorSelectionDialog. The program displays a window containing a drawing area. Clicking on it opens a color selection dialog, and changing the color in the color selection dialog changes the
background color.


/* example-start colorsel colorsel.c */
#include
#include
#include
GtkWidget *colorseldlg = NULL;
GtkWidget *drawingarea = NULL;
/* Color changed handler */
void color_changed_cb( GtkWidget *widget,
GtkColorSelection *colorsel )
{
gdouble color[3];
GdkColor gdk_color;
GdkColormap *colormap;
/* Get drawingarea colormap */
colormap = gdk_window_get_colormap (drawingarea->window);
/* Get current color */
gtk_color_selection_get_color (colorsel,color);
/* Fit to a unsigned 16 bit integer (0..65535) and
* insert into the GdkColor structure */
gdk_color.red = (guint16)(color[0]*65535.0);
gdk_color.green = (guint16)(color[1]*65535.0);
gdk_color.blue = (guint16)(color[2]*65535.0);
/* Allocate color */
gdk_color_alloc (colormap, &gdk_color);
/* Set window background color */
gdk_window_set_background (drawingarea->window, &gdk_color);
/* Clear window */
gdk_window_clear (drawingarea->window);
}
/* Drawingarea event handler */
gint area_event( GtkWidget *widget,
GdkEvent*event,
gpointer client_data )
{
gint handled = FALSE;
GtkWidget *colorsel;
/* Check if we've received a button pressed event */
if (event->type == GDK_BUTTON_PRESS && colorseldlg == NULL)
{
/* Yes, we have an event and there's no colorseldlg yet! */
handled = TRUE;
/* Create color selection dialog */
colorseldlg = gtk_color_selection_dialog_new("Select background color");
/* Get the ColorSelection widget */
colorsel = GTK_COLOR_SELECTION_DIALOG(colorseldlg)->colorsel;
/* Connect to the "color_changed" signal, set the client-data
* to the colorsel widget */
gtk_signal_connect(GTK_OBJECT(colorsel), "color_changed",
(GtkSignalFunc)color_changed_cb, (gpointer)colorsel);
/* Show the dialog */
gtk_widget_show(colorseldlg);
}
return handled;
}
/* Close down and exit handler */
gint destroy_window( GtkWidget *widget,
GdkEvent*event,
gpointer client_data )
{
gtk_main_quit ();
return(TRUE);
}
/* Main */
gint main( gint argc,
gchar *argv[] )
{
GtkWidget *window;
/* Initialize the toolkit, remove gtk-related commandline stuff */
gtk_init (&argc,&argv);
/* Create toplevel window, set title and policies */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW(window), "Color selection test");
gtk_window_set_policy (GTK_WINDOW(window), TRUE, TRUE, TRUE);
/* Attach to the "delete" and "destroy" events so we can exit */
gtk_signal_connect (GTK_OBJECT(window), "delete_event",
(GtkSignalFunc)destroy_window, (gpointer)window);
/* Create drawingarea, set size and catch button events */
drawingarea = gtk_drawing_area_new ();
gtk_drawing_area_size (GTK_DRAWING_AREA(drawingarea), 200, 200);
gtk_widget_set_events (drawingarea, GDK_BUTTON_PRESS_MASK);
gtk_signal_connect (GTK_OBJECT(drawingarea), "event",
(GtkSignalFunc)area_event, (gpointer)drawingarea);
/* Add drawingarea to window, then show them both */
gtk_container_add (GTK_CONTAINER(window), drawingarea);
gtk_widget_show (drawingarea);
gtk_widget_show (window);
/* Enter the gtk main loop (this never returns) */
gtk_main ();
/* Satisfy grumpy compilers */
return(0);
}
/* example-end */

9.14 File Selections

   The file selection widget is a quick and simple way to display a File dialog box. It comes complete with Ok, Cancel, and Help buttons, a great way to cut down on programming time.

  To create a new file selection box use:


GtkWidget *gtk_file_selection_new( gchar *title );

  To set the filename, for example to bring up a specific directory, or give a default filename, use this function:


void gtk_file_selection_set_filename( GtkFileSelection *filesel,
gchar*filename );

  To grab the text that the user has entered or clicked on, use this function:


gchar *gtk_file_selection_get_filename( GtkFileSelection *filesel );

  There are also pointers to the widgets contained within the file selection widget. These are:

  dir_list

  file_list

  selection_entry

  selection_text

  main_vbox

  ok_button

  cancel_button

  help_button

  Most likely you will want to use the ok_button, cancel_button, and help_button pointers in signaling their use.

  Included here is an example stolen from testgtk.c, modified to run on its own. As you will see, there is nothing much to creating a file selection widget. While in this example the Help button appears on the screen, it does nothing as there is not
a signal attached to it.


/* example-start filesel filesel.c */
#include
/* Get the selected filename and print it to the console */
void file_ok_sel( GtkWidget*w,GtkFileSelection *fs )
{
g_print ("%s
", gtk_file_selection_get_filename
(GTK_FILE_SELECTION (fs)));
}
void destroy( GtkWidget *widget,
gpointer data )
{
gtk_main_quit ();
}
int main( int argc,
char *argv[] )
{
GtkWidget *filew;
gtk_init (&argc, &argv);
/* Create a new file selection widget */
filew = gtk_file_selection_new ("File selection");
gtk_signal_connect (GTK_OBJECT (filew), "destroy",
(GtkSignalFunc) destroy, &filew);
/* Connect the ok_button to file_ok_sel function */
gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
"clicked", (GtkSignalFunc) file_ok_sel, filew );
/* Connect the cancel_button to destroy the widget */
gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION
(filew)->cancel_button),
"clicked", (GtkSignalFunc) gtk_widget_destroy,
GTK_OBJECT (filew));
/* Lets set the filename, as if this were a save dialog, and we are giving
a default filename */
gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew),
"penguin.png");
gtk_widget_show(filew);
gtk_main ();
return 0;
}
/* example-end */

10. Container Widgets

10.1 The EventBox

  Some GTK widgets don't have associated X windows, so they just draw on their parents. Because of this, they cannot receive events and if they are incorrectly sized, they don't clip so you can get messy overwriting, etc. If you require more from
these widgets, the EventBox is for you.

  At first glance, the EventBox widget might appear to be totally useless. It draws nothing on the screen and responds to no events. However, it does serve a function - it provides an X window for its child widget. This is important as many GTK
widgets do not have an associated X window. Not having an X window saves memory and improves performance, but also has some drawbacks. A widget without an X window cannot receive events, and does not perform any clipping on its contents. Although the
name EventBox emphasizes the event-handling function, the widget can also be used for clipping. (and more, see the example below).

  To create a new EventBox widget, use:


GtkWidget *gtk_event_box_new( void );

  A child widget can then be added to this EventBox:


gtk_container_add( GTK_CONTAINER(event_box), child_widget );

  The following example demonstrates both uses of an EventBox - a label is created that is clipped to a small box, and set up so that a mouse-click on the label causes the program to exit. Resizing the window reveals varying amounts of the label.


/* example-start eventbox eventbox.c */
#include
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *event_box;
GtkWidget *label;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Event Box");
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_exit), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create an EventBox and add it to our toplevel window */
event_box = gtk_event_box_new ();
gtk_container_add (GTK_CONTAINER(window), event_box);
gtk_widget_show (event_box);
/* Create a long label */
label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
gtk_container_add (GTK_CONTAINER (event_box), label);
gtk_widget_show (label);
/* Clip it short. */
gtk_widget_set_usize (label, 110, 20);
/* And bind an action to it */
gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
GTK_SIGNAL_FUNC (gtk_exit), NULL);
/* Yet one more thing you need an X window for ... */
gtk_widget_realize (event_box);
gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
gtk_widget_show (window);
gtk_main ();
return(0);
}
/* example-end */

10.2 The Alignment widget

   The alignment widget allows you to place a widget within its window at a position and size relative to the size of the Alignment widget itself. For example, it can be very useful for centering a widget within the window.

  There are only two functions associated with the Alignment widget:


GtkWidget* gtk_alignment_new( gfloat xalign,
gfloat yalign,gfloat xscale,gfloat yscale );
void gtk_alignment_set( GtkAlignment *alignment,
gfloatxalign,gfloatyalign,gfloatxscale,gfloatyscale );

   The first function creates a new Alignment widget with the specified parameters. The second function allows the alignment paramters of an exisiting Alignment widget to be altered.

   All four alignment parameters are floating point numbers which can range from 0.0 to 1.0. The xalign and yalign arguments affect the position of the widget placed within the Alignment widget. The xscale and yscale arguments effect the amount of
space allocated to the widget.

  A child widget can be added to this Alignment widget using:


gtk_container_add( GTK_CONTAINER(alignment), child_widget );

  For an example of using an Alignment widget, refer to the example for the Progress Bar widget.

10.3 Fixed Container

   The Fixed container allows you to place widgets at a fixed position within it's window, relative to it's upper left hand corner. The position of the widgets can be changed dynamically.

  There are only three functions associated with the fixed widget:


GtkWidget* gtk_fixed_new( void );
void gtk_fixed_put( GtkFixed*fixed,
GtkWidget *widget,gint16 x,gint16 y );
void gtk_fixed_move( GtkFixed*fixed,
GtkWidget *widget,gint16 x,gint16 y );

  The function gtk_fixed_new allows you to create a new Fixed container.

  gtk_fixed_put places widget in the container fixed at the position specified by x and y.

  gtk_fixed_move allows the specified widget to be moved to a new position.

  The following example illustrates how to use the Fixed Container.


/* example-start fixed fixed.c */
#include
/* I'm going to be lazy and use some global variables to
* store the position of the widget within the fixed
* container */
gint x=50;
gint y=50;
/* This callback function moves the button to a new position
* in the Fixed container. */
void move_button( GtkWidget *widget,
GtkWidget *fixed )
{
x = (x+30)%300;
y = (y+50)%300;
gtk_fixed_move( GTK_FIXED(fixed), widget, x, y);
}
int main( int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *fixed;
GtkWidget *button;
gint i;
/* Initialise GTK */
gtk_init(&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Fixed Container");
/* Here we connect the "destroy" event to a signal handler */
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create a Fixed Container */
fixed = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(window), fixed);
gtk_widget_show(fixed);
for (i = 1 ; i <= 3 ; i++) {
/* Creates a new button with the label "Press me" */
button = gtk_button_new_with_label ("Press me");
/* When the button receives the "clicked" signal, it will call the
* function move_button() passing it the Fixed Container as its
* argument. */
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (move_button), fixed);
/* This packs the button into the fixed containers window. */
gtk_fixed_put (GTK_FIXED (fixed), button, i*50, i*50);
/* The final step is to display this newly created widget. */
gtk_widget_show (button);
}
/* Display the window */
gtk_widget_show (window);
/* Enter the event loop */
gtk_main ();
return(0);
}
/* example-end */

10.4 Layout Container

   The Layout container is similar to the Fixed container except that it implements an infinite (where infinity is less than 2^32) scrolling area. The X window system has a limitation where windows can be at most 32767 pixels wide or tall. The Layout
container gets around this limitation by doing some exotic stuff using window and bit gravities, so that you can have smooth scrolling even when you have many child widgets in your scrolling area.

  A Layout container is created using:


GtkWidget *gtk_layout_new( GtkAdjustment *hadjustment,
GtkAdjustment *vadjustment );

  As you can see, you can optionally specify the Adjustment objects that the Layout widget will use for its scrolling.

  You can add and move widgets in the Layout container using the following two functions:


void gtk_layout_put( GtkLayout *layout,
GtkWidget *widget,gint x,gint y );
void gtk_layout_move( GtkLayout *layout,
GtkWidget *widget,gint x,gint y );

  The size of the Layout container can be set using the next function:


void gtk_layout_set_size( GtkLayout *layout,
guintwidth,guintheight );

   Layout containers are one of the very few widgets in the GTK widget set that actively repaint themselves on screen as they are changed using the above functions (the vast majority of widgets queue requests which are then processed when control
returns to the gtk_main() function).

  When you want to make a large number of changes to a Layout container, you can use the following two functions to disable and re-enable this repainting functionality:


void gtk_layout_freeze( GtkLayout *layout );
void gtk_layout_thaw( GtkLayout *layout );

  The final four functions for use with Layout widgets are for manipulating the horizontal and vertical adjustment widgets:


GtkAdjustment* gtk_layout_get_hadjustment( GtkLayout *layout );
GtkAdjustment* gtk_layout_get_vadjustment( GtkLayout *layout );
void gtk_layout_set_hadjustment( GtkLayout *layout,
GtkAdjustment *adjustment );
void gtk_layout_set_vadjustment( GtkLayout *layout,
GtkAdjustment *adjustment);

10.5 Frames

   Frames can be used to enclose one or a group of widgets with a box which can optionally be labelled. The position of the label and the style of the box can be altered to suit.

  A Frame can be created with the following function:


GtkWidget *gtk_frame_new( const gchar *label );

   The label is by default placed in the upper left hand corner of the frame. A value of NULL for the label argument will result in no label being displayed. The text of the label can be changed using the next function.


void gtk_frame_set_label( GtkFrame*frame,const gchar *label );

  The position of the label can be changed using this function:


void gtk_frame_set_label_align( GtkFrame *frame,
gfloatxalign,gfloatyalign );

   xalign and yalign take values between 0.0 and 1.0. xalign indicates the position of the label along the top horizontal of the frame. yalign is not currently used. The default value of xalign is 0.0 which places the label at the left hand end of
the frame.

  The next function alters the style of the box that is used to outline the frame.


void gtk_frame_set_shadow_type( GtkFrame*frame,GtkShadowTypetype);

  The type argument can take one of the following values:

  GTK_SHADOW_NONE

  GTK_SHADOW_IN

  GTK_SHADOW_OUT

  GTK_SHADOW_ETCHED_IN (the default)

  GTK_SHADOW_ETCHED_OUT

  The following code example illustrates the use of the Frame widget.


/* example-start frame frame.c */
#include
int main( int argc,
char *argv[] )
{
/* GtkWidget is the storage type for widgets */
GtkWidget *window;
GtkWidget *frame;
GtkWidget *button;
gint i;
/* Initialise GTK */
gtk_init(&argc, &argv);
/* Create a new window */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Frame Example");
/* Here we connect the "destroy" event to a signal handler */
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
gtk_widget_set_usize(window, 300, 300);
/* Sets the border width of the window. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create a Frame */
frame = gtk_frame_new(NULL);
gtk_container_add(GTK_CONTAINER(window), frame);
/* Set the frame's label */
gtk_frame_set_label( GTK_FRAME(frame), "GTK Frame Widget" );
/* Align the label at the right of the frame */
gtk_frame_set_label_align( GTK_FRAME(frame), 1.0, 0.0);
/* Set the style of the frame */
gtk_frame_set_shadow_type( GTK_FRAME(frame), GTK_SHADOW_ETCHED_OUT);
gtk_widget_show(frame);
/* Display the window */
gtk_widget_show (window);
/* Enter the event loop */
gtk_main ();
return(0);
}
/* example-end */

10.6 Aspect Frames

  The aspect frame widget is like a frame widget, except that it also enforces the aspect ratio (that is, the ratio of the width to the height) of the child widget to have a certain value, adding extra space if necessary. This is useful, for
instance, if you want to preview a larger image. The size of the preview should vary when the user resizes the window, but the aspect ratio needs to always match the original image.

  To create a new aspect frame use:


GtkWidget *gtk_aspect_frame_new( const gchar *label,
gfloat xalign,gfloat yalign,gfloat ratio,gint obey_child);

   xalign and yalign specify alignment as with Alignment widgets. If obey_child is true, the aspect ratio of a child widget will match the aspect ratio of the ideal size it requests. Otherwise, it is given by ratio.

  To change the options of an existing aspect frame, you can use:


void gtk_aspect_frame_set( GtkAspectFrame *aspect_frame,
gfloatxalign,gfloatyalign,gfloatratio,gintobey_child);

  As an example, the following program uses an AspectFrame to present a drawing area whose aspect ratio will always be 2:1, no matter how the user resizes the top-level window.


/* example-start aspectframe aspectframe.c */
#include
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *aspect_frame;
GtkWidget *drawing_area;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Create an aspect_frame and add it to our toplevel window */
aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
0.5, /* center x */
0.5, /* center y */
2, /* xsize/ysize = 2 */
FALSE /* ignore child's aspect */);
gtk_container_add (GTK_CONTAINER(window), aspect_frame);
gtk_widget_show (aspect_frame);
/* Now add a child widget to the aspect frame */
drawing_area = gtk_drawing_area_new ();
/* Ask for a 200x200 window, but the AspectFrame will give us a 200x100
* window since we are forcing a 2x1 aspect ratio */
gtk_widget_set_usize (drawing_area, 200, 200);
gtk_container_add (GTK_CONTAINER(aspect_frame), drawing_area);
gtk_widget_show (drawing_area);
gtk_widget_show (window);
gtk_main ();
return 0;
}
/* example-end */

10.7 Paned Window Widgets

   The paned window widgets are useful when you want to divide an area into two parts, with the relative size of the two parts controlled by the user. A groove is drawn between the two portions with a handle that the user can drag to change the
ratio. The division can either be horizontal (HPaned) or vertical (VPaned).

  To create a new paned window, call one of:


GtkWidget *gtk_hpaned_new (void);
GtkWidget *gtk_vpaned_new (void);

  After creating the paned window widget, you need to add child widgets to its two halves. To do this, use the functions:


void gtk_paned_add1 (GtkPaned *paned, GtkWidget *child);
void gtk_paned_add2 (GtkPaned *paned, GtkWidget *child);

  gtk_paned_add1() adds the child widget to the left or top half of the paned window. gtk_paned_add2() adds the child widget to the right or bottom half of the paned window.

  A paned widget can be changed visually using the following two functions.


void gtk_paned_set_handle_size( GtkPaned *paned,guint16 size);
void gtk_paned_set_gutter_size( GtkPaned *paned,guint16 size);

   The first of these sets the size of the handle and the second sets the size of the gutter that is between the two parts of the paned window.

  As an example, we will create part of the user interface of an imaginary email program. A window is divided into two portions vertically, with the top portion being a list of email messages and the bottom portion the text of the email message.
Most of the program is pretty straightforward. A couple of points to note: text can't be added to a Text widget until it is realized. This could be done by calling gtk_widget_realize(), but as a demonstration of an alternate technique, we connect a
handler to the "realize" signal to add the text. Also, we need to add the GTK_SHRINK option to some of the items in the table containing the text window and its scrollbars, so that when the bottom portion is made smaller, the correct portions shrink
instead of being pushed off the bottom of the window.


/* example-start paned paned.c */
#include
#include
/* Create the list of "messages" */
GtkWidget *create_list( void )
{
GtkWidget *scrolled_window;
GtkWidget *list;
GtkWidget *list_item;
int i;
char buffer[16];
/* Create a new scrolled window, with scrollbars only if needed */
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
/* Create a new list and put it in the scrolled window */
list = gtk_list_new ();
gtk_scrolled_window_add_with_viewport (
GTK_SCROLLED_WINDOW (scrolled_window), list);
gtk_widget_show (list);
/* Add some messages to the window */
for (i=0; i<10; i++) {
sprintf(buffer,"Message #%d",i);
list_item = gtk_list_item_new_with_label (buffer);
gtk_container_add (GTK_CONTAINER(list), list_item);
gtk_widget_show (list_item);
}
return scrolled_window;
}
/* Add some text to our text widget - this is a callback that is invoked
when our window is realized. We could also force our window to be
realized with gtk_widget_realize, but it would have to be part of
a hierarchy first */
void realize_text( GtkWidget *text,gpointer data )
{
gtk_text_freeze (GTK_TEXT (text));
gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
"From: pathfinder@nasa.gov
"
"To: mom@nasa.gov
"
"Subject: Made it!
"
"
"
"We just got in this morning. The weather has been
"
"great - clear but cold, and there are lots of fun sights.
"
"Sojourner says hi. See you soon.
"
" -Path
", -1);
gtk_text_thaw (GTK_TEXT (text));
}
/* Create a scrolled text area that displays a "message" */
GtkWidget *create_text( void )
{
GtkWidget *table;
GtkWidget *text;
GtkWidget *hscrollbar;
GtkWidget *vscrollbar;
/* Create a table to hold the text widget and scrollbars */
table = gtk_table_new (2, 2, FALSE);
/* Put a text widget in the upper left hand corner. Note the use of
* GTK_SHRINK in the y direction */
text = gtk_text_new (NULL, NULL);
gtk_table_attach (GTK_TABLE (table), text, 0, 1, 0, 1,
GTK_FILL | GTK_EXPAND,
GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 0);
gtk_widget_show (text);
/* Put a HScrollbar in the lower left hand corner */
hscrollbar = gtk_hscrollbar_new (GTK_TEXT (text)->hadj);
gtk_table_attach (GTK_TABLE (table), hscrollbar, 0, 1, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_widget_show (hscrollbar);
/* And a VScrollbar in the upper right */
vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
gtk_table_attach (GTK_TABLE (table), vscrollbar, 1, 2, 0, 1,
GTK_FILL, GTK_EXPAND | GTK_FILL | GTK_SHRINK, 0, 0);
gtk_widget_show (vscrollbar);
/* Add a handler to put a message in the text widget when it is realized */
gtk_signal_connect (GTK_OBJECT (text), "realize",
GTK_SIGNAL_FUNC (realize_text), NULL);
return table;
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *vpaned;
GtkWidget *list;
GtkWidget *text;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Paned Windows");
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_widget_set_usize (GTK_WIDGET(window), 450, 400);
/* create a vpaned widget and add it to our toplevel window */
vpaned = gtk_vpaned_new ();
gtk_container_add (GTK_CONTAINER(window), vpaned);
gtk_paned_set_handle_size (GTK_PANED(vpaned),
10);
gtk_paned_set_gutter_size (GTK_PANED(vpaned),
15);
gtk_widget_show (vpaned);
/* Now create the contents of the two halves of the window */
list = create_list ();
gtk_paned_add1 (GTK_PANED(vpaned), list);
gtk_widget_show (list);
text = create_text ();
gtk_paned_add2 (GTK_PANED(vpaned), text);
gtk_widget_show (text);
gtk_widget_show (window);
gtk_main ();
return 0;
}
/* example-end */

10.8 Viewports

   It is unlikely that you will ever need to use the Viewport widget directly. You are much more likely to use the Scrolled Window widget which itself uses the Viewport.

   A viewport widget allows you to place a larger widget within it such that you can view a part of it at a time. It uses Adjustments to define the area that is currently in view.

  A Viewport is created with the function


GtkWidget *gtk_viewport_new( GtkAdjustment *hadjustment,
GtkAdjustment *vadjustment );

   As you can see you can specify the horizontal and vertical Adjustments that the widget is to use when you create the widget. It will create its own if you pass NULL as the value of the arguments.

  You can get and set the adjustments after the widget has been created using the following four functions:


GtkAdjustment *gtk_viewport_get_hadjustment (GtkViewport *viewport );
GtkAdjustment *gtk_viewport_get_vadjustment (GtkViewport *viewport );
void gtk_viewport_set_hadjustment( GtkViewport *viewport,
GtkAdjustment *adjustment );
void gtk_viewport_set_vadjustment( GtkViewport *viewport,
GtkAdjustment *adjustment );

  The only other viewport function is used to alter its appearance:


void gtk_viewport_set_shadow_type( GtkViewport *viewport,
GtkShadowTypetype );

  Possible values for the type parameter are:

  GTK_SHADOW_NONE,

  GTK_SHADOW_IN,

  GTK_SHADOW_OUT,

  GTK_SHADOW_ETCHED_IN,

  GTK_SHADOW_ETCHED_OUT

10.9 Scrolled Windows

   Scrolled windows are used to create a scrollable area with another widget inside it. You may insert any type of widget into a scrolled window, and it will be accessible regardless of the size by using the scrollbars.

  The following function is used to create a new scrolled window.


GtkWidget *gtk_scrolled_window_new( GtkAdjustment *hadjustment,
GtkAdjustment *vadjustment );

   Where the first argument is the adjustment for the horizontal direction, and the second, the adjustment for the vertical direction. These are almost always set to NULL.


void gtk_scrolled_window_set_policy( GtkScrolledWindow *scrolled_window,
GtkPolicyTypehscrollbar_policy,GtkPolicyTypevscrollbar_policy );

   This sets the policy to be used with respect to the scrollbars. The first argument is the scrolled window you wish to change. The second sets the policy for the horizontal scrollbar, and the third the policy for the vertical scrollbar.

   The policy may be one of GTK_POLICY_AUTOMATIC or GTK_POLICY_ALWAYS. GTK_POLICY_AUTOMATIC will automatically decide whether you need scrollbars, whereas GTK_POLICY_ALWAYS will always leave the scrollbars there.

  You can then place your object into the scrolled window using the following function.


void gtk_scrolled_window_add_with_viewport(GtkScrolledWindow
*scrolled_window,GtkWidget *child);

   Here is a simple example that packs a table eith 100 toggle buttons into a scrolled window. I've only commented on the parts that may be new to you.


/* example-start scrolledwin scrolledwin.c */
#include
#include
void destroy( GtkWidget *widget,
gpointer data )
{
gtk_main_quit();
}
int main( int argc,
char *argv[] )
{
static GtkWidget *window;
GtkWidget *scrolled_window;
GtkWidget *table;
GtkWidget *button;
char buffer[32];
int i, j;
gtk_init (&argc, &argv);
/* Create a new dialog window for the scrolled window to be
* packed into.*/
window = gtk_dialog_new ();
gtk_signal_connect (GTK_OBJECT (window), "destroy",
(GtkSignalFunc) destroy, NULL);
gtk_window_set_title (GTK_WINDOW (window), "GtkScrolledWindow example");
gtk_container_set_border_width (GTK_CONTAINER (window), 0);
gtk_widget_set_usize(window, 300, 300);
/* create a new scrolled window. */
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_container_set_border_width (GTK_CONTAINER (scrolled_window), 10);
/* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
* GTK_POLICY_AUTOMATIC will automatically decide whether you need
* scrollbars, whereas GTK_POLICY_ALWAYS will always leave the scrollbars
* there.The first one is the horizontal scrollbar, the second,
* the vertical. */
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
/* The dialog window is created with a vbox packed into it. */
gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window,
TRUE, TRUE, 0);
gtk_widget_show (scrolled_window);
/* create a table of 10 by 10 squares. */
table = gtk_table_new (10, 10, FALSE);
/* set the spacing to 10 on x and 10 on y */
gtk_table_set_row_spacings (GTK_TABLE (table), 10);
gtk_table_set_col_spacings (GTK_TABLE (table), 10);
/* pack the table into the scrolled window */
gtk_scrolled_window_add_with_viewport (
GTK_SCROLLED_WINDOW (scrolled_window), table);
gtk_widget_show (table);
/* this simply creates a grid of toggle buttons on the table
* to demonstrate the scrolled window. */
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++) {
sprintf (buffer, "button (%d,%d)
", i, j);
button = gtk_toggle_button_new_with_label (buffer);
gtk_table_attach_defaults (GTK_TABLE (table), button,
i, i+1, j, j+1);
gtk_widget_show (button);
}
/* Add a "close" button to the bottom of the dialog */
button = gtk_button_new_with_label ("close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) gtk_widget_destroy,GTK_OBJECT (window));
/* this makes it so the button is the default. */
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area),
button, TRUE, TRUE, 0);
/* This grabs this button to be the default button. Simply hitting
* the "Enter" key will cause this button to activate. */
gtk_widget_grab_default (button);
gtk_widget_show (button);
gtk_widget_show (window);
gtk_main();
return(0);
}
/* example-end */

   Try playing with resizing the window. You'll notice how the scrollbars react. You may also wish to use the gtk_widget_set_usize() call to set the default size of the window or other widgets.

10.10 Button Boxes

   Button Boxes are a convenient way to quickly layout a group of buttons. They come in both horizontal and vertical flavours. You create a new Button Box with one of the following calls, which create a horizontal or vertical box, respectively:


GtkWidget *gtk_hbutton_box_new( void );
GtkWidget *gtk_vbutton_box_new( void );

   The only attributes pertaining to button boxes effect how the buttons are laid out. You can change the spacing between the buttons with:


void gtk_hbutton_box_set_spacing_default( gint spacing );
void gtk_vbutton_box_set_spacing_default( gint spacing );

  Similarly, the current spacing values can be queried using:


gint gtk_hbutton_box_get_spacing_default( void );
gint gtk_vbutton_box_get_spacing_default( void );

  The second attribute that we can access effects the layout of the buttons within the box. It is set using one of:


void gtk_hbutton_box_set_layout_default( GtkButtonBoxStyle layout );
void gtk_vbutton_box_set_layout_default( GtkButtonBoxStyle layout );

  The layout argument can take one of the following values:

  GTK_BUTTONBOX_DEFAULT_STYLE

  GTK_BUTTONBOX_SPREAD

  GTK_BUTTONBOX_EDGE

  GTK_BUTTONBOX_START

  GTK_BUTTONBOX_END

  The current layout setting can be retrieved using:


GtkButtonBoxStyle gtk_hbutton_box_get_layout_default( void );
GtkButtonBoxStyle gtk_vbutton_box_get_layout_default( void );

  Buttons are added to a Button Box using the usual function:


gtk_container_add( GTK_CONTAINER(button_box), child_widget );

  Here's an example that illustrates all the different layout settings for Button Boxes.


/* example-start buttonbox buttonbox.c */
#include
/* Create a Button Box with the specified parameters */
GtkWidget *create_bbox( ginthorizontal,
char *title,
gintspacing,
gintchild_w,
gintchild_h,
gintlayout )
{
GtkWidget *frame;
GtkWidget *bbox;
GtkWidget *button;
frame = gtk_frame_new (title);
if (horizontal)
bbox = gtk_hbutton_box_new ();
else
bbox = gtk_vbutton_box_new ();
gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
gtk_container_add (GTK_CONTAINER (frame), bbox);
/* Set the appearance of the Button Box */
gtk_button_box_set_layout (GTK_BUTTON_BOX (bbox), layout);
gtk_button_box_set_spacing (GTK_BUTTON_BOX (bbox), spacing);
gtk_button_box_set_child_size (GTK_BUTTON_BOX (bbox),
child_w, child_h);
button = gtk_button_new_with_label ("OK");
gtk_container_add (GTK_CONTAINER (bbox), button);
button = gtk_button_new_with_label ("Cancel");
gtk_container_add (GTK_CONTAINER (bbox), button);
button = gtk_button_new_with_label ("Help");
gtk_container_add (GTK_CONTAINER (bbox), button);
return(frame);
}
int main( int argc,
char *argv[] )
{
static GtkWidget* window = NULL;
GtkWidget *main_vbox;
GtkWidget *vbox;
GtkWidget *hbox;
GtkWidget *frame_horz;
GtkWidget *frame_vert;
/* Initialize GTK */
gtk_init( &argc, &argv );
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Button Boxes");
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
main_vbox = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), main_vbox);
frame_horz = gtk_frame_new ("Horizontal Button Boxes");
gtk_box_pack_start (GTK_BOX (main_vbox), frame_horz, TRUE, TRUE, 10);
vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
gtk_container_add (GTK_CONTAINER (frame_horz), vbox);
gtk_box_pack_start (GTK_BOX (vbox),
create_bbox (TRUE, "Spread (spacing 40)", 40, 85, 20,
GTK_BUTTONBOX_SPREAD),
TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (vbox),
create_bbox (TRUE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
TRUE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (vbox),
create_bbox (TRUE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
TRUE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (vbox),
create_bbox (TRUE, "End (spacing 10)", 10, 85, 20, GTK_BUTTONBOX_END),
TRUE, TRUE, 5);
frame_vert = gtk_frame_new ("Vertical Button Boxes");
gtk_box_pack_start (GTK_BOX (main_vbox), frame_vert, TRUE, TRUE, 10);
hbox = gtk_hbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (hbox), 10);
gtk_container_add (GTK_CONTAINER (frame_vert), hbox);
gtk_box_pack_start (GTK_BOX (hbox),
create_bbox (FALSE, "Spread (spacing 5)", 5, 85, 20, GTK_BUTTONBOX_SPREAD),
TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox),
create_bbox (FALSE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
TRUE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (hbox),
create_bbox (FALSE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
TRUE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (hbox),
create_bbox (FALSE, "End (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_END),
TRUE, TRUE, 5);
gtk_widget_show_all (window);
/* Enter the event loop */
gtk_main ();
return(0);
}
/* example-end */

10.11 Toolbar

   Toolbars are usually used to group some number of widgets in order to simplify customization of their look and layout. Typically a toolbar consists of buttons with icons, labels and tooltips, but any other widget can also be put inside a toolbar.
Finally, items can be arranged horizontally or vertically and buttons can be displayed with icons, labels, or both.

  Creating a toolbar is (as one may already suspect) done with the following function:


GtkWidget *gtk_toolbar_new( GtkOrientation orientation,
GtkToolbarStylestyle );

  where orientation may be one of:

  GTK_ORIENTATION_HORIZONTAL

  GTK_ORIENTATION_VERTICAL

  and style one of:

  GTK_TOOLBAR_TEXT

  GTK_TOOLBAR_ICONS

  GTK_TOOLBAR_BOTH

   The style applies to all the buttons created with the `item' functions (not to buttons inserted into toolbar as separate widgets).

  After creating a toolbar one can append, prepend and insert items (that means simple text strings) or elements (that means any widget types) into the toolbar. To describe an item we need a label text, a tooltip text, a private tooltip text, an
icon for the button and a callback function for it. For example, to append or prepend an item you may use the following functions:


GtkWidget *gtk_toolbar_append_item( GtkToolbar*toolbar,
const char*text,const char*tooltip_text,const char*tooltip_private_text,
GtkWidget *icon,GtkSignalFunccallback,gpointer user_data );
GtkWidget *gtk_toolbar_prepend_item( GtkToolbar*toolbar,
const char*text,const char*tooltip_text,const char*tooltip_private_text,
GtkWidget *icon,GtkSignalFunccallback,gpointer user_data );

  If you want to use gtk_toolbar_insert_item, the only additional parameter which must be specified is the position in which the item should be inserted, thus:


GtkWidget *gtk_toolbar_insert_item( GtkToolbar*toolbar,const char*text,
const char*tooltip_text,const char*tooltip_private_text,GtkWidget *icon,
GtkSignalFunccallback,gpointer user_data,gint position );

  To simplify adding spaces between toolbar items, you may use the following functions:


void gtk_toolbar_append_space( GtkToolbar *toolbar );
void gtk_toolbar_prepend_space( GtkToolbar *toolbar );
void gtk_toolbar_insert_space( GtkToolbar *toolbar,gintposition );

  While the size of the added space can be set globally for a whole toolbar with the function:


void gtk_toolbar_set_space_size( GtkToolbar *toolbar,gintspace_size) ;

  If it's required, the orientation of a toolbar and its style can be changed "on the fly" using the following functions:


void gtk_toolbar_set_orientation( GtkToolbar *toolbar,
GtkOrientationorientation );
void gtk_toolbar_set_style( GtkToolbar*toolbar,
GtkToolbarStylestyle );
void gtk_toolbar_set_tooltips( GtkToolbar *toolbar,gintenable );

   Where orientation is one of GTK_ORIENTATION_HORIZONTAL or GTK_ORIENTATION_VERTICAL. The style is used to set appearance of the toolbar items by using one of GTK_TOOLBAR_ICONS, GTK_TOOLBAR_TEXT, or GTK_TOOLBAR_BOTH.

  To show some other things that can be done with a toolbar, let's take the following program (we'll interrupt the listing with some additional explanations):


#include
#include "gtk.xpm"
/* This function is connected to the Close button or
* closing the window from the WM */
gint delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
{
gtk_main_quit ();
return(FALSE);
}

   The above beginning seems for sure familiar to you if it's not your first GTK program. There is one additional thing though, we include a nice XPM picture to serve as an icon for all of the buttons.


GtkWidget* close_button; /* This button will emit signal to close
* application */
GtkWidget* tooltips_button; /* to enable/disable tooltips */
GtkWidget* text_button,
* icon_button,
* both_button; /* radio buttons for toolbar style */
GtkWidget* entry; /* a text entry to show packing any widget into
* toolbar */

  In fact not all of the above widgets are needed here, but to make things clearer I put them all together.


/* that's easy... when one of the buttons is toggled, we just
* check which one is active and set the style of the toolbar
* accordingly
* ATTENTION: our toolbar is passed as data to callback ! */
void radio_event (GtkWidget *widget, gpointer data)
{
if (GTK_TOGGLE_BUTTON (text_button)->active)
gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_TEXT);
else if (GTK_TOGGLE_BUTTON (icon_button)->active)
gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_ICONS);
else if (GTK_TOGGLE_BUTTON (both_button)->active)
gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_BOTH);
}
/* even easier, just check given toggle button and enable/disable
* tooltips */
void toggle_event (GtkWidget *widget, gpointer data)
{
gtk_toolbar_set_tooltips (GTK_TOOLBAR ( data ),
GTK_TOGGLE_BUTTON (widget)->active );
}

   The above are just two callback functions that will be called when one of the buttons on a toolbar is pressed. You should already be familiar with things like this if you've already used toggle buttons (and radio buttons).


int main (int argc, char *argv[])
{
/* Here is our main window (a dialog) and a handle for the handlebox */
GtkWidget* dialog;
GtkWidget* handlebox;
/* Ok, we need a toolbar, an icon with a mask (one for all of
the buttons) and an icon widget to put this icon in (but
we'll create a separate widget for each button) */
GtkWidget * toolbar;
GdkPixmap * icon;
GdkBitmap * mask;
GtkWidget * iconw;
/* this is called in all GTK application. */
gtk_init (&argc, &argv);
/* create a new window with a given title, and nice size */
dialog = gtk_dialog_new ();
gtk_window_set_title ( GTK_WINDOW ( dialog ) , "GTKToolbar Tutorial");
gtk_widget_set_usize( GTK_WIDGET ( dialog ) , 600 , 300 );
GTK_WINDOW ( dialog ) ->allow_shrink = TRUE;
/* typically we quit if someone tries to close us */
gtk_signal_connect ( GTK_OBJECT ( dialog ), "delete_event",
GTK_SIGNAL_FUNC ( delete_event ), NULL);
/* we need to realize the window because we use pixmaps for
* items on the toolbar in the context of it */
gtk_widget_realize ( dialog );
/* to make it nice we'll put the toolbar into the handle box,
* so that it can be detached from the main window */
handlebox = gtk_handle_box_new ();
gtk_box_pack_start ( GTK_BOX ( GTK_DIALOG(dialog)->vbox ),
handlebox, FALSE, FALSE, 5 );


   The above should be similar to any other GTK application. Just initialization of GTK, creating the window, etc. There is only one thing that probably needs some explanation: a handle box. A handle box is just another box that can be used to pack
widgets in to. The difference between it and typical boxes is that it can be detached from a parent window (or, in fact, the handle box remains in the parent, but it is reduced to a very small rectangle, while all of its contents are reparented to a
new freely floating window). It is usually nice to have a detachable toolbar, so these two widgets occur together quite often.


/* toolbar will be horizontal, with both icons and text, and
* with 5pxl spaces between items and finally,
* we'll also put it into our handlebox */
toolbar = gtk_toolbar_new ( GTK_ORIENTATION_HORIZONTAL,GTK_TOOLBAR_BOTH );
gtk_container_set_border_width ( GTK_CONTAINER ( toolbar ) , 5 );
gtk_toolbar_set_space_size ( GTK_TOOLBAR ( toolbar ), 5 );
gtk_container_add ( GTK_CONTAINER ( handlebox ) , toolbar );
/* now we create icon with mask: we'll reuse it to create
* icon widgets for toolbar items */
icon = gdk_pixmap_create_from_xpm_d ( dialog->window, &mask,
&dialog->style->white, gtk_xpm );

  Well, what we do above is just a straightforward initialization of the toolbar widget and creation of a GDK pixmap with its mask. If you want to know something more about using pixmaps, refer to GDK documentation or to the Pixmaps section earlier
in this tutorial.


/* our first item is button */
iconw = gtk_pixmap_new ( icon, mask ); /* icon widget */
close_button =
gtk_toolbar_append_item ( GTK_TOOLBAR (toolbar), /* our toolbar */
"Close", /* button label */
"Closes this app", /* this button's tooltip */
"Private", /* tooltip private info */
iconw, /* icon widget */
GTK_SIGNAL_FUNC (delete_event), /* a signal */
NULL );
gtk_toolbar_append_space (GTK_TOOLBAR(toolbar)); /* space after item */

  In the above code you see the simplest case: adding a button to toolbar. Just before appending a new item, we have to construct a pixmap widget to serve as an icon for this item; this step will have to be repeated for each new item. Just after the
item we also add a space, so the following items will not touch each other. As you see gtk_toolbar_append_item returns a pointer to our newly created button widget, so that we can work with it in the normal way.


/* now, let's make our radio buttons group... */
iconw = gtk_pixmap_new ( icon, mask );
icon_button = gtk_toolbar_append_element(
GTK_TOOLBAR(toolbar),
GTK_TOOLBAR_CHILD_RADIOBUTTON, /* a type of element */
NULL,/* pointer to widget */
"Icon",/* label */
"Only icons in toolbar", /* tooltip */
"Private", /* tooltip private string */
iconw, /* icon */
GTK_SIGNAL_FUNC (radio_event), /* signal */
toolbar);/* data for signal */
gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );

   Here we begin creating a radio buttons group. To do this we use gtk_toolbar_append_element. In fact, using this function one can also +add simple items or even spaces (type = GTK_TOOLBAR_CHILD_SPACE or +GTK_TOOLBAR_CHILD_BUTTON). In the above case
we start creating a radio group. In creating other radio buttons for this group a pointer to the previous button in the group is required, so that a list of buttons can be easily constructed (see the section on Radio Buttons earlier in this tutorial).


/* following radio buttons refer to previous ones */
iconw = gtk_pixmap_new ( icon, mask );
text_button =
gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
GTK_TOOLBAR_CHILD_RADIOBUTTON,
icon_button,
"Text",
"Only texts in toolbar",
"Private",
iconw,
GTK_SIGNAL_FUNC (radio_event),
toolbar);
gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
iconw = gtk_pixmap_new ( icon, mask );
both_button =
gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
GTK_TOOLBAR_CHILD_RADIOBUTTON,
text_button,
"Both",
"Icons and text in toolbar",
"Private",
iconw,
GTK_SIGNAL_FUNC (radio_event),
toolbar);
gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(both_button),TRUE);

  In the end we have to set the state of one of the buttons manually (otherwise they all stay in active state, preventing us from switching between them).


/* here we have just a simple toggle button */
iconw = gtk_pixmap_new ( icon, mask );
tooltips_button =
gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
GTK_TOOLBAR_CHILD_TOGGLEBUTTON,
NULL,
"Tooltips",
"Toolbar with or without tips",
"Private",
iconw,
GTK_SIGNAL_FUNC (toggle_event),
toolbar);
gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(tooltips_button),TRUE);

  A toggle button can be created in the obvious way (if one knows how to create radio buttons already).


/* to pack a widget into toolbar, we only have to
* create it and append it with an appropriate tooltip */
entry = gtk_entry_new ();
gtk_toolbar_append_widget( GTK_TOOLBAR (toolbar),
entry,
"This is just an entry",
"Private" );
/* well, it isn't created within thetoolbar, so we must still show it */
gtk_widget_show ( entry );

  As you see, adding any kind of widget to a toolbar is simple. The one thing you have to remember is that this widget must be shown manually (contrary to other items which will be shown together with the toolbar).


/* that's it ! let's show everything. */
gtk_widget_show ( toolbar );
gtk_widget_show (handlebox);
gtk_widget_show ( dialog );
/* rest in gtk_main and wait for the fun to begin! */
gtk_main ();
return 0;
}

  So, here we are at the end of toolbar tutorial. Of course, to appreciate it in full you need also this nice XPM icon, so here it is:


/* XPM */
static char * gtk_xpm[] = {
"32 39 5 1",
".c none",
"+c black",
"@c #3070E0",
"#c #F05050",
"$c #35E035",
"................+...............",
"..............+++++.............",
"............+++++@@++...........",
"..........+++++@@@@@@++.........",
"........++++@@@@@@@@@@++........",
"......++++@@++++++++@@@++.......",
".....+++@@@+++++++++++@@@++.....",
"...+++@@@@+++@@@@@@++++@@@@+....",
"..+++@@@@+++@@@@@@@@+++@@@@@++..",
".++@@@@@@+++@@@@@@@@@@@@@@@@@@++",
".+#+@@@@@@++@@@@+++@@@@@@@@@@@@+",
".+##++@@@@+++@@@+++++@@@@@@@@$@.",
".+###++@@@@+++@@@+++@@@@@++$$$@.",
".+####+++@@@+++++++@@@@@+@$$$$@.",
".+#####+++@@@@+++@@@@++@$$$$$$+.",
".+######++++@@@@@@@++@$$$$$$$$+.",
".+#######+##+@@@@+++$$$$$$@@$$+.",
".+###+++##+##+@@++@$$$$$$++$$$+.",
".+###++++##+##+@@$$$$$$$@+@$$@+.",
".+###++++++#+++@$$@+@$$@++$$$@+.",
".+####+++++++#++$$@+@$$++$$$$+..",
".++####++++++#++$$@+@$++@$$$$+..",
".+#####+++++##++$$++@+++$$$$$+..",
".++####+++##+#++$$+++++@$$$$$+..",
".++####+++####++$$++++++@$$$@+..",
".+#####++#####++$$+++@++++@$@+..",
".+#####++#####++$$++@$$@+++$@@..",
".++####++#####++$$++$$$$$+@$@++.",
".++####++#####++$$++$$$$$$$$+++.",
".+++####+#####++$$++$$$$$$$@+++.",
"..+++#########+@$$+@$$$$$$+++...",
"...+++########+@$$$$$$$$@+++....",
".....+++######+@$$$$$$$+++......",
"......+++#####+@$$$$$@++........",
".......+++####+@$$$$+++.........",
".........++###+$$$@++...........",
"..........++##+$@+++............",
"...........+++++++..............",
".............++++..............."};

10.12 Notebooks

   The NoteBook Widget is a collection of "pages" that overlap each other, each page contains different information with only one page visible at a time. This widget has become more common lately in GUI programming, and it is a good way to show
blocks of similar information that warrant separation in their display.

  The first function call you will need to know, as you can probably guess by now, is used to create a new notebook widget.


GtkWidget *gtk_notebook_new( void );

  Once the notebook has been created, there are a number of functions that operate on the notebook widget. Let's look at them individually.

   The first one we will look at is how to position the page indicators. These page indicators or "tabs" as they are referred to, can be positioned in four ways: top, bottom, left, or right.


void gtk_notebook_set_tab_pos( GtkNotebook *notebook,
GtkPositionTypepos );

  GtkPositionType will be one of the following, which are pretty self explanatory:

  GTK_POS_LEFT

  GTK_POS_RIGHT

  GTK_POS_TOP

  GTK_POS_BOTTOM

  GTK_POS_TOP is the default.

   Next we will look at how to add pages to the notebook. There are three ways to add pages to the NoteBook. Let's look at the first two together as they are quite similar.


void gtk_notebook_append_page( GtkNotebook *notebook,
GtkWidget *child,GtkWidget *tab_label );
void gtk_notebook_prepend_page( GtkNotebook *notebook,
GtkWidget *child,GtkWidget *tab_label );

   These functions add pages to the notebook by inserting them from the back of the notebook (append), or the front of the notebook (prepend). child is the widget that is placed within the notebook page, and tab_label is the label for the page being
added. The child widget must be created separately, and is typically a set of options setup witin one of the other container widgets, such as a table.

   The final function for adding a page to the notebook contains all of the properties of the previous two, but it allows you to specify what position you want the page to be in the notebook.


void gtk_notebook_insert_page( GtkNotebook *notebook,
GtkWidget *child,GtkWidget *tab_label,gint position );

   The parameters are the same as _append_ and _prepend_ except it contains an extra parameter, position. This parameter is used to specify what place this page will be inserted into the first page having position zero.

  Now that we know how to add a page, lets see how we can remove a page from the notebook.


void gtk_notebook_remove_page( GtkNotebook *notebook,gint page_num );

  This function takes the page specified by page_num and removes it from the widget pointed to by notebook.

  To find out what the current page is in a notebook use the function:


gint gtk_notebook_get_current_page( GtkNotebook *notebook );

   These next two functions are simple calls to move the notebook page forward or backward. Simply provide the respective function call with the notebook widget you wish to operate on. Note: When the NoteBook is currently on the last page, and
gtk_notebook_next_page is called, the notebook will wrap back to the first page. Likewise, if the NoteBook is on the first page, and gtk_notebook_prev_page is called, the notebook will wrap to the last page.


void gtk_notebook_next_page( GtkNoteBook *notebook );
void gtk_notebook_prev_page( GtkNoteBook *notebook );

   This next function sets the "active" page. If you wish the notebook to be opened to page 5 for example, you would use this function. Without using this function, the notebook defaults to the first page.


void gtk_notebook_set_page( GtkNotebook *notebook,gint page_num );

  The next two functions add or remove the notebook page tabs and the notebook border respectively.


void gtk_notebook_set_show_tabs( GtkNotebook *notebook,
gboolean show_tabs);
void gtk_notebook_set_show_border( GtkNotebook *notebook,
gboolean show_border );

  The next function is useful when the you have a large number of pages, and the tabs don't fit on the page. It allows the tabs to be scrolled through using two arrow buttons.


void gtk_notebook_set_scrollable( GtkNotebook *notebook,
gboolean scrollable );

  show_tabs, show_border and scrollable can be either TRUE or FALSE.

  Now let's look at an example, it is expanded from the testgtk.c code that comes with the GTK distribution. This small program creates a window with a notebook and six buttons. The notebook contains 11 pages, added in three different ways,
appended, inserted, and prepended. The buttons allow you rotate the tab positions, add/remove the tabs and border, remove a page, change pages in both a forward and backward manner, and exit the program.


/* example-start notebook notebook.c */
#include
#include
/* This function rotates the position of the tabs */
void rotate_book( GtkButton *button,GtkNotebook *notebook )
{
gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
}
/* Add/Remove the page tabs and the borders */
void tabsborder_book( GtkButton *button,GtkNotebook *notebook )
{
gint tval = FALSE;
gint bval = FALSE;
if (notebook->show_tabs == 0)
tval = TRUE;
if (notebook->show_border == 0)
bval = TRUE;
gtk_notebook_set_show_tabs (notebook, tval);
gtk_notebook_set_show_border (notebook, bval);
}
/* Remove a page from the notebook */
void remove_book( GtkButton *button,
GtkNotebook *notebook )
{
gint page;
page = gtk_notebook_get_current_page(notebook);
gtk_notebook_remove_page (notebook, page);
/* Need to refresh the widget --
This forces the widget to redraw itself. */
gtk_widget_draw(GTK_WIDGET(notebook), NULL);
}
gint delete( GtkWidget *widget,GtkWidget *event,gpointer data )
{
gtk_main_quit();
return(FALSE);
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *button;
GtkWidget *table;
GtkWidget *notebook;
GtkWidget *frame;
GtkWidget *label;
GtkWidget *checkbutton;
int i;
char bufferf[32];
char bufferl[32];
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
table = gtk_table_new(3,6,FALSE);
gtk_container_add (GTK_CONTAINER (window), table);
/* Create a new notebook, place the position of the tabs */
notebook = gtk_notebook_new ();
gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
gtk_widget_show(notebook);
/* Let's append a bunch of pages to the notebook */
for (i=0; i < 5; i++) {
sprintf(bufferf, "Append Frame %d", i+1);
sprintf(bufferl, "Page %d", i+1);
frame = gtk_frame_new (bufferf);
gtk_container_set_border_width (GTK_CONTAINER (frame), 10);
gtk_widget_set_usize (frame, 100, 75);
gtk_widget_show (frame);
label = gtk_label_new (bufferf);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_widget_show (label);
label = gtk_label_new (bufferl);
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
}
/* Now let's add a page to a specific spot */
checkbutton = gtk_check_button_new_with_label ("Check me please!");
gtk_widget_set_usize(checkbutton, 100, 75);
gtk_widget_show (checkbutton);
label = gtk_label_new ("Add page");
gtk_notebook_insert_page (GTK_NOTEBOOK (notebook),checkbutton,label,2);
/* Now finally let's prepend pages to the notebook */
for (i=0; i < 5; i++) {
sprintf(bufferf, "Prepend Frame %d", i+1);
sprintf(bufferl, "PPage %d", i+1);
frame = gtk_frame_new (bufferf);
gtk_container_set_border_width (GTK_CONTAINER (frame), 10);
gtk_widget_set_usize (frame, 100, 75);
gtk_widget_show (frame);
label = gtk_label_new (bufferf);
gtk_container_add (GTK_CONTAINER (frame), label);
gtk_widget_show (label);
label = gtk_label_new (bufferl);
gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
}
/* Set what page to start at (page 4) */
gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
/* Create a bunch of buttons */
button = gtk_button_new_with_label ("close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (delete), NULL);
gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
gtk_widget_show(button);
button = gtk_button_new_with_label ("next page");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) gtk_notebook_next_page,
GTK_OBJECT (notebook));
gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
gtk_widget_show(button);
button = gtk_button_new_with_label ("prev page");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) gtk_notebook_prev_page,
GTK_OBJECT (notebook));
gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
gtk_widget_show(button);
button = gtk_button_new_with_label ("tab position");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) rotate_book,
GTK_OBJECT(notebook));
gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
gtk_widget_show(button);
button = gtk_button_new_with_label ("tabs/border on/off");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) tabsborder_book,
GTK_OBJECT (notebook));
gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
gtk_widget_show(button);
button = gtk_button_new_with_label ("remove page");
gtk_signal_connect (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) remove_book,
GTK_OBJECT(notebook));
gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
gtk_widget_show(button);
gtk_widget_show(table);
gtk_widget_show(window);
gtk_main ();
return(0);
}
/* example-end */

  I hope this helps you on your way with creating notebooks for your GTK applications.

11. CList Widget

  The CList widget has replaced the List widget (which is still available).

  The CList widget is a multi- column list widget that is capable of handling literally thousands of rows of information. Each column can optionally have a title, which itself is optionally active, allowing us to bind a function to its selection.

11.1 Creating a CList widget

  Creating a CList is quite straightforward, once you have learned about widgets in general. It provides the almost standard two ways, that is the hard way, and the easy way. But before we create it, there is one thing we should figure out
beforehand: how many columns should it have?

  Not all columns have to be visible and can be used to store data that is related to a certain cell in the list.


GtkWidget *gtk_clist_new ( gint columns );
GtkWidget *gtk_clist_new_with_titles( gint columns,
gchar *titles[] );

  The first form is very straightforward, the second might require some explanation. Each column can have a title associated with it, and this title can be a label or a button that reacts when we click on it. If we use the second form, we must
provide pointers to the title texts, and the number of pointers should equal the number of columns specified. Of course we can always use the first form, and manually add titles later.

  Note: The CList widget does not have its own scrollbars and should be placed within a ScrolledWindow widget if your require this functionality. This is a change from the GTK 1.0 implementation.

11.2 Modes of operation

  There are several attributes that can be used to alter the behaviour of a CList. First there is


void gtk_clist_set_selection_mode( GtkCList *clist,
GtkSelectionModemode );

  which, as the name implies, sets the selection mode of the CList. The first argument is the CList widget, and the second specifies the cell selection mode (they are defined in gtkenums.h). At the time of this writing, the following modes are
available to us:

  GTK_SELECTION_SINGLE - The selection is either NULL or contains a GList pointer for a single selected item.

  GTK_SELECTION_BROWSE - The selection is NULL if the list contains no widgets or insensitive ones only, otherwise it contains a GList pointer for one GList structure, and therefore exactly one list item.

  GTK_SELECTION_MULTIPLE - The selection is NULL if no list items are selected or a GList pointer for the first selected item. That in turn points to a GList structure for the second selected item and so on. This is currently the default for the
CList widget.

  GTK_SELECTION_EXTENDED - The selection is always NULL.

  Others might be added in later revisions of GTK.

  We can also define what the border of the CList widget should look like. It is done through


void gtk_clist_set_shadow_type( GtkCList*clist,
GtkShadowTypeborder );

  The possible values for the second argument are

  GTK_SHADOW_NONE

  GTK_SHADOW_IN

  GTK_SHADOW_OUT

  GTK_SHADOW_ETCHED_IN

  GTK_SHADOW_ETCHED_OUT

11.3 Working with titles

  When you create a CList widget, you will also get a set of title buttons automatically. They live in the top of the CList window, and can act either as normal buttons that respond to being pressed, or they can be passive, in which case they are
nothing more than a title. There are four different calls that aid us in setting the status of the title buttons.


void gtk_clist_column_title_active( GtkCList *clist,gint column );
void gtk_clist_column_title_passive( GtkCList *clist,gintcolumn );
void gtk_clist_column_titles_active( GtkCList *clist );
void gtk_clist_column_titles_passive( GtkCList *clist );

  An active title is one which acts as a normal button, a passive one is just a label. The first two calls above will activate/deactivate the title button above the specific column, while the last two calls activate/deactivate all title buttons in
the supplied clist widget.

  But of course there are those cases when we don't want them at all, and so they can be hidden and shown at will using the following two calls.


void gtk_clist_column_titles_show( GtkCList *clist );
void gtk_clist_column_titles_hide( GtkCList *clist );

  For titles to be really useful we need a mechanism to set and change them, and this is done using


void gtk_clist_set_column_title( GtkCList *clist,
gintcolumn,gchar*title );

  Note that only the title of one column can be set at a time, so if all the titles are known from the beginning, then I really suggest using gtk_clist_new_with_titles (as described above) to set them. It saves you coding time, and makes your
program smaller. There are some cases where getting the job done the manual way is better, and that's when not all titles will be text. CList provides us with title buttons that can in fact incorporate whole widgets, for example a pixmap. It's all
done through


void gtk_clist_set_column_widget( GtkCList*clist,
gint column,GtkWidget *widget );

  which should require no special explanation.

11.4 Manipulating the list itself

  It is possible to change the justification for a column, and it is done through


void gtk_clist_set_column_justification( GtkCList *clist,
gintcolumn,GtkJustificationjustification );

  The GtkJustification type can take the following values:

  GTK_JUSTIFY_LEFT - The text in the column will begin from the left edge.

  GTK_JUSTIFY_RIGHT - The text in the column will begin from the right edge.

  GTK_JUSTIFY_CENTER - The text is placed in the center of the column.

  GTK_JUSTIFY_FILL - The text will use up all available space in the column. It is normally done by inserting extra blank spaces between words (or between individual letters if it's a single word). Much in the same way as any ordinary WYSIWYG text
editor.

  The next function is a very important one, and should be standard in the setup of all CList widgets. When the list is created, the width of the various columns are chosen to match their titles, and since this is seldom the right width we have to
set it using


void gtk_clist_set_column_width( GtkCList *clist,
gintcolumn,gintwidth );

   Note that the width is given in pixels and not letters. The same goes for the height of the cells in the columns, but as the default value is the height of the current font this isn't as critical to the application. Still, it is done through


void gtk_clist_set_row_height( GtkCList *clist,gintheight );

  Again, note that the height is given in pixels.

  We can also move the list around without user interaction, however, it does require that we know what we are looking for. Or in other words, we need the row and column of the item we want to scroll to.


void gtk_clist_moveto( GtkCList *clist,
gintrow,gintcolumn,gfloatrow_align,gfloatcol_align );

   The gfloat row_align is pretty important to understand. It's a value between 0.0 and 1.0, where 0.0 means that we should scroll the list so the row appears at the top, while if the value of row_align is 1.0, the row will appear at the bottom
instead. All other values between 0.0 and 1.0 are also valid and will place the row between the top and the bottom. The last argument, gfloat col_align works in the same way, though 0.0 marks left and 1.0 marks right instead.

  Depending on the application's needs, we don't have to scroll to an item that is already visible to us. So how do we know if it is visible? As usual, there is a function to find that out as well.


GtkVisibility gtk_clist_row_is_visible( GtkCList *clist,gintrow );

  The return value is is one of the following:

  GTK_VISIBILITY_NONE

  GTK_VISIBILITY_PARTIAL

  GTK_VISIBILITY_FULL

   Note that it will only tell us if a row is visible. Currently there is no way to determine this for a column. We can get partial information though, because if the return is GTK_VISIBILITY_PARTIAL, then some of it is hidden, but we don't know if
it is the row that is being cut by the lower edge of the listbox, or if the row has columns that are outside.

   We can also change both the foreground and background colors of a particular row. This is useful for marking the row selected by the user, and the two functions that is used to do it are


void gtk_clist_set_foreground( GtkCList *clist,gintrow,GdkColor *color );
void gtk_clist_set_background( GtkCList *clist,gintrow,GdkColor *color );

  Please note that the colors must have been previously allocated.

11.5 Adding rows to the list

  We can add rows in three ways. They can be prepended or appended to the list using


gint gtk_clist_prepend( GtkCList *clist,gchar*text[] );
gint gtk_clist_append( GtkCList *clist,gchar*text[] );

   The return value of these two functions indicate the index of the row that was just added. We can insert a row at a given place using


void gtk_clist_insert( GtkCList *clist,gintrow,gchar*text[] );

   In these calls we have to provide a collection of pointers that are the texts we want to put in the columns. The number of pointers should equal the number of columns in the list. If the text[] argument is NULL, then there will be no text in the
columns of the row. This is useful, for example, if we want to add pixmaps instead (something that has to be done manually).

  Also, please note that the numbering of both rows and columns start at 0.

  To remove an individual row we use


void gtk_clist_remove( GtkCList *clist,gintrow );

   There is also a call that removes all rows in the list. This is a lot faster than calling gtk_clist_remove once for each row, which is the only alternative.


void gtk_clist_clear( GtkCList *clist );

   There are also two convenience functions that should be used when a lot of changes have to be made to the list. This is to prevent the list flickering while being repeatedly updated, which may be highly annoying to the user. So instead it is a
good idea to freeze the list, do the updates to it, and finally thaw it which causes the list to be updated on the screen.


void gtk_clist_freeze( GtkCList * clist );
void gtk_clist_thaw( GtkCList * clist );

11.6 Setting text and pixmaps in the cells

  A cell can contain a pixmap, text or both. To set them the following functions are used.


void gtk_clist_set_text( GtkCList*clist,
gint row,gint column,const gchar *text );
void gtk_clist_set_pixmap( GtkCList*clist,
gint row,gint column,GdkPixmap *pixmap,GdkBitmap *mask );
void gtk_clist_set_pixtext( GtkCList*clist,gint row,gint column,
gchar *text,guint8 spacing,GdkPixmap *pixmap,GdkBitmap *mask );

   It's quite straightforward. All the calls have the CList as the first argument, followed by the row and column of the cell, followed by the data to be set. The spacing argument in gtk_clist_set_pixtext is the number of pixels between the pixmap
and the beginning of the text. In all cases the data is copied into the widget.

  To read back the data, we instead use


gint gtk_clist_get_text( GtkCList*clist,
gint row,gint column,gchar**text );
gint gtk_clist_get_pixmap( GtkCList *clist,
gintrow,gintcolumn,GdkPixmap **pixmap,GdkBitmap **mask );
gint gtk_clist_get_pixtext( GtkCList *clist,
gintrow,gintcolumn,gchar **text,
guint8 *spacing,GdkPixmap **pixmap,GdkBitmap **mask );

   The returned pointers are all pointers to the data stored within the widget, so the referenced data should not be modified or released. It isn't necessary to read it all back in case you aren't interested. Any of the pointers that are meant for
return values (all except the clist) can be NULL. So if we want to read back only the text from a cell that is of type pixtext, then we would do the following, assuming that clist, row and column already exist:


gchar *mytext;
gtk_clist_get_pixtext(clist, row, column, &mytext, NULL, NULL, NULL);

  There is one more call that is related to what's inside a cell in the clist, and that's


GtkCellType gtk_clist_get_cell_type( GtkCList *clist,
gintrow,gintcolumn );

  which returns the type of data in a cell. The return value is one of

  GTK_CELL_EMPTY

  GTK_CELL_TEXT

  GTK_CELL_PIXMAP

  GTK_CELL_PIXTEXT

  GTK_CELL_WIDGET

  There is also a function that will let us set the indentation, both vertical and horizontal, of a cell. The indentation value is of type gint, given in pixels, and can be both positive and negative.


void gtk_clist_set_shift( GtkCList *clist,
gintrow,gintcolumn,gintvertical,ginthorizontal );

11.7 Storing data pointers

   With a CList it is possible to set a data pointer for a row. This pointer will not be visible for the user, but is merely a convenience for the programmer to associate a row with a pointer to some additional data.

  The functions should be fairly self-explanatory by now.


void gtk_clist_set_row_data( GtkCList *clist,gintrow,gpointerdata );
void gtk_clist_set_row_data_full( GtkCList *clist,
gintrow,gpointerdata,GtkDestroyNotifydestroy );
gpointer gtk_clist_get_row_data( GtkCList *clist,gintrow );
gint gtk_clist_find_row_from_data( GtkCList *clist,gpointerdata );

11.8 Working with selections

  There are also functions available that let us force the (un)selection of a row. These are


void gtk_clist_select_row( GtkCList *clist,gintrow,gintcolumn );
void gtk_clist_unselect_row( GtkCList *clist,gintrow,gintcolumn );

  And also a function that will take x and y coordinates (for example, read from the mousepointer), and map that onto the list, returning the corresponding row and column.


gint gtk_clist_get_selection_info( GtkCList *clist,
gintx,ginty,gint *row,gint *column );

  When we detect something of interest (it might be movement of the pointer, a click somewhere in the list) we can read the pointer coordinates and find out where in the list the pointer is. Cumbersome? Luckily, there is a simpler way...

11.9 The signals that bring it together

  As with all other widgets, there are a few signals that can be used. The CList widget is derived from the Container widget, and so has all the same signals, but also adds the following:

  select_row - This signal will send the following information, in order: GtkCList *clist, gint row, gint column, GtkEventButton *event

  unselect_row - When the user unselects a row, this signal is activated. It sends the same information as select_row

  click_column - Send GtkCList *clist, gint column

  So if we want to connect a callback to select_row, the callback function would be declared like this


void select_row_callback(GtkWidget *widget,
gint row,gint column,GdkEventButton *event,gpointer data);

  The callback is connected as usual with


gtk_signal_connect(GTK_OBJECT( clist),
"select_row"
GTK_SIGNAL_FUNC(select_row_callback),
NULL);

11.10 A CList example


/* example-start clist clist.c */
#include
/* User clicked the "Add List" button. */
void button_add_clicked( gpointer data )
{
int indx;
/* Something silly to add to the list. 4 rows of 2 columns each */
gchar *drink[4][2] = { { "Milk","3 Oz" },
{ "Water", "6 l" },
{ "Carrots", "2" },
{ "Snakes","55" } };
/* Here we do the actual adding of the text. It's done once for
* each row.
*/
for ( indx=0 ; indx < 4 ; indx++ )
gtk_clist_append( (GtkCList *) data, drink[indx]);
return;
}
/* User clicked the "Clear List" button. */
void button_clear_clicked( gpointer data )
{
/* Clear the list using gtk_clist_clear. This is much faster than
* calling gtk_clist_remove once for each row.
*/
gtk_clist_clear( (GtkCList *) data);
return;
}
/* The user clicked the "Hide/Show titles" button. */
void button_hide_show_clicked( gpointer data )
{
/* Just a flag to remember the status. 0 = currently visible */
static short int flag = 0;
if (flag == 0)
{
/* Hide the titles and set the flag to 1 */
gtk_clist_column_titles_hide((GtkCList *) data);
flag++;
}
else
{
/* Show the titles and reset flag to 0 */
gtk_clist_column_titles_show((GtkCList *) data);
flag--;
}
return;
}
/* If we come here, then the user has selected a row in the list. */
void selection_made( GtkWidget*clist,
gintrow,
gintcolumn,
GdkEventButton *event,
gpointerdata )
{
gchar *text;
/* Get the text that is stored in the selected row and column
* which was clicked in. We will receive it as a pointer in the
* argument text.
*/
gtk_clist_get_text(GTK_CLIST(clist), row, column, &text);
/* Just prints some information about the selected row */
g_print("You selected row %d. More specifically you clicked in "
"column %d, and the text in this cell is %s

",
row, column, text);
return;
}
int main( intargc,
gchar *argv[] )
{
GtkWidget *window;
GtkWidget *vbox, *hbox;
GtkWidget *scrolled_window, *clist;
GtkWidget *button_add, *button_clear, *button_hide_show;
gchar *titles[2] = { "Ingredients", "Amount" };
gtk_init(&argc, &argv);
window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_usize(GTK_WIDGET(window), 300, 150);
gtk_window_set_title(GTK_WINDOW(window), "GtkCList Example");
gtk_signal_connect(GTK_OBJECT(window),
"destroy",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL);
vbox=gtk_vbox_new(FALSE, 5);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 5);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_widget_show(vbox);
/* Create a scrolled window to pack the CList widget into */
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
gtk_box_pack_start(GTK_BOX(vbox), scrolled_window, TRUE, TRUE, 0);
gtk_widget_show (scrolled_window);
/* Create the CList. For this example we use 2 columns */
clist = gtk_clist_new_with_titles( 2, titles);
/* When a selection is made, we want to know about it. The callback
* used is selection_made, and its code can be found further down */
gtk_signal_connect(GTK_OBJECT(clist), "select_row",
GTK_SIGNAL_FUNC(selection_made),
NULL);
/* It isn't necessary to shadow the border, but it looks nice :) */
gtk_clist_set_shadow_type (GTK_CLIST(clist), GTK_SHADOW_OUT);
/* What however is important, is that we set the column widths as
* they will never be right otherwise. Note that the columns are
* numbered from 0 and up (to 1 in this case).
*/
gtk_clist_set_column_width (GTK_CLIST(clist), 0, 150);
/* Add the CList widget to the vertical box and show it. */
gtk_container_add(GTK_CONTAINER(scrolled_window), clist);
gtk_widget_show(clist);
/* Create the buttons and add them to the window. See the button
* tutorial for more examples and comments on this.
*/
hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0);
gtk_widget_show(hbox);
button_add = gtk_button_new_with_label("Add List");
button_clear = gtk_button_new_with_label("Clear List");
button_hide_show = gtk_button_new_with_label("Hide/Show titles");
gtk_box_pack_start(GTK_BOX(hbox), button_add, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(hbox), button_clear, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(hbox), button_hide_show, TRUE, TRUE, 0);
/* Connect our callbacks to the three buttons */
gtk_signal_connect_object(GTK_OBJECT(button_add), "clicked",
GTK_SIGNAL_FUNC(button_add_clicked),
(gpointer) clist);
gtk_signal_connect_object(GTK_OBJECT(button_clear), "clicked",
GTK_SIGNAL_FUNC(button_clear_clicked),
(gpointer) clist);
gtk_signal_connect_object(GTK_OBJECT(button_hide_show), "clicked",
GTK_SIGNAL_FUNC(button_hide_show_clicked),
(gpointer) clist);
gtk_widget_show(button_add);
gtk_widget_show(button_clear);
gtk_widget_show(button_hide_show);
/* The interface is completely set up so we show the window and
* enter the gtk_main loop.
*/
gtk_widget_show(window);
gtk_main();
return(0);
}
/* example-end */


[ 本帖最後由 gxf 於 2007-10-9 01:23 編輯 ]

[火星人 ] 給GTK+初學者------英文版已經有747次圍觀

http://coctec.com/docs/linux/show-post-169256.html