'Custom Styles (css)

Good afternoon.

I am learning the PyQt (5.15.2) framework along with Python (3.8.6) and here is the question.

I have 25 buttons (5x5) to display and select letters of the alphabet and a 'start' button. After the window is formed, I have to fill all the buttons with a different random color. This process is repeated each time the “start” button is pressed.

After clicking on the button with the letter, I should get its color and position. I get "font: 44px; background: yellow;". Is there any way to get just the color value?

How can this problem be solved?

Sincerely, Vladislav

Thank you.

enter code here
    
import random  
import sys  
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton,
                             QGridLayout, QHBoxLayout, QVBoxLayout) 


class MyApp(QWidget): 
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setStyleSheet('font: 44px; background: lightgray;')
        self.my_btn = []
        self.my_color = ['yellow', 'darkseagreen', 'dodgerblue', 'darkorange', 'lightblue']
        self.bk = list('QWERTYUIOPLKJHGFDSAZXCVBN')

        start_btn = QPushButton('Start')
        start_btn.clicked.connect(lambda state, x=1: self.mystart(x))
        self.my_ini = 1

        hbox = QHBoxLayout()
        hbox.addWidget(start_btn)
        grid = QGridLayout()
        for i in range(25):
            btn = QPushButton(self.bk[i])
            self.my_btn.append(btn)
            y, x = divmod(i, 5)
            grid.addWidget(self.my_btn[i], y, x)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addLayout(grid)
        self.setLayout(vbox)
        
        self.show()

    def showmy(self, nom, clr):
        print('#', nom,self.my_btn[nom].text(), 'CLICK-color ->', self.my_btn[nom].styleSheet())

    def mystart(self, rz):
        for i in range(25):
            random.shuffle(self.my_color)
            clr = self.my_color[0]
            self.my_btn[i].setStyleSheet(f'font: 44px; background: {clr};')
            if self.my_ini == 1:
                self.my_btn[i].clicked.connect(lambda state, x=i, c=self.my_btn[i].styleSheet(): self.showmy(x, c))
        self.my_ini = 0

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source