PyQt Connect to KeyPressEvent

Certain widgets will allow me to do:

self.widget.clicked.connect(on_click) 

but do:

 self.widget.keyPressEvent.connect(on_key) 

cannot say that the object does not have the "connect" attribute.

I know that subclassing the widget's classification and keyPressEvent method will allow me to respond to the event. But how can I .connect() on a keyboard event after that or, if not to say, say, from a user's context?

+5
source share
2 answers

Create a custom signal and emit it from the redefined event handler:

 class MyWidget(QtGui.QWidget): keyPressed = QtCore.pyqtSignal() def keyPressEvent(self, event): super(MyWidget, self).keyPressEvent(event) self.keyPressed.emit() ... self.widget.keyPressed.connect(on_key) 

(NB: a base class implementation call is required to preserve existing event handling).

+8
source

The way I did this in the past is (this is the job) where it is in the sender and the receiver advertises / connects to the signal.

 def keyPressEvent(self, event): if type(event) == QtGui.QKeyEvent: if event.key() == QtCore.Qt.Key_Space: self.emit(QtCore.SIGNAL('MYSIGNAL')) 
+3
source

Source: https://habr.com/ru/post/1209039/


All Articles