-1

Using PYQT5, I have created a grid of buttons using QPushButton, as shown below:

self.pads = []
        self.binding = ['a','b','c','d','e','f','g','h','i'] #add quota for binding
        for r in range(3):
            for c in range(3):
                pad = QPushButton()
                pad.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
                pad.setStyleSheet("QPushButton { background-color: lightcoral }"
                        "QPushButton:Hover { background-color: lightpink }"
                      "QPushButton:pressed { background-color: indianred }" )
                self.pads.append(pad)
                padLayout.addWidget(pad, r, c)
                padLayout.setSpacing(30)
        for i in self.pads:
            i.setShortcut(self.binding)

I have also created an array of keys, which I thought I would be able to use setShortcut using the array in order so that when I press a key, it would trigger only one of the buttons. I'm having difficulty understanding how to make this function as I created the buttons, using a loop.

Also, when I try this, I get this error:

Traceback (most recent call last):
  File "/Users/ricochetnkweso/PycharmProjects/pythonProject/Crash_Test.py", line 160, in <module>
    window = mainWindow()  # After Qapp instance but before event loop
  File "/Users/ricochetnkweso/PycharmProjects/pythonProject/Crash_Test.py", line 60, in __init__
    i.setShortcut(self.binding)
TypeError: setShortcut(self, Union[QKeySequence, QKeySequence.StandardKey, str, int]): argument 1 has unexpected type 'list'

Which I don't understand the meaning.

  • As the error clearly says, you cannot set a *list* of strings (which is what `self.binding` is) as a shortcut, since `setShortcut` expects as argument any of a QKeySequence, QKeySequence.StandardKey, str or int (a QtCire.Qt.Key enum). – musicamante Mar 15 '21 at 09:04

1 Answers1

0

Use the zip function:

for button, shortcut in zip(self.pads, self.binding):
    button.setShortcut(shortcut)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241