In this lesson, we are going to learn how to create and assign multiple keyboard shortcuts to your PyQt5 application in Python.

The QShortcut class provides a way of connecting keyboard shortcuts to Qt’s signals and slots mechanism, so that objects can be informed when a shortcut is executed. The shortcut can be set up to contain all the key presses necessary to describe a keyboard shortcut, including the modifier keys such as Shift, Ctrl, and Alt.

And the The QKeySequence class encapsulates a key sequence as used by shortcuts.

Buy Me a Coffee? Your support is much appreciated!
PayPal Me:
Venmo: @Jie-Jenn

Source Code:

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

class AppDemo(QWidget):
    def __init__(self):

        self.label = QLabel('Press Ctrl + O', self)

        self.shortcut_open = QShortcut(QKeySequence('Ctrl+O'), self)

        self.shortcut_close = QShortcut(QKeySequence('Ctrl+Q'), self)
        self.shortcut_close.activated.connect(self.closeApp) # or lambda : app.quit()

        self.layout = QHBoxLayout()

        self.resize(150, 150)

    def on_open(self):
        print('Ctrl O has been fired')

    def closeApp(self):

app = QApplication(sys.argv)

demo = AppDemo()