Search code examples
pythonpyqtpyqt4

How to use arrow keys to trigger an event PyQt4


I want my arrow key on my keyboard to do the same thing if a button is pressed. I know if I want to connect to a fxn after clicking a button I would do something like self.btn.clicked.connect(fxnnamehere). Is there something like this put for the arrow keys on my keyboard?


Solution

  • For this case, the QShortCut class can be used:

    import sys
    from PyQt4 import QtCore, QtGui
    
    
    class Widget(QtGui.QWidget):
        def __init__(self):
            super().__init__()
    
            QtGui.QShortcut(QtCore.Qt.Key_Up, self, self.fooUp)
            QtGui.QShortcut(QtCore.Qt.Key_Down, self, self.fooDown)
            QtGui.QShortcut(QtCore.Qt.Key_Left, self, self.fooLeft)
            QtGui.QShortcut(QtCore.Qt.Key_Right, self, self.fooRight)
    
        def fooUp(self):
            print("up")
    
        def fooDown(self):
            print("down")
    
        def fooLeft(self):
            print("left")
    
        def fooRight(self):
            print("right")
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    

    In your particular case it seems that you are using the code generated by Qt Designer, that class that provides is not a qwidget, but a class that serves to fill in the original widget.

    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            ...
    
            QtGui.QShortcut(QtCore.Qt.Key_Up, MainWindow, self.fooUp)
            QtGui.QShortcut(QtCore.Qt.Key_Down, MainWindow, self.fooDown)
            QtGui.QShortcut(QtCore.Qt.Key_Left, MainWindow, self.fooLeft)
            QtGui.QShortcut(QtCore.Qt.Key_Right, MainWindow, self.fooRight)
    
        def fooUp(self):
            print("up")
    
        def fooDown(self):
            print("down")
    
        def fooLeft(self):
            print("left")
    
        def fooRight(self):
            print("right")