簡體   English   中英

Qt Python - 在按鈕列表中更改所有按鈕的顏色,直到被點擊的那個

[英]Qt Python - in a list of buttons change color of all buttons up until the one that was clicked

我有一個 Qt 按鈕列表,如下所示: self.buttons = [button1, button2, button3]單擊一個按鈕時,我希望列表中單擊的按鈕之前的所有按鈕都更改其 colors。

我做了一個for循環來遍歷按鈕並將每個按鈕連接到我定義的function,但是當我單擊一個按鈕並且連接的function運行時,它不知道按鈕列表中按鈕的順序,因此我不能使其他按鈕更改 colors。 我在想我需要以某種方式將按鈕的 id 或其他東西傳遞給 function 但不知道該怎么做,因為我無法將 arguments 傳遞給連接的self.button1.clicked.connect(self.change_color)

ZE8801102A40AD89DDCFDCAEBF008D25Z 本身會自動將一個參數傳遞給連接的 function,但它是主要的 window,它對我的情況沒有幫助:

def change_color(i):  
    print(i)

Output 點擊時:

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

將所有按鈕添加到QButtonGroup (使用它們的索引作為 id),然后連接到組的idClicked 信號 這將自動發送單擊按鈕的索引。 下面是一個簡單的演示,展示了如何做到這一點:

在此處輸入圖像描述

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_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM