c++qtqtstylesheetsqtwidgets

Can I change the style of a QObject by changing the ObjectName via stylesheets?


I recently learned about the nice possibility to style objects in Qt with a stylesheet. Now I want to change the background color of a QFrame after a specific event happened. So I set up two entries:

QFrame#ColorA {
    background-color: #FFFFFF;
}

QFrame#ColorB {
    background-color: #B2D235;
}

and gave the QFrame the ObjectName ColorA and it gets displayed perfectly fine. But when said event happens, and I set the ObjectName to ColorB, nothing in the UI changes.

I know that I can change the color by setting the stylesheet to background-color: #B2D235, but I thought there must be a nicer way through the stylesheet.


Solution

  • For the style modification to take effect, you have to call unpolish()/polish().

    So when your event happens, add something like (if you call it directly from QFrame subclass)

    style()->unpolish(this);
    style()->polish(this);
    

    or like this

    style()->unpolish(ui->your_frame);
    style()->polish(ui->your_frame);
    

    if you call it from a class that contains your QFrame (I suppose that your QFrame is defined in a UI file).