Issue
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;}
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.