切换按钮¶
切换按钮是一种点击后保持“按下”状态的按钮。
再次点击它将使切换按钮返回到其正常状态。
static void
on_toggle (GtkToggleButton *toggle,
gpointer user_data)
{
if (gtk_toggle_button_get_active (toggle))
gtk_button_set_label (GTK_BUTTON (toggle), "Goodbye");
else
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);
def on_toggle (toggle):
if toggle.props.active:
toggle.props.label = "Goodbye"
else:
toggle.props.label = "Hello"
# ...
toggle = Gtk.ToggleButton(label="Hello")
toggle.connect("toggled", on_toggle)
var toggle = new Gtk.ToggleButton.with_label ("Hello");
toggle.toggled.connect (() => {
if (toggle.active)
toggle.label = "Goodbye";
else
toggle.label = "Hello";
});
const toggle = new Gtk.ToggleButton({ label: "Hello" });
toggle.connect("toggled", () => {
if (toggle.active) {
toggle.label = "Goodbye";
} else {
toggle.label = "Hello";
}
});
程序化切换¶
您可以使用 GtkToggleButton:active 属性来程序化地更改切换按钮的状态。
GtkWidget *toggle = gtk_toggle_button_new_with_label ("Hello");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), TRUE);
toggle = Gtk.ToggleButton(label="Hello")
toggle.set_active(True)
var toggle = new Gtk.ToggleButton.with_label ("Hello") {
active = true
};
const toggle = new Gtk.ToggleButton({
label: "Hello",
active: true,
});
更改 GtkToggleButton:active 属性还会发出 GtkToggleButton::toggled 信号;如果您正在程序化地更改切换按钮的状态,并且希望避免运行您自己的信号回调,则应在调用 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);
# "toggle" and "on_toggle" are defined elsewhere
signal_id, _ = GObject.signal_parse_name("toggled", toggle, True)
flags = GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE
def dummy(*args):
pass
GObject.signal_handlers_block_matched(toggle,
flags,
signal_id=signal_id, detail=0,
closure=on_toggle,
func=dummy, data=dummy)
toggle.props.active = True
GObject.signal_handlers_unblock_matched(toggle, flags,
signal_id=signal_id, detail=0,
closure=on_toggle,
func=dummy, data=dammy)
// "toggle" and "on_toggle" are defined elsewhere
SignalHandler.block_by_func (toggle, on_toggle, null);
toggle.active = true;
SignalHandler.unblock_by_func (toggle, on_toggle, null);
// "toggle" and "on_toggle" are defined elsewhere
const [, signal_id] = GObject.signal_parse_name("toggled", toggle, true);
const match = { signal_id, func: on_toggle };
GObject.signal_handlers_block_matched(toggle, match);
toggle.active = true;
GObject.signal_handlers_unblock_matched(toggle, match);
组件的常用方法¶
如果您想为切换按钮添加助记符快捷方式,可以使用
new_with_mnemonic()构造函数。
API 参考¶
在示例中,我们使用了以下类