0
votes

Okay what I am aiming for is a way to set the background color of a QGroupBox without overwriting any other styles that might be set on that object before.

Intuitively I'd use a QPalette for doing this but since my application is using stylesheets, I can't use palettes (using them just has no effect whatsoever).

Thus I am left with setting the background color via stylesheets. If the only style I want to set this was the background color, that'd be easy:

myBox->setStyleSheet("background-color: red;");

This however will overwrite all stylesheets that have been set on myBox before this call. In my case I am setting the font-size at a different place but on the same object and also via stylesheets.

So the next idea is to append to the existing stylesheet like this:

myBox->setStyleSheet(myBox->styleSheet() + " background-color: red;");

That's working so far, but the problem is that I want to change the background color rather frequently (not only once or twice) and while using the above method for the successive color changes (provided I append to the the stylesheet instead of prepending to it), it makes the stylesheet continually grow larger and larger. Furthermore I'd eventually be setting the background color hundreds of times in one and the same stylesheet just so I can have the currently active color as the final value. Parsing this seems like a huge waste of computational resources.

I am therefore looking for a way to change the background color of my box only. The method must preserve all attributes that are currently set in a stylesheet on my object (except the background color of course) and should not make the stylesheet grow to infinity without actually adding new information to it. And ideally the solution is not cascading the background color to children of my box.

How is something like this usually handled within Qt?


A possible solution that I could come up with would be to create a wrapper around the QGroupBox and introduce the style attributes I want to set on it as member variables and then creating the stylesheet based on the values of the member variables each time any of them changes.

This seems like a solution that doesn't scale very well and to me it seems like there should be a standard solution to this that doesn't require manually creating such wrappers every time...

1

1 Answers

0
votes

You can have a selector like on CSS, example below:

QGroupBox { background-color: #fbca10;}

Or if you want more specific you can have the accessibleName as the selector also, example:

QGroupBox[accessibleName="mybox"] { background-color: #fbca10;}

the accessibleName is property on QWidget. You can set it on qt designer or by code.