Map a keyboard button to a signal/action

Hi everyone,

is there a simple way to map some key to a signal or action (except of adding GtkEventController and handle all those events), something like
gtk_widget_bind_key(widget, GDK_KEY_Escape, "close") ?

GTK4 has GtkShortcut. See the Shortcuts demo in gtk4-demo.

In a widget subclass’s class_init, you can use e.g. Gtk.WidgetClass.add_binding_action

Thank you for suggestion, I’ve already seen that and skipped because it’s needed for an instanse (not for class) and working with shortcuts a bit more complicated than with keyboard events. So that just finished by adding GtkEventController and callback like

static gboolean help_dialog_cb(GtkEventControllerKey *c, guint val, guint code, guint mo, GtkButton *btn) {
  if ((val != GDK_KEY_Escape) || mo || !GTK_IS_BUTTON(btn)) return false;
  g_signal_emit_by_name(btn, EV_CLICK);
  return true;
}
...
    GtkEventController *kcntrl = gtk_event_controller_key_new();
    if (GTK_IS_EVENT_CONTROLLER(kcntrl)) { // optional
      g_signal_connect(kcntrl, EV_KEY, G_CALLBACK(help_dialog_cb), help_dialog.btn);
      gtk_widget_add_controller(help_dialog.win, kcntrl);
    }

Anyway thank you.

As an alternative:

    controller = gtk_shortcut_controller_new ();
    gtk_widget_add_controller (win, controller);
    
    shortcut = gtk_shortcut_new (gtk_keyval_trigger_new (GDK_KEY_Escape, 0),
                                 gtk_named_action_new ("win.close"));
    gtk_shortcut_controller_add_shortcut (GTK_SHORTCUT_CONTROLLER (controller), shortcut);

I don’t think that’s worse.

Looks good, but it doesn’t work. Nothing happens at pressing <Esc> as opposed to that with a signal emitted from callback. No idea why, maybe something more is needed to add.

It assumes that it’s in a GtkApplicationWindow with an action called close. You can modify that to your actual situation. Alternatively, you can use gtk_callback_action_new().

1 Like

Ahh… <Esc> there is used to close a modal window dialog by emitting “clicked” signal as it were by clicking on close button (it works via callback emitted signal as it written in the first snippet).
Okay, thank you for alternatives.

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.