Using Gtk.EventControllerKey

Hello I want to move from key-press-event/key-release-event to Gtk.EventControllerKey but can’t get any signal from it. What is wrong in this code?

from gi.repository import Gtk, GLib
class Window:
    def __init__(self):
        window = Gtk.Window()
        window.connect('delete-event',Gtk.main_quit)
        self.__controller = Gtk.EventControllerKey.new(window)
        self.__controller.connect("key-released", self._on_key_released)
        window.show_all()
        window.resize(800, 800)

    def _on_key_released(self, controller, val, code, state):
        print(val)


if __name__ == "__main__":
    Window()
    Gtk.main()

Window is a Widget subclass. See https://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Widget.html#Gtk.Widget.add_events you can use to add the key-press and key-release events to the event mask of the object.

Same result… But I guess Gtk.Window already has this masks because connecting to “key-press-event” and “key-release-event” works.

Your code is correct, but GtkEventControllerKey is broken in GTK 3.

Thanks will wait for a fix or for GTK4 :wink:

The signals exist and you can connect to them, but in some cases the object does not even try to emit them, such as when some “events” or flags are not set.

You can actually get the events mask of the window and check if the key-press and key-release events are set.