Thursday, April 26, 2007

QStyleSheet

Yesterday I thought I can be a bit artistic and improve the KLettres input widget (which is a QLineEdit). So I looked at QStyleSheet and after lots of trials I found out that it cannot take any variable. You have to set
background-color: rgb(202, 217, 84);
and you cannot set
background-color: rgb(m_theme->letterInputColor());
OK, I thought I'll set the nice round corners and border width with QStyleSheet and the colors with QPalette. No luck, QStyleSheet overrides QPalette, no way you can use both.
Pino cleaned my code recently and put everything related to themes in one class in order to manage that easier. So if I use QStyleSheet I'll have to hardcode the colors in the KLettresView class...

You can see on the left the normal widget used with QPalette and on the right the widget with a QStyleSheet applied which allows the rounded corners and the border width to be customized.




The stylesheet code looks like this:
m_letterEdit->setStyleSheet("border-style: solid; color: rgb(141, 80, 17); border-color: rgb(141, 80, 17); background-color: rgb(196, 189, 94); border-bottom-right-radius:10; border-radius: 15px; border-width: 3px");
where m_letterEdit is my QLineEdit.

Note that you can easily set stylesheets in Qt Designer by right clicking on the widget and choose "Change stylesheet..." then write your stylesheet attributes in the field. The dialog checks that they are valid.

4 comments:

Anonymous said...

Hi there Annma!,

Good to see you improving klettres with nice stylesheet additions.

Though I am not yet an advance C++ coder I think the next thing would be possible:

m_letterEdit->setStyleSheet(" background-color: rgb(".m_theme->letterInputColor()."); border-bottom-right-radius:10;
");

This way the output of m_theme->letterInputColor() is added in the string that gets parsed by m_letterEdit->setStyleSheet().

I might not be completely right, but it works this way in a lot of other languages.

Niels

annma said...

Hi Niels,

Thanks for your help but unfortunately it does not work. The rgb() value takes
rgb(255,255,255); but not
rgb(QColor::red(), QColor::green(), QColor::blue());
even if those are the same numbers than above.

It seems to me quite a severe limitation in the use of QStyleSheet.

Volodymyr Kuznetsov said...

What about something like this:

int r, g, b;
m_theme->letterInputColor().getRgb(&r, &g, &b);
m_letterEdit->setStyleSheet(QString("color: rgb(%1, %2, %2);").arg(r).arg(g).arg(b));

annma said...

YEEPEE That did it!

Thansk a lot Vladimir and Niels, I think saw it in IRC :)

There's no limitations in QStyleSheet, only in my coding knowledge!