1
votes

Its my code. How to assign the values for CSS through variable and the use same in PyQt5 stylesheet ?

    self.label = QLabel("sample")
    self.label.setObjectName("label_1")
    self.label.setStyleSheet(my_stylesheet())

def my_stylesheet():
    return """
    QLabel#label_1{color:red;background-color:blue;}
    """

Instead of direct values (like red, blue), assign it in a variable and how to use it. For ex :

color_1 =red
color_2 = blue
QLabel#label_1{"color:color_1; background-color:color_2;}
2
Use f-string or str.format method eg: f"{{color: {color_1}; background-color: {color_2};}}"Art
not work for metckraomuqnt
Did you use this? f"QLabel#label_1{{color: {color_1}; background-color: {color_2};}}" also in your color_1 =red the red should be a string.Art
@tckraomuqnt are you asking if you can use a "dynamic" variable reference in the stylesheet, so that everytime the value of that variable changes the stylesheet is updated as well? If that's the case, no, you can't: stylesheets are static strings that are evaluated once they're set.musicamante
@Bala hereArt

2 Answers

1
votes

A possible solution is to use property where the Qt stylesheet change is applied in the setter:

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow


class Label(QLabel):
    def __init__(
        self, background=QColor("white"), foreground=QColor("black"), parent=None
    ):
        super().__init__(parent)
        self._background = background
        self._foreground = foreground

        self._change_stylesheet()

    @property
    def background(self):
        return self._background

    @background.setter
    def background(self, color):
        if self._background == color:
            return
        self._background = color
        self._change_stylesheet()

    @property
    def foreground(self):
        return self._foreground

    @foreground.setter
    def foreground(self, color):
        if self._foreground == color:
            return
        self._foreground = color
        self._change_stylesheet()

    def _change_stylesheet(self):
        qss = "QLabel{color:%s;background-color:%s}" % (
            self.background.name(),
            self.foreground.name(),
        )
        self.setStyleSheet(qss)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    label = Label()
    label.setText("Qt is awesome!!!")
    label.setAlignment(Qt.AlignCenter)
    label.setFont(QFont("Arial", 40))

    label.background = QColor("red")
    label.foreground = QColor("blue")

    w = QMainWindow()
    w.setCentralWidget(label)
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())
0
votes

This code doesn't give a direct solution to your problem. But it solves your problem, somehow.

import sys
from PyQt5 import QtWidgets

color_red = "color_red"
color_blue = "color_blue"

backcolor_skyblue = "bcolor_skyblue"
backcolor_lightgreen = "bcolor_lightgreen"

class CssSample(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Css Stylesheet")

        self.label_1 = QtWidgets.QLabel("Sample 1 Label")
        self.label_1.setFixedSize(200,50)
        self.label_1.setProperty("color",color_red )
        self.label_1.setProperty("backcolor",backcolor_skyblue)
        self.label_1.setStyleSheet(my_stylesheet())

        self.label_2 = QtWidgets.QLabel("Sample 2 Label")
        self.label_2.setFixedSize(200, 50)
        self.label_2.setProperty("color", color_blue)
        self.label_2.setProperty("backcolor",backcolor_lightgreen)
        self.label_2.setStyleSheet(my_stylesheet())

        self.vbox = QtWidgets.QVBoxLayout()
        self.vbox.addWidget(self.label_1)
        self.vbox.addWidget(self.label_2)
        self.setLayout(self.vbox)

def my_stylesheet():
    
    return """
    QLabel[color = "color_red"]
    { color : red;font-family: Trebuchet MS; font-style: normal; font-size:12pt; font-weight:700; }
    
    QLabel[color = "color_blue"]
    { color : blue;font-family: Trebuchet MS; font-style: normal; font-size:12pt; font-weight:700;}
    
    QLabel[backcolor = "bcolor_skyblue"]
    { background-color : skyblue}
    
    QLabel[backcolor = "bcolor_lightgreen"]
    { background-color : lightgreen}
    
    QLabel{ background-color: @mycolor;}
    
"""

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainwindow = CssSample()
    mainwindow.show()
    sys.exit(app.exec_())