【发布时间】:2019-08-02 14:52:14
【问题描述】:
我有一个 PySide2 应用程序,它的大小正在增长,我想转储所有快捷方式。 有没有简单的解决办法?
第一个目标是能够列出它们(假设检查它们都记录在案并且没有重复),但我很快就会有兴趣让用户自定义它们(所以如果有人有一个例子一个快捷方式编辑器,我也会感兴趣;我暂时只找到了这个https://doc.qt.io/archives/qq/qq14-actioneditor.html。
这篇帖子Qt - Disable/enable all shortcuts 建议findChildren,所以我想出了一个解决方案的开始(见下面的代码),但我觉得Qt 中可能包含一些我可能错过的东西?
# This is file mygui.py
import sys
from PySide2.QtWidgets import QAction, QMessageBox, QMainWindow, QApplication
from PySide2.QtGui import QIcon, QKeySequence
class MyGUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('My GUI')
self.fileMenu = self.menuBar().addMenu('&File')
self.toolBar = self.addToolBar('my toolbar')
act = QAction('About', self)
act.triggered.connect(self.popup_hello)
act.setShortcuts(['Ctrl+A'])
for x in [self.fileMenu, self.toolBar]: x.addAction(act)
act = QAction('Show shortcuts', self)
act.triggered.connect(self.display_shortcuts)
for x in [self.fileMenu, self.toolBar]: x.addAction(act)
act = QAction('Quit', self, icon=QIcon.fromTheme('exit'))
act.setShortcuts(QKeySequence.Quit)
act.triggered.connect(self.close)
for x in [self.fileMenu, self.toolBar]: x.addAction(act)
def popup_hello(self):
self.statusBar().showMessage('Bienvenue')
QMessageBox.about(self, 'About', 'This is my GUI. v0.1')
def display_shortcuts(self):
for action in self.findChildren(QAction) :
print(type(action), action.toolTip(), [x.toString() for x in action.shortcuts()])
if __name__ == '__main__':
qt_app = QApplication(sys.argv)
app = MyGUI()
app.show()
#app.dumpObjectTree()
app.display_shortcuts()
qt_app.exec_()
这显示:
$ python3 mygui.py
<class 'PySide2.QtWidgets.QAction'> File []
<class 'PySide2.QtWidgets.QAction'> my toolbar []
<class 'PySide2.QtWidgets.QAction'> About ['Ctrl+A']
<class 'PySide2.QtWidgets.QAction'> Show shortcuts []
<class 'PySide2.QtWidgets.QAction'> Quit ['Ctrl+Q']
一个额外的问题:
- 我不明白为什么此处将“我的工具栏”列为 QAction?
[edit] 因为似乎没有原生解决方案,所以我启动了一个小部件here。
【问题讨论】:
-
你期望得到什么输出?
-
输出正确(“我的工具栏”除外)。我只是对使用
findChildren的解决方案感到惊讶。我希望所有快捷方式都可能在某处注册。或者有一个标准的 Qt 函数来完成这项工作。 -
也许对你的编辑来说,使用QKeySequenceEdit会有所帮助
标签: python python-3.x keyboard-shortcuts pyside2