7.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( const gchar *label );

GtkWidget *gtk_toggle_button_new_with_mnemonic( const gchar *label );

As you can imagine, these work identically to the normal button widget calls. The first creates a blank toggle button, and the last two, a button with a label widget already packed into it. The _mnemonic() variant additionally parses the label for '_'-prefixed mnemonic characters.

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 button, 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_get_active (GTK_TOGGLE_BUTTON (widget))) 
    {
        /* 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,
                                   gboolean        is_active );

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" and "toggled" signals to be emitted from the button.

gboolean gtk_toggle_button_get_active	(GtkToggleButton *toggle_button);

This returns the current state of the toggle button as a boolean TRUE/FALSE value.