A toggle button is a type of button which remains “pressed-in” when clicked.

Clicking it again will cause the toggle button to return to its normal state.

static void
on_toggle (GtkToggleButton *toggle,
           gpointer user_data)
  if (gtk_toggle_button_get_active (toggle))
    gtk_button_set_label (GTK_BUTTON (toggle), "Goodbye");
    gtk_button_set_label (GTK_BUTTON (toggle), "Hello");

// ...

GtkWidget *toggle = gtk_toggle_button_new_with_label ("Hello");

g_signal_connect (toggle, "toggled", G_CALLBACK (on_toggle), NULL);

Programmatic toggling

You can use the GtkToggleButton:active property to programmatically change the state of a toggle button.

GtkWidget *toggle = gtk_toggle_button_new_with_label ("Hello");

gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), TRUE);

Changing the GtkToggleButton:active property will also emit the GtkToggleButton::toggled signal; if you are programmatically changing the state of the toggle button and you wish to avoid running your own signal callback, you should block the handler before calling set_active():

// "toggle" and "on_toggle" are defined elsewhere
g_signal_handlers_block_by_func (toggle, on_toggle, NULL);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), TRUE);
g_signal_handlers_unblock_by_func (toggle, on_toggle, NULL);

Grouping buttons

Toggle buttons can be grouped together, to form mutually exclusive groups: only one of the buttons can be toggled at a time, and toggling another one will switch the currently toggled one off.

GtkWidget *live = gtk_toggle_button_new_with_label ("Live");
GtkWidget *laugh = gtk_toggle_button_new_with_label ("Laugh");
GtkWidget *love = gtk_toggle_button_new_with_label ("Love");

gtk_toggle_button_set_group (GTK_TOGGLE_BUTTON (laugh),
                             GTK_TOGGLE_BUTTON (live));
gtk_toggle_button_set_group (GTK_TOGGLE_BUTTON (love),
                             GTK_TOGGLE_BUTTON (live));

Useful methods for the component

  • If you want to add a mnemonic shortuct to your toggle button, you can use the new_with_mnemonic() constructor.

API references

In the examples we used the following classes: