In this PyQt5 tutorial, I want to revisit the topic “How to assign keyboard shortcuts” in more detail and with few more examples.

Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn



Source Code:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QWidget, QShortcut, QLabel, QApplication


class AppDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(1200, 800)
        
        self.display = QLabel()
        self.display.setAlignment(Qt.AlignCenter)
        self.display.setGeometry(1550, 1000, 600, 200)     
        self.display.setStyleSheet('font-size: 60px')

        # basic shortcut
        self.shortcut = QShortcut(QKeySequence('Ctrl+O'), self)
        self.shortcut.activated.connect(lambda shortcut_key=self.shortcut.key().toString(): self.displayKeys(shortcut_key))

        # standard shortcut
        self.shortcut = QShortcut(QKeySequence.Forward, self)
        self.shortcut.activated.connect(lambda shortcut_key=self.shortcut.key().toString(): self.displayKeys(shortcut_key))

        # Special Keys assignment
        self.shortcut = QShortcut(QKeySequence('Ctrl+Shift+T'), self)
        self.shortcut.activated.connect(lambda shortcut_key=self.shortcut.key().toString(): self.displayKeys(shortcut_key))      

        #  key sequence order
        self.shortcut = QShortcut(QKeySequence('Ctrl+Space+Shift'), self) # won't work
        self.shortcut.activated.connect(lambda shortcut_key=self.shortcut.key().toString(): self.displayKeys(shortcut_key))      
        
        self.shortcut = QShortcut(QKeySequence('Ctrl+Shift+Space'), self) # will work
        self.shortcut.activated.connect(lambda shortcut_key=self.shortcut.key().toString(): self.displayKeys(shortcut_key))      

    def displayKeys(self, mapping):
        self.display.setText(mapping)
        self.display.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = AppDemo()
    demo.show()
    
    sys.exit(app.exec_())