1

I'm using PySide2 and I want to have multiple shortcuts that carry out the same function but also would depend on which key was pressed.

I tried to link the functions as such inside a QMainWindow:

QtWidgets.QShortcut(QtGui.QKeySequence("1"),self).activated.connect(self.test_func)
QtWidgets.QShortcut(QtGui.QKeySequence("2"),self).activated.connect(self.test_func)

Such that they both execute this function.

def test_func(self, signal):
    print(signal)

Hoping that print("1") happens when the key "1" is pressed and print("2") happens when the second key is pressed. When I tried running this and press the keys 1 and 2, I get this error:

TypeError: test_func() missing 1 required positional argument: 'signal'

How can I accomplish this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Teacher Mik
  • 147
  • 3
  • 9

1 Answers1

2

The activated signal does not send any information so the one option is to obtain the object that emits the signal (ie the QShortcut) to obtain the QKeySequence, and from the latter the string:

from PySide2 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        QtWidgets.QShortcut(QtGui.QKeySequence("1"), self, activated=self.test_func)
        QtWidgets.QShortcut(QtGui.QKeySequence("2"), self, activated=self.test_func)

    @QtCore.Slot()
    def test_func(self):
        shorcut = self.sender()
        sequence = shorcut.key()
        print(sequence.toString())

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks for this, it works. I greatly appreciated it! I do have a follow-up question as it didn't completely work in the context of the entire code I am developing. If you can, please check it out [here:](https://stackoverflow.com/questions/55195979/pyside2-finding-out-which-qkeysequence-was-pressed-2) – Teacher Mik Mar 16 '19 at 10:58