Two Shortcuts for One Button in PyQt

Viewed 965

In PyQt, how would you tie in two shortcuts for one button? I have scoured the QT documentation and StackOverflow, but the only thing I found was Two shortcuts for one action, but that was for QT and I could not wrap my head around that.

1 Answers

The only difference is that instead of using QList you should use the list:

from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        menubar = self.menuBar()
        menu = menubar.addMenu("File")
        foo_action = menu.addAction("foo")
        foo_action.setShortcuts(["Ctrl+1", "Ctrl+S"])
        foo_action.triggered.connect(self.on_triggered)

    @QtCore.pyqtSlot()
    def on_triggered(self):
        print("on_triggered")

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

In the case of QWidgets they do not have the setShortcuts() method, so one option is to use QShortcuts:

for sequence in ("Enter", "Return",):
    shorcut = QtWidgets.QShortcut(sequence, self.pushButton_eq)
    shorcut.activated.connect(self.pushButton_eq.animateClick)
Related