Dynamic Properties and Stylesheets
- See also the official documentation:
Qt stylesheets make it possible to customize the look of Qt applications without having to master the magic behind Qt styles. From lighter tweaks to the quite complex, stylesheets can do the job. For a fully customized and unique user experience, QtQuick andare a better choice.
When using stylesheets, styles are applied using selectors. For instance, the snippet below gives allwidgets a yellow background color, if this style sheet is set on the form widget or on a widget that contains it. Here, the selector is the word QLineEdit:
There are numerous selectors based on object names, sub-controls, pseudo-states and more. These can be used to change the look of a user interface and also make allwidgets named okButton have green text, and so on.
For dynamic changes in the user interface look, the property value selector can be used in combination with dynamic properties. Dynamic properties were introduced in Qt 4.2 and allow you to assign property values tos for properties that do not exist at compile time. I.e. if you choose to set the a property called urgent to true for a , that property will stick even tough the class does not contain a Q_PROPERTY macro for the property urgent.
Creating a stylesheet selector relying on a dynamic property, e.g. urgent, makes it possible to highlight parts of the user interface in a very dynamic manner. For instance, adding the following rule to the stylesheet above will given anywith the urgent property set to true red text on a yellow background.
This does not have to be limited to QLineEdits though. if the selector was changed from QLineEdit[urgent=true] to [urgent=true], setting the urgent property to true on aor QPushButton will make their texts show in red as well. Basically, any stylesheet aware widget could be turned red using this generic selector.
There are limitations to using this trick. The main one is that the style will not update itself automatically when the value of a property referenced from the style sheet changes. Instead, you must manually trigger an update of the visual appearance of a widget when a styled property changes. For example:
Note that this must be done in the widget to which the style was applied.accepts either a QWidget or a QApplication as a parameter.