Qt: Using custom Style Sheet property



Qt Style Sheet is a great way for quickly set the appearance of GUI controls using CSS style properties. There is a large set of Qt Style Sheet properties available for every type of widgets. However, in case you need to use this same way for set a property non available in the standard set, here a small example about how to do it.


Basically a Style Sheet property is a flag with only two possible values: true or false. Is possible to set style sheet properties for both states using the following syntax:

*[myCustomProperty="true"] 
{
background-color: red; 
......
}

*[myCustomProperty="false"] 
{ 
background-color: green;
......
}

The asterisk set the property as "global" for each level of widgets. In case you need to point the property to some specific widget the rule of Qt style sheet is the same as follow:

#MyWidgetName [myCustomProperty="true"] 
{ 
......
}

Once you have registered the styles connected to the two states (or just one, there is no need to set both, just the only you need) you can "apply" the styles by manually set the property from inside your widget object code:

setProperty("myCustomProperty", [true/false]);

Or outside after widget creation using pointer as follow:

QFrame *myFrame = new QFrame(this);
myFrame->setProperty("myCustomProperty", [true/false]);

Please note this call will have effect only during widget initialization phase and before the widget is painted at screen. If you want to apply the styles "on the fly" for example in consequence of a mouse pression event you need to add some lines as follow:

setProperty("myCustomProperty", [true/false]);
style()->unpolish(this);
style()->polish(this);

This will force the Qt engine to repaint the widget using the new styles just set.

1 Comments:

Hey, works great! This helped me to build a custom widget similar to layer selection in image manipulation programs.

Anonymous
March 24, 2015 at 9:22 AM comment-delete

Post a Comment