The key-press-event handler doesn't receive the EventKey object

,

I am listening for the key-press-event signal. The callback gets called but unfortunately the EventKey object is empty. I have no way of telling which key has been pressed. I have something like:

const win = new Gtk.Window({
  defaultWidth: 450,
  defaultHeight: 600,
  title: "Hello World",
});

win.connect("key-press-event", function(widget, event){
  console.log(win === widget); // true
  console.log(event);  // {}
  console.log(event.keyval);  // undefined
});

Unfortunately the documentation doesn’t explain how to use these signals.

In GTK3, the key-press-event signal emits a Gdk.Event, which is a union of types. Unions are a bit tricky in GJS; in this case you’ll probably just want use the accessors like Gdk.Event.get_keyval():

const win = new Gtk.Window({
  defaultWidth: 450,
  defaultHeight: 600,
  title: "Hello World",
});

win.connect("key-press-event", function(widget, event) {
  log(event instanceof Gdk.Event);                         // true
  log(event.get_event_type() === Gdk.EventType.KEY_PRESS); // true
    
  // We know this is a key press event, so elide the boolean
  const [, keyval] = event.get_keyval();
});
2 Likes

Thanks. This is really useful. I wish we could have this info somewhere in the gjs.guide.

Information about GObject usage like this in GJS can be found on gjs-docs.gnome.org, which is scraped from the GJS repository. At this point GTK3 is probably a little old to expect many tutorials to be written for it.

That being said, gjs.guide is a community-driven site, so you are welcome to contribute what you learn about key-press events here.

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