【问题标题】:list all shortcuts of a QMainWindow列出 QMainWindow 的所有快捷方式
【发布时间】: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


【解决方案1】:

有简单的解决方案吗?

没有本地方法可以在窗口中查找所有快捷方式,因此您的方法是正确的。

我不明白为什么此处将“我的工具栏”列为 QAction?

并非每个 QAction 都意味着有一个关联的 QShortcut,在 QToolBar 的情况下,它已经有一个默认的 QAction,即 toggleViewAction(),这是您得到的,并且没有关联的快捷方式。

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 2015-03-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多