How to implement key press events ?



  • The UI is as following .
    http://img.my.csdn.net/uploads/201211/03/1351957960_1171.jpg

    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)

        l=QVBoxLayout(self)
    
        self.label=QLabel("(None)", self)
        l.addWidget(self.label)
    
        self.setEnterAction=QAction("Set Enter", self, shortcut=Qt.Key_Return, triggered=self.setEnter)
        self.addAction(self.setEnterAction)
        l.addWidget(QPushButton("Enter", self, clicked=self.setEnterAction.triggered))
    
        self.setSpaceAction=QAction("Set Space", self, shortcut=Qt.Key_Space, triggered=self.setSpace)
        self.addAction(self.setSpaceAction)
        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
    a=QApplication(argv)
    w=Widget()
    w.show()
    w.raise_()
    exit(a.exec_())
    @

    Hope this helps.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.