[英]PyQt5 Shortcut does not work all the time
因此,我使用 PyQt5 構建了一個 GUI,並為我的子菜單創建了一個快捷方式,如下所示:
''' Menubar '''
mainMenu = self.menuBar()
''' Sub-Menubar '''
fileMenu = mainMenu.addMenu('Options')
Pathfinder = QAction('Choose Folder', self)
Pathfinder.setShortcut("Shift+L")
Pathfinder.triggered.connect(lambda: self.clicked_menu(0))
fileMenu.addAction(Pathfinder)
按 Shift + L 可以正常工作...只要我的鼠標 cursor 在元素中未處於活動狀態。 例如,如果我更改其中一個 spinBox 中的值,並且 cursor (=caret) 在 spinBox 內“閃爍”,則 Shift+L 什么也不做。
self.spinBoxMaxHolesPerCycle = QSpinBox(self)
self.spinBoxMaxHolesPerCycle.setGeometry(485, 310, 45, 20)
self.spinBoxMaxHolesPerCycle.setMaximum(200)
self.spinBoxMaxHolesPerCycle.setValue(100)
self.spinBoxMaxHolesPerCycle.valueChanged.connect(lambda: self.changedValue(11))
有沒有辦法解決這個問題,而無需單擊其他地方“分離”cursor?
您面臨的行為與鼠標 cursor 無關,而是與鍵盤焦點有關(不過,您可以通過單擊將焦點設置為小部件)。
問題是 QSpinBox 小部件包含一個 QLineEdit 用於使用鍵盤編輯值,並且由於您的快捷方式可以解釋為文本(大寫“L”字母),小部件自動“吃掉”鍵盤事件,防止將其傳播給父級。
如果您只關心單個小部件,則可以將其子類化並覆蓋其keyPressEvent
,如果它與快捷方式不匹配,則只需調用基本實現。
由於您可能希望將行為應用於多個小部件,因此一種解決方案是在 QApplication 上安裝事件過濾器並檢查按鍵事件:如果事件與您的快捷方式匹配,則只需觸發操作並返回 True。
# ...
# make the action an attribute, so that it can be accessed from elsewhere
self.pathfinderAction = QtWidgets.QAction('Choose Folder', self)
# ...
QtWidgets.QApplication.instance().installEventFilter(self)
def eventFilter(self, source, event):
if (isinstance(source, QtWidgets.QWidget) and
event.type() == QtCore.QEvent.KeyPress):
sequence = QtGui.QKeySequence(int(event.modifiers()) + event.key())
if sequence == self.pathfinderAction.shortcut():
# the event matches the shortcut
self.pathfinderAction.trigger()
return True
return super().eventFilter(source, event)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.