How to add style via setStyleSheet() without losing the original style(s) in Qt?
Asked Answered
D

3

16

I know I can use setStyleSheet() to set styles in Qt. But when I use setStyleSheet() twice, the first styles are lost, which are set by first use of setStyleSheet().

For example,

setStyleSheet("QLabel{color:red;}");
setStyleSheet("QLabel{border-image:url(……)}")

When I set border-image, the red color property lost.

I tried to solve it by using:

setStyleSheet(styleSheet()+QString("QLabel{border-image:url(……)}"));

but it was the same that only the border-image property existed.

Must I add every style property when I use setStyleSheet(), although that I set it before.

Is there a way to apply this twice without overwriting prior styles?

Daggett answered 6/5, 2014 at 8:49 Comment(0)
M
18

You can set stylesheets without QLabel tag:

setStyleSheet("color:red;");

After setting one stylesheet property, you can add another property like:

setStyleSheet( styleSheet().append(QString("border-image:url(……);")) );
Magician answered 6/5, 2014 at 9:23 Comment(1)
But it doesn't work when I have to use styles like QPushButton:pressed{}. Any better way to figure it out?Daggett
M
11

This is in response to your comment on the accepted answer.

You can prevent overwriting stylesheets properties by setting the constant values to the parent (permitting that the parent's style isn't being changed dynamically as well). Only set the values that you change with C++ to the child item.

parentWidget->setStyleSheet( "QLabel#yourLabel { color:red; }" );
yourLabel->setStyleSheet( "QLabel { border-image:url(...) };" );

This will retain all of the parents properties that have been set on the widget when you change the widget's stylesheet.

Furthermore, this removes the case of a very large string, which is possible in the accepted answer. Frequent changes will inefficiently append the string with previously defined styles that will not be used.

Maemaeander answered 26/7, 2016 at 3:53 Comment(1)
This is applicable when using Qt Designer as well. My personal preference of styling when the widget must be changed by code is setting the constant values in Qt Designer to the parent with the corresponding widget type tags and object name tags. Simply use the second line of code to set to the child, and no previous properties will be lost.Maemaeander
U
1

By using double column for the second entry.

ui->pushButton_2->setStyleSheet(
            "QPushButton{background-color:red;color:white}\
             QPushButton::hover{color:black}");
Unbeaten answered 21/11, 2019 at 2:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.