Important: Please read the Qt Code of Conduct -

Creating dynamic properties with ui elements

  • There are two questions here. First an overview. I'm trying to set stylesheets dynamically via properties. Now for example I have this code:
    @ui->label_auto->setStyleSheet("*[opmode='A'] { background-color: lime } *[opmode='B'] { background-color: red }" );@

    background color is lime


    background color is red

    But the problem is this code only works in the constructor. If I take the 'setProperty' lines to a different function nothing happens.
    Question 1: How can I get that to work?

    Question 2: I'm assuming the way to do it would be to use the Q_PROPERTY macro and define my own properties (if there's a simpler way by all means let me know). But how do I set the properties, using this macro, of a ui-> element? There are no examples of this (after extensive googling).

    Any help would be appreciated.


  • According to the "Style sheet syntax page":

    bq. Warning: If the value of the Qt property changes after the style sheet has been set, it might be necessary to force a style sheet recomputation. One way to achieve this is to unset the style sheet and set it again.

    Repolishing the widget after changing the property also seems to work:
    // or
    qApp->postEvent(ui->label_auto, new QEvent(QEvent::Polish));@

    bq. But how do I set the properties, using this macro, of a ui-> element?

    I'm not sure what you mean by that. But if you declare the property in the window, rather than in a class derived from QLabel, you can set the stylesheet to the window, and add another level to the label selector. You would still have to force the style sheet recalculation, but you can put the code that'll do it in the property setter:
    // this represents the window
    this->setStyleSheet("*[opmode='A'] #label_auto { background-color: lime } *[opmode='B'] #label_auto { background-color: red }" );
    this->setProperty("opmode", A);

    // with
    class YourClass : public QWidget {
    Q_PROPERTY(QString opmode READ opmode WRITE setOpmode)
    QString _opmode;

    void setOpmode(const QString &value) {
        if(_opmode != value) {
            _opmode = value;
    QString opmode() const {
        return _opmode;


    Another way to achieve the same result, if you have only 2 or 3 states would be to use a disabled QCheckBox, and use its checked/unchecked/indeterminate pseudo-states in the stylesheet.

Log in to reply