PDA

View Full Version : Change Stylesheet Using Dynamic Property



stefanadelbert
2nd July 2010, 02:24
I'm trying to use a dynamic property to change a style for a QPushButton.

I have something like the following:

C++


// Create button with dynamic property
button = new QPushButton(this);
button->setObjectName(QString::fromUtf8("MyButton"));
button->setProperty("myProperty", "rank1");
// Button background should be red now
...
// Change the property
button->setProperty("myProperty", "rank2");
// The button's background colour should be blue now


QSS


QPushButton#MyButton[myProperty="rank1"] { background: red; }
QPushButton#MyButton[myProperty="rank2"] { background: blue; }


This does work to a certain degree. If I call QApplication::setStyleSheet() after updating myProperty, the style does update correctly. But the style is not updating correctly when I change the property. Is it incorrect to expect the button's background colour to change dynamically when the "myProperty" dynamic property is changed?

stefanadelbert
2nd July 2010, 02:40
I found this post from a while back: http://www.qtcentre.org/archive/index.php/t-25747.html. It seems that the stylesheet needs to be reapplied after the dynamic property is changed.

Is there a way to tell a QWidget to reapply its stylesheet rather than calling QWidget::setStyleSheet()? It would be inefficient to call QApplication::setStyleSheet() each time a property on some QWidget changes, particularly seeing that the stylesheet itself has not actually changed. Ideally I would just like the particular QWidget in question to adjust (repaint) itself based on its current stylesheet.

mdomke
20th August 2010, 23:46
I ran into the same problem. The documentation somehow suggests to use dynamic properties to style your widgets but this only works at initialization time or when you call setStyleSheet explicitly after you have altered the property's value. I'm actually doing a



button->setStyleSheet(button->styleSheet())


after each property change.

stefanadelbert
26th August 2010, 00:23
This is exactly what I found. It does somewhat defeat the purpose of dynamic style properties, but it's still better than having to recreate the stylesheet every time!

Lykurg
26th August 2010, 07:48
It's just a wild guess: Does it help if you define a NOTIFY signal for your property?