PDA

View Full Version : Passing variable to stylesheet in runtime



ndev
22nd February 2015, 14:54
Hi,
is it possible to pass variable from application to stylesheet in runtime ?
For example, set background image for button:
QPushButton{
background-image: buttonImage;
background-repeat: no-repeat;
background-position: left;
}
where buttonImage is set like setProperty("buttonImage", "url(:/down.png)");

ChrisW67
22nd February 2015, 20:41
There is some ability to use dynamic properties to change styles on-the-fly
http://qt-project.org/wiki/DynamicPropertiesAndStylesheets

This approach may not be suited to arbitrary changes like the one you are after. If you are trying to change the image on the button based on whether it is pushed/not-pushed on/off etc then you should look at the QIcon class ability to hold multiple images for different states.

ndev
23rd February 2015, 07:30
I know about property selector, but I need more advanced control to use different images for buttons in runtime.
QIcon doesn't fit because I'd like to place image on left button side, not on center. Also I need at least 2 states: default and hover.

wysota
23rd February 2015, 07:42
Have you considered using a custom style instead of stylesheets?

Santosh Reddy
23rd February 2015, 12:45
Will this help


QPushButton button;

QString styleSheetTemplate = "QPushButton {"
"background-image: %1;"
"background-repeat: no-repeat;"
"background-position: left;"
"}";

button.setProperty("buttonImage", "url(:/down)");

QString styleSheet = styleSheetTemplate.arg(button.property("buttonImage").toString());

button.setStyleSheet(styleSheet);

ndev
23rd February 2015, 12:58
Main idea was to have only one stylesheet for whole application with ability to change some values dynamically, but as I see currently this isn't possible.
So, I've made workaround, by overriding stylesheet for button with custom background-image property.