【问题标题】:How to assign keys to QPushButtons created in a Loop如何将按键分配给在循环中创建的 QPushButton
【发布时间】:2021-03-15 08:56:51
【问题描述】:

使用 PYQT5,我使用 QPushButton 创建了一个按钮网格,如下所示:

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)

我还创建了一个键数组,我认为我可以使用数组来使用 setShortcut,这样当我按下一个键时,它只会触发一个按钮。在使用循环创建按钮时,我很难理解如何实现此功能。

另外,当我尝试这个时,我得到了这个错误:

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'

我不明白意思。

【问题讨论】:

  • 正如错误清楚地表明的那样,您不能将字符串的 list (这是self.binding 是)设置为快捷方式,因为setShortcut 期望作为任何参数一个 QKeySequence、QKeySequence.StandardKey、str 或 int(一个 QtCire.Qt.Key 枚举)。

标签: python for-loop pyqt5 key-bindings qpushbutton


【解决方案1】:

使用zip函数:

for button, shortcut in zip(self.pads, self.binding):
    button.setShortcut(shortcut)

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 2018-05-16
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2019-02-25
    • 2022-01-17
    相关资源
    最近更新 更多