Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dynamic Property for stylesheet



  • I need to change the color of a button dynamically. I tried this based on a property "orderstatus".
    Another approach didn't work for me too: https://stackoverflow.com/questions/21685414/qt5-setting-background-color-to-qpushbutton-and-qcheckbox.
    But i would prefer a way, which allows me to set the specific color in the stylesheet.

    My code for the property approach:

    //Code in UIOrder.cpp
    void UIOrder::statChanged(OrderStatus::Enum stat)
    {
      m_ui.btnStatus->setProperty("orderstatus", stat);
      int status = m_ui.btnStatus->property("orderstatus").toInt();
      m_ui.btnStatus->repaint();
    }
    
    /*Code in stylsheet*/
    *[orderstatus="1"]{	background: rgb(   0,   0, 255, 255); }
    *[orderstatus="2"]{	background: rgb(   0, 255,   0, 255); }
    /*...*/
    

    int status has the right value after executing, so i guess, the property was set sucessfully.
    But the button doesn't change the color and keeps the first set color (first called when OrderStatus::Enum stat == Sent(1) )
    The button stays blue, but it should be green.

    Thanks for your help : )


  • Lifetime Qt Champion

    Hi and welcome to the forums

    Properties need some extra code when used with stylesheets:
    Please see
    https://wiki.qt.io/Dynamic_Properties_and_Stylesheets

    Try the last part
    myLineEdit->setProperty("urgent", true);
    myLineEdit->style()->unpolish(myLineEdit);
    myLineEdit->style()->polish(myLineEdit);

    m_ui.btnStatus as myLineEdit. ofc :)



  • @mrjj Thank you very much. I've tried to solve this problem for hours, but the solution was so easy.


Log in to reply