Background for QStaticText by html
Solved
General and Desktop
-
Hello
Environment: qt5.12.2, mingw64, windows 10 x64
I get a simple example of widget with QStaticText (out of the documentation) and set the next text:
#include <QWidget> #include <QStaticText> #include <QPainter> class MyWidget: public QWidget { Q_OBJECT; public: MyWidget(QString txt, QWidget *parent = 0) : QWidget(parent), m_staticText(txt) {} protected: void paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawStaticText(0, 0, m_staticText); } private: QStaticText m_staticText; };
auto styleStr = QString(R"(style = "background-color: %1;")").arg("red"); auto formatedStr = QString("<pre %1>%2</pre>").arg(styleStr).arg("some text"); MyWidget w(formatedStr); w.show();
But then I see no background color (only text). When I change QStaticText to QLabel, it works properly. I can change the font for QStaticText, but background-color settings doesn't work..
-
QStaticText is an object that caches text layout information. As such it only accepts html formatting that refers to the text itself, not what it is drawn on (the background). If you want a background just get the text's size() and draw a colored rectangle before you draw the text.
-
@Chris-Kawa thanks 🙏