Details of Boxes

GTK+ 2.0 Tutorial
<<< Previous | Packing Widgets | Next >>>

# 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,
                             gboolean   expand,
                             gboolean   fill,
                             guint      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 ( gboolean 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.

<<< Previous | Home | Next >>>
Packing Widgets | Up | Packing Demonstration Program