Reputation: 1977
I have a PySide2 application that is growing in size, and I'd like to dump all shortcuts. Is there a simple solution?
The first objective is to be able to list them (let's say to check they are all documented and there's no duplicates), but I'll very soon be interested in letting the user customize them (so if someone has an example of a shortcut editor, I'll be interested too; I only found this https://doc.qt.io/archives/qq/qq14-actioneditor.html for the moment).
This post Qt - Disable/enable all shortcuts suggests findChildren
, so I've come up with a beginning of a solution (see code below), but I'm feeling there could be something included natively in Qt that I may have missed?
# 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_()
This displays:
$ 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']
One bonus questions:
[edit] since there doesn't seem to be a native solution, I've started a small widget here.
Upvotes: 1
Views: 752
Reputation: 244112
Is there a simple solution?
There is no native method to find all the shortcuts in a window so your methodology is correct.
I don't see why 'my toolbar' is listed here as a QAction?
Not every QAction implies having an associated QShortcut, in the case of QToolBar it already has a default QAction which is the toggleViewAction(), that is the one you are getting and that does not have an associated shortcut.
Upvotes: 2