Qt Snippet: QLabel with text shadow


In case you want to show your text labels a little more "beautiful" to see a little trick is to add shadow to text and create a 3D text like. In the CSS standard set exist a tag called text-shadow able to apply such effect automatically. Unfortunately this feature is not supported by the Qt QSS stylesheet set so we need to found another way.


Common solution is to derivate the QLabel class and overwrite the paint function. To make text shadow you have to paint your text in a white or light gray color and then paint again the text in dark color just around one pixel moved as example below:
QRect SectionRect(0, 0, 200, 200);
QString MyText("Shadow Text");
painter->setPen(Qt::white);
painter->drawText(SectionRect.adjusted(1,1,1,1), Qt::AlignHCenter | Qt::AlignVCenter, MyText);
painter->setPen(Qt::black);
painter->drawText(SectionRect, Qt::AlignHCenter | Qt::AlignVCenter, MyText);

SectionRect is the area inside you want to paint the text that will be centered horizontally and vertically. The code itself is quite easy, the most long  part is to develop all the code for class derivation. Fortunately it exist another way more fast for get a very similar effect by using the QGraphicsDropShadowEffect object. Using the following code will add to you QLabel text a little shadow making a 3D effect:

QGraphicsDropShadowEffect *pLabelTextShadowEffect = new QGraphicsDropShadowEffect(this);
pLabelTextShadowEffect->setColor(QColor("#BBBBBB"));
pLabelTextShadowEffect->setBlurRadius(0);
pLabelTextShadowEffect->setOffset(1, 1);
pMyLabel->setGraphicsEffect(pLabelTextShadowEffect );

The result is the following:


As you can see the effect is quite good and the code required is very short. Based to the background color of the widget or dialog it will be necessary to set correctly the shadow color to get a better result. You just only have to try.

0 Comments:

Post a Comment