Search code examples
pythonpyqtkeyboard-shortcutspython-3.4pyqt5

PyQt5: Keyboard shortcuts w/ QAction


How do I implement keyboard shortcuts (to run a function) in PyQt5? I see I'm supposed QAction in one way or another, but I can't put the two and two together, and all examples don't seem to work with PyQt5 but instead PyQt4.


Solution

  • Use QShortcut and QKeySequence classes like this:

    import sys
    from PyQt5.QtCore import pyqtSlot
    from PyQt5.QtGui import QKeySequence
    from PyQt5.QtWidgets import QWidget, QShortcut, QLabel, QApplication, QHBoxLayout
    
    class Window(QWidget):
        def __init__(self, *args, **kwargs):
            QWidget.__init__(self, *args, **kwargs)
    
            self.label = QLabel("Try Ctrl+O", self)
            self.shortcut = QShortcut(QKeySequence("Ctrl+O"), self)
            self.shortcut.activated.connect(self.on_open)
    
            self.layout = QHBoxLayout()
            self.layout.addWidget(self.label)
    
            self.setLayout(self.layout)
            self.resize(150, 100)
            self.show()
    
        @pyqtSlot()
        def on_open(self):
            print("Opening!")
    
    app = QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())