PyQt5: w / QAction shortcuts

Simply put - how do I make keyboard shortcuts (to launch a function) in PyQt5? I see that I suggested that QAction is anyway, but I can't put two and two together, and all the examples don't seem to work with PyQt5. Thanks

+9
source share
1 answer

Use QShortcut and QKeySequence 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_()) 
+11
source

Source: https://habr.com/ru/post/975700/


All Articles