Important: Please read the Qt Code of Conduct -

How to implement key press events ?

  • The UI is as following .

    What I want is :
    When I press the Enter key ,the label should shows “Enter”
    When I press The blank space key ,the label should shows “space”

    How to implement this ?

    I know I should reimplement the keyPressEvent handler ,but I guss I was got stuck by the focus

  • You're right, you are going to have issues with focus if you re-implement keyPressEvent for each button. The example below uses QAction's bound to the widget to capture the key events. The buttons then simply invoke these actions "triggered" method.

    from PyQt4.QtCore import *
    from PyQt4.QtGui import *

    class Widget(QWidget):
    def init(self, parent=None):
    QWidget.init(self, parent)

        self.label=QLabel("(None)", self)
        self.setEnterAction=QAction("Set Enter", self, shortcut=Qt.Key_Return, triggered=self.setEnter)
        l.addWidget(QPushButton("Enter", self, clicked=self.setEnterAction.triggered))
        self.setSpaceAction=QAction("Set Space", self, shortcut=Qt.Key_Space, triggered=self.setSpace)
        l.addWidget(QPushButton("Space", self, clicked=self.setSpaceAction.triggered))
    def setEnter(self): self.label.setText("Enter")
    def setSpace(self): self.label.setText("Space")

    if name=="main":
    from sys import argv, exit

    Hope this helps.

Log in to reply