Question

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?

Was it helpful?

Solution

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(……);")) );

OTHER TIPS

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.

By using double column for the second entry.

ui->pushButton_2->setStyleSheet(
            "QPushButton{background-color:red;color:white}\
             QPushButton::hover{color:black}");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top