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.
            Asked
            
        
        
            Active
            
        
            Viewed 2.4k times
        
    20
            
            
        
        Lachlan
        
- 1,245
 - 5
 - 18
 - 34
 
3 Answers
33
            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_())
8
            
            
        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"))
        ronathan
        
- 736
 - 7
 - 5
 
- 
                    Hello may I ask what is `my_action` or what object is it? I think your answer is great! – Ice Bear Jan 01 '21 at 05:15
 - 
                    Could you please add an example code... your answer is very much helpful to others :) – Ice Bear Jan 01 '21 at 05:32
 
1
            
            
        It can be more simple and more powerful, depending on your needs:
QShortcut( 'Shift+Ins', tree_view ).activated.connect( lambda : tree_view.add_row( 'next sibling' ) )
... passes the string 'next sibling' as parameter to the method tree_view.add_row.
Also check out the "Standard Shortcuts" section in QKeySequence: probably usually best to stick with the platform-specific conventions (and not override them inadvertently...) unless there's a good reason to do otherwise.
        mike rodent
        
- 14,126
 - 11
 - 103
 - 157