python - Qt Python - 在按钮列表中更改所有按钮的颜色,直到单击的按钮为止

标签 python pyside pyside2 signals-slots qpushbutton

我有一个如下所示的 Qt 按钮列表:self.buttons = [button1,button2,button3] 当单击一个按钮时,我希望列表中单击的按钮之前的所有按钮都更改其颜色。

我做了一个 for 循环来遍历按钮并将每个按钮连接到我定义的函数,但是当我单击按钮并且连接的函数运行时,它不知道按钮列表中按钮的顺序,因此我无法让其他按钮改变颜色。我想我需要以某种方式将按钮的 id 或其他内容传递给函数,但无法弄清楚如何执行此操作,因为我无法将参数传递给连接的函数: self.button1.clicked.connect(self.更改颜色)

Qt 本身会自动将一个参数传递给连接的函数,但它是主窗口,对我的情况没有帮助:

def change_color(i):  
    print(i)

点击时输出:

<__main__.Main_Window(0x6000019e0000, name="MainWindow") at 0x11df5ccc0>

最佳答案

将所有按钮添加到 QButtonGroup (使用他们的索引作为id)然后连接到组的idClicked signal 。这将自动发送单击按钮的索引。下面是一个简单的演示,展示了如何做到这一点:

enter image description here

import sys, random
from PySide2 import QtCore, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)
        self.buttons = QtWidgets.QButtonGroup(self)
        for index in range(1, 11):
            button = QtWidgets.QPushButton(f'Button {index}')
            self.buttons.addButton(button, index)
            layout.addWidget(button)
        self.buttons.idClicked.connect(self.handleButtons)

    def handleButtons(self, index):
        color = f'#{random.randint(0, 0xFFFFFF):06x}'
        for index in range(1, index):
            self.buttons.button(index).setStyleSheet(f'background: {color}')

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setWindowTitle('Test')
    window.show()
    sys.exit(app.exec_())

关于python - Qt Python - 在按钮列表中更改所有按钮的颜色,直到单击的按钮为止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70776344/

相关文章:

python - XGBClassifier num_class 无效

python - PDF 与 QWebView : missing refresh/repaint after loading

python - Qwidget 背景颜色改变时程序随机崩溃

python - 区分 PySide 中的信号源

python - 将 Pyqtgraph 嵌入到 PySide2

python - QLayout 中的重叠小部件

python - 显示具有覆盖率的未测试函数

python - "site"不是一个包

python - 从其他表访问数据 - Django Rest Api 中的外键 - 未知列

qt - PySide/PyQt根据minimumSize截断QLabel中的文本