PyQt Connect to KeyPressEvent

前端 未结 2 499
情书的邮戳
情书的邮戳 2020-12-03 15:06

Certain widgets will allow me to do:

self.widget.clicked.connect(on_click)

but doing:

self.widget.keyPressEvent.connect(on_         


        
2条回答
  •  無奈伤痛
    2020-12-03 15:43

    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).

提交回复
热议问题