changing stylesheet dynamically

做~自己de王妃 提交于 2019-11-29 11:36:33

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!