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_())
str.format
method eg:f"{{color: {color_1}; background-color: {color_2};}}"
– Artf"QLabel#label_1{{color: {color_1}; background-color: {color_2};}}"
also in yourcolor_1 =red
the red should be a string. – Art