PyQt5:带QAction的键盘快捷键 [英] PyQt5: Keyboard shortcuts w/ QAction
本文介绍了PyQt5:带QAction的键盘快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在PyQt5中实现键盘快捷键(以运行功能)?我看到我应该以一种或另一种方式使用QAction
,但是我不能将两者和两者放在一起,并且所有示例似乎都不适用于PyQt5,而是适用于PyQt4.
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.
推荐答案
使用QShortcut
和QKeySequence
类,如下所示:
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_())
这篇关于PyQt5:带QAction的键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文