15

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
waterd
  • 603
  • 1
  • 7
  • 23

3 Answers3

17

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(……);")) );
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • But it doesn't work when I have to use styles like `QPushButton:pressed{}`. Any better way to figure it out? – waterd Mar 20 '16 at 04:32
10

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.

  • 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. –  Jul 26 '16 at 03:54
0

By using double column for the second entry.

ui->pushButton_2->setStyleSheet(
            "QPushButton{background-color:red;color:white}\
             QPushButton::hover{color:black}");
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
vk3who
  • 349
  • 2
  • 7