PyQt5: Keyboard shortcuts w/ QAction

Also possible simply to write

my_action.setShortcut(QKeySequence("Ctrl+Shift+A"))

If you already have the action defined elsewhere.


An example of defining an action looks like this:

from aqt import mw

def testFunction():
    showInfo("Hello action!")

my_action = QAction("test", mw)
my_action.triggered.connect(testFunction)
my_action.setShortcut(QKeySequence("Ctrl+Shift+A"))

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_())