changing stylesheet dynamically

2020-02-13 01:49发布

问题:

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

回答1:

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



回答2:

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.