Gtk.Button 上的加速器没有标签?

Accelerator on a Gtk.Button without a label?

所以我有一个Gtk.Button。我想加个加速键(快捷键),比如Ctrl+O.

如果我有一个标签,我可以在字母下面使用下划线来绑定,比如“_Open”。

虽然我的按钮没有任何标签,但它有一个图标。这是我 Gtk.HeaderBar.

中的一个按钮

如何在有图标但没有标签的 Gtk.Button 上放置加速器?

我认为快捷键用于菜单项,但您可以设置下划线助记符,例如“_Open”,Gtk.Button.new_with_mnemonic(label)

如果使用 XML,则向对象添加 <accelerator> 元素。

<object class="GtkButton" id="foo_button">
  <property name="visible">1</property>
  <property name="can-focus">1</property>
  <signal name="clicked" handler="_on_foo_button_clicked" swapped="no"/>
  <accelerator key="n" signal="activate" modifiers="GDK_CONTROL_MASK"/>
  <child>
    <object class="GtkImage">
      <property name="visible">1</property>
      <property name="icon-name">folder-new-symbolic</property>
    </object>
  </child>
</object>

通过c-API设置accelerator/shortcut时,我找到了以下解决方案:

/* init the keyboard shortcuts */
{
#if ( GTK_MAJOR_VERSION >= 4 )
    (*this_).keyboard_shortcut_ctrl = GTK_SHORTCUT_CONTROLLER(gtk_shortcut_controller_new());
    gtk_widget_add_controller( (*this_).window, GTK_EVENT_CONTROLLER((*this_).keyboard_shortcut_ctrl) );
#else
    (*this_).keyboard_shortcut_group = gtk_accel_group_new();
    gtk_window_add_accel_group(GTK_WINDOW( (*this_).window ), (*this_).keyboard_shortcut_group);
#endif
}

然后每个按钮:

    (*this_).edit_undo_icon = gtk_image_new_from_pixbuf( gui_resources_get_edit_undo( res ));
    gtk_widget_set_size_request( GTK_WIDGET((*this_).edit_undo_icon), 32 /*=w*/ , 32 /*=h*/ );
    (*this_).edit_undo = GTK_BUTTON(gtk_button_new());
    gtk_button_set_image( GTK_BUTTON((*this_).edit_undo), (*this_).edit_undo_icon );
    gtk_widget_set_tooltip_text( GTK_WIDGET((*this_).edit_undo), "Undo (Ctrl-Z)" );
#if ( GTK_MAJOR_VERSION >= 4 )
    GtkShortcutTrigger *undo_trig = gtk_shortcut_trigger_parse_string( "<Control>Z" );
    GtkShortcutAction *undo_act = gtk_callback_action_new( &gui_toolbox_undo_shortcut_callback,
                                                           &((*this_).tools_data),
                                                           NULL
                                                         );
    GtkShortcut* ctrl_z = gtk_shortcut_new_with_arguments( undo_trig,
                                                           undo_act,
                                                           NULL /* = format_string */
                                                         );
    gtk_shortcut_controller_add_shortcut( (*this_).keyboard_shortcut_ctrl, ctrl_z );
#else
    gtk_widget_add_accelerator( GTK_WIDGET((*this_).edit_undo),
                                "clicked",
                                (*this_).keyboard_shortcut_group,
                                GDK_KEY_z,
                                GDK_CONTROL_MASK,
                                GTK_ACCEL_VISIBLE
                              );

#endif

请注意,gui_toolbox_undo_shortcut_callback 与 button-clicked 信号具有不同的签名。