PyQt Connect to KeyPressEvent

jpcgt picture jpcgt · Dec 15, 2014 · Viewed 23k times · Source

Certain widgets will allow me to do:

self.widget.clicked.connect(on_click)

but doing:

self.widget.keyPressEvent.connect(on_key)

will fail saying that the object has no attribute 'connect'.

I know that sub-classing the widget and re-implementing the keyPressEvent method will allow me to respond to the event. But how can I .connect() to the keyboard event thereafter, or otherwise said, from a user context?

Answer

ekhumoro picture ekhumoro · Dec 15, 2014

Create a custom signal, and emit it from your reimplemented event handler:

class MyWidget(QtGui.QWidget):
    keyPressed = QtCore.pyqtSignal(int)

    def keyPressEvent(self, event):
        super(MyWidget, self).keyPressEvent(event)
        self.keyPressed.emit(event.key())
...

def on_key(key):
    # test for a specific key
    if key == QtCore.Qt.Key_Return:
        print('return key pressed')
    else:
        print('key pressed: %i' % key)

self.widget.keyPressed.connect(on_key)

(NB: calling the base-class implementation is required in order to keep the existing handling of events).