gpt4 book ai didi

python - 列出 QMainWindow 的所有快捷方式

转载 作者:行者123 更新时间:2023-12-01 00:41:17 25 4
gpt4 key购买 nike

我有一个 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 列出?

[编辑]由于似乎没有 native 解决方案,我启动了一个小部件 here .

最佳答案

有简单的解决方案吗?

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

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

并非每个 QAction 都意味着有一个关联的 QShortcut,对于 QToolBar,它已经有一个默认的 QAction,即 toggleViewAction() ,这就是您所获得的,并且没有关联的快捷方式。

关于python - 列出 QMainWindow 的所有快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57328901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com