【发布时间】:2020-09-15 12:38:11
【问题描述】:
在 PyQt5 应用程序中,我有一个 QMenu。我想让它一旦打开菜单,用户就可以使用键 1、2、3 等来选择菜单中的选项 1、2、3 等。但是,我在设置快捷方式或让快捷方式对按键做出反应时遇到问题。
我从this 网站上举了一个例子,并稍加修改以显示我的问题。我尝试在 addAction 函数中分配快捷方式,但这不起作用。
我尝试过创建常规的 QShortcut,但是当菜单打开时它们不再响应。我注意到我可以使用向上和向下箭头更改选定的选项,然后使用回车键确认我的选择,因此 QMenu 能够捕捉按键。但是如何分配自己的快捷方式?
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Context Menu"
self.top = 200
self.left = 500
self.width = 400
self.height = 300
self.InitWindow()
def InitWindow(self):
self.setWindowIcon(QtGui.QIcon("icon.png"))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
def contextMenuEvent(self, event):
contextMenu = QMenu(self)
newAct = contextMenu.addAction("New", self.triggered, shortcut='A')
openAct = contextMenu.addAction("Open", self.triggered2, shortcut='B')
quitAct = contextMenu.addAction("Quit", self.triggered3, shortcut='C')
action = contextMenu.exec_(self.mapToGlobal(event.pos()))
if action == quitAct:
self.close()
def triggered(self):
print("triggered 1")
def triggered2(self):
print("triggered 2")
def triggered3(self):
print("triggered 3")
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
【问题讨论】:
-
`shortcut='A'` 有点奇怪:它不会在上下文菜单中显示快捷方式(当我认为它应该从 Qt5.15 开始时,
showShortcutsInContextMenus is True或可以更改App.styleHints().setShowShortcutsInContextMenus(True). -
使用
newAct.setShortcuts(["1"])确实显示快捷方式...但不足以使其工作。