单选按钮

单选按钮是带有“选中”指示器的按钮,它们属于一组相似的按钮。组内只能选择一个单选按钮。

GTK 使用 复选框 组来实现“单选”行为。

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

gtk_check_button_set_group (GTK_CHECK_BUTTON (laugh),
                            GTK_CHECK_BUTTON (live));
gtk_check_button_set_group (GTK_CHECK_BUTTON (love),
                            GTK_CHECK_BUTTON (live));

检测被激活的按钮

您可以使用“toggled”信号,或者可以使用“active”属性。

static void
on_toggled (GtkCheckButton *button,
            const char *identifier)
{
  gboolean is_active = gtk_check_button_get_active (button);

  if (strcmp (identifier, "live") == 0)
    update_live (is_active);   // update_live() is defined elsewhere
  else if (strcmp (identifier, "laugh") == 0)
    update_laugh (is_active);  // update_laugh() is defined elsewhere
  else if (strcmp (identifier, "love") == 0)
    update_love (is_active);   // update_love() is defined elsewhere
}

// ...

  // The live, laugh, and love variables are defined like the example above
  g_signal_connect (live, "toggled", G_CALLBACK (on_toggled), "live");
  g_signal_connect (laugh, "toggled", G_CALLBACLK (on_toggled), "laugh");
  g_signal_connect (love, "love", G_CALLBACK (on_toggled), "love");

组件的常用方法

  • 如果您想为您的单选按钮启用助记符快捷键,可以使用 new_with_mnemonic() 构造函数,或者 set_use_underline() 方法。

API 参考

在示例中,我们使用了以下类