PDA

View Full Version : QColor with style sheets



tommy
26th December 2007, 22:10
I have a question about how to use QColor with style sheets.
Normally I would color my text by doing:



QLabel Label;
Label->setStyleSheet( "color: rgb(100,200,200);" );


Now I'd like to specify the rgb color in QColor format (as shown below) but that won't work:



QLabel Label;
mycolor = QColor(100,200,200);
x1Label->setStyleSheet( "color: mycolor;" );


I think I can not put QColor directly into the stylesheet.
So I also tried color: mycolor.toRgb(); but still didn't get it to work

marcel
26th December 2007, 22:16
So you want to dynamically specify colors... Well, you can't do it like that.
You can do it with a QString and placeholders:


QString style = "color: rgb(%1, %2, %3);";
label->setStyleSheet(style.arg(myColor.red()).arg(myColor .green()).arg(myColor.blue()));

tommy
26th December 2007, 23:06
Thanks Marcel,

I got your code to work but I don't know what the syntax is to combine what you suggested into the same style sheet with the other style declarations. For example both of the style sheet declarations below work but I can't put them together into one. What is the syntax? Thanks a lot!



mycolor = QColor(100,200,200);

QString style = "background: rgb(%1, %2, %3);";

drawButton->setStyleSheet(style.arg(mycolor.red()).arg(mycolor .green()).arg(mycolor.blue()));


drawButton->setStyleSheet(
"color:black; font-size:12px;"
"font-weight:bold;"
);

wysota
26th December 2007, 23:42
With the label colour it would be much simpler to use the palette...

QLabel label;
QPalette palette = label.palette();
palette.setColor(QPalette::Foreground, mycolor);
label.setPalette(palette);

marcel
27th December 2007, 05:37
I got your code to work but I don't know what the syntax is to combine what you suggested into the same style sheet with the other style declarations. For example both of the style sheet declarations below work but I can't put them together into one. What is the syntax? Thanks a lot!

Because the style sheet parameter is a QString, you can use all QString features, like the "+" and "+=" operators:


mycolor = QColor(100,200,200);
QString style = "background: rgb(%1, %2, %3);";
style = style.arg(mycolor.red()).arg(mycolor.green()).arg( mycolor.blue());
style += "color:black; font-size:12px;";
style += "font-weight:bold;";
drawButton->setStyleSheet(style);