Using variables in qt StyleSheets

What you're trying to accomplish simply isn't possible using pure Qt style sheets.

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

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

Unfortunately this has several drawbacks (inability to preview in designer, changing code rather than a style sheet), but it's about as close as you can get to what you're trying to achieve with Qt.


You could build your own tiny Sass quite easily:

1.Create a text file with definitions of variables. Use simple format like this:

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

2.In qss file use variable names:

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

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

4.Apply the preprocessed qss in the app.

This is the simplest solution. You can change both definition file and qss file outside the app and apply it without recompilation of code.