Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing stylesheet dynamically

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

like image 314
Ghilas BELHADJ Avatar asked Mar 21 '14 15:03

Ghilas BELHADJ


2 Answers

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

like image 85
mofr Avatar answered Sep 30 '22 06:09

mofr


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.

like image 24
izak Avatar answered Sep 30 '22 06:09

izak