how to add color, background-color value through variable in PyQt5?

Question:

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;}
Asked By: tckraomuqnt

||

Answers:

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_())
Answered By: eyllanesc

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_())
Answered By: Bala

Instead of using complicated python codes or creating custom classes, you can do something like this:

primary_color = '#000000'
secondary_color = '#ffffff'

stylesheet = """
QMainWindow {
    background-color: $primary_color;
}

QDialog {
    background-color: $secondary_color;
}
""".replace('$primary_color', primary_color)
    .replace('$secondary_color', secondary_color)

self.setStyleSheet(stylesheet)

First, create variables for any colors you use in your style. Then in your stylesheet variable, you can use a string like $primary_color instead of your color.
Then at the end, replace this string with the variable that holds your color.

After that, you can set this style as the page stylesheet.

Answered By: mimskydo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.