Using variables in qt StyleSheets

Is it possible to assign a variable name to hex / rgb numbers in a .qss file. For eh

myColor = #FFCC08 QPushButton { background-color: myColor;} 

So that I can define the variable at the top of the stylesheet and use the variable name needed instead of using the hex code. Also, if I need to change the color, then I need to change in one place, and it will be reflected in the file.

I also searched for Saas , but I don’t know how it can be used in qt.

Thanks:)

+8
qt qss
source share
2 answers

You can easily create your own tiny sass:

1. Create a text file with variable definitions. Use a simple format:

 @myColor = #FFDDEE @myColor2 = #112233 @myWidth = 20px 

2. In the qss file, use the variable names:

 QPushButton { background-color: @myColor; min-width: @myWidth; } 

3.Open both files and for each variable in the definition file change its appearance in the qss file with the value (string) from the definition file. This is a simple string replacement.

4.Apply the pre-processed qss in the application.

This is the simplest solution. You can modify the definition file and qss outside the application and apply it without recompiling the code.

+9
source share

What you are trying to do simply is not possible using pure Qt style sheets.

You can achieve a similar effect by modifying and reloading your stylesheets from C ++ code, for example:

 QString myColor = "#FFCC08"; QString styleSheet = "QPushButton { background-color: %1;}"; ... myWidget->setStyleSheet( styleSheet.arg(myColor) ); 

Unfortunately, this has several drawbacks (the inability to preview in the designer, changing the code, not the stylesheet), but it is about as close as you can achieve what you are trying to achieve with Qt.

+3
source share

All Articles