changing stylesheet dynamically
Asked Answered
C

3

8

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 ?.

Chloral answered 21/3, 2014 at 15:19 Comment(1)
possible duplicate of Are Qt's stylesheets really handling _dynamic_ properties?Carver
E
30

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

Enure answered 8/10, 2014 at 5:33 Comment(3)
This is a nice PyQt example: dgovil.com/blog/2017/02/24/qt_stylesheetsEdee
Link is not workingFriseur
@Friseur fortunately, I've inlined the most important part into the answerEnure
T
1

Had the same problem in PyQT today. None of the suggestions found on SO worked, but what did work in the end is to use the cascading nature of stylesheets. In my application, I had an application-wide stylesheet that would style buttons differently when they are checked:

QToolButton {
    background-color: #12313F;
    background: #12313F;
    color: #DEE8EC;
    spacing: 0px;
    border: none
}

QToolButton[checked="true"] {
    background-color: #5B8AA1;
    background: #5B8AA1;
}

This is set to be the main stylesheet, this is python but hopefully it gets the idea across (I'm reading the stylesheet as a string from style.css):

mainwindow.setStyleSheet(
    pkg_resources.resource_stream(__name__, 'style.css').read())

In my code the checked property of the QAction children of the toolbar might change, and then I want the toolbar to update and that button to be highlighted.

To accomplish this (took lots of trial and error), I override the stylesheet of my toolbar object, which is a child of the main window. It turns out I don't even have to set anything, an empty string is enough:

toolbar.setStyleSheet("")

Et Voila, the toolbar renders correctly. QT 4.8. YMMV in C++ but hopefully it works.

Tva answered 19/5, 2017 at 10:16 Comment(0)
A
0

I had the same experience with C++; in Qt.6.6 a higher level stylesheet set in the creator had no affect on component QLabel, until I added setStyleSheet("") for the individual QLabel. Stylesheet "" is set at the same time as the property in the code.

Almsgiver answered 4/1 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.