Text Shadows in QLabel Snippets

https://falsinsoft.blogspot.com/2015/10/qt-snippet-qlabel-with-text-shadow.html

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.









https://wiki.qt.io/Text_Shadows_in_QLabel_Snippets

Easy way to add shadows to text in QLabel

include headers <QGraphicsDropShadowEffect>

// For an example we have QLabel called userName
// set blur to 0, and setOffset to 1,1 and color for smooth look must be little butter darker then text color

QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this);
effect->setBlurRadius(0);
effect->setColor(QColor("#EEEEEE"));
effect->setOffset(1,1);
ui->userName->setGraphicsEffect(effect);

猜你喜欢

转载自blog.csdn.net/zx249388847/article/details/80905336