Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
Lachlan Avatar asked Sep 23 '14 07:09

Lachlan


1 Answers

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_())
like image 100
Fenikso Avatar answered Sep 23 '22 02:09

Fenikso