changing stylesheet dynamically

Ghilas BELHADJ picture Ghilas BELHADJ · Mar 21, 2014 · Viewed 17.5k times · Source

I'm trying to change the style of my QLabel using a dynamic property since we can target this property in QSS like this:

QLabel[foo = "warning"]{ color: red; }
QLabel[foo = "success"]{ color: green; }

the stye of my label does update when I use the QApplication::setStyleSheet() but does not seems to work when I change the value of the property.

label = new QLabel( this );
label->setText( "some text" );
label->setProperty( "foo", "warning");

// after some event
label->setProperty( "foo", "success" );
// the label's color should be green now

did I missed something, or the style change can just not work this way ?.

Answer

mofr picture mofr · Oct 8, 2014

Wherever we are changing the property we need to add the following code to trigger an update

label->setProperty("foo", "success");
label->style()->unpolish(label);
label->style()->polish(label);
label->update();

http://qt-project.org/wiki/DynamicPropertiesAndStylesheets