Search code examples
pyqtpyqt5

Get list of existing QShortcuts


I would like to create various objects with associated keyboard shortcuts. The following code works fine. However, it doesn't prevent multiple objects from being assigned the same shortcut keys.

I'd like the create_shortcut function to check if there are existing shortcuts with the same keys and return an error if there are.

I've looked over the documentation for QWidget but haven't found any way to list existing shortcuts.

Any idea how to do this?

class MyClass(QObject):

    def __init__(self, parent, shortcut_keys: str):
        super().__init__(parent)
        self.create_shortcut(shortcut_keys)

    def create_shortcut(self, shortcut_keys) -> None:
        parent = self.parent()
        self.shortcut = QShortcut(QKeySequence(shortcut_keys), parent)
        self.shortcut.activated.connect(self.do_stuff)
    
    def do_stuff(self):
        ...


Solution

  • QShortcut inherits from QObject, meaning that it is always shown in the list of children of the parent for which it was created.

    Assuming that the shortcuts have always been created with a parent, just use findChildren(className):

    def create_shortcut(self, shortcut_keys) -> None:
        seq = QKeySequence(shortcut_keys)
        for other in self.parent().findChildren(QShortcut):
            if seq == other.key():
                # already exists, ignore
                return
    
        # create new shortcut
        shortcut = QShortcut(QKeySequence(shortcut_keys), parent)
        shortcut.activated.connect(self.do_stuff)
    

    Note: creating persistent instance attributes is pointless whenever those attributes will be most certainly overwritten.

    Alternatively, just create a list as instance attribute, append new shortcuts to it and always check for them before creating others.