QPlainTextEdit使用HTML方式设置颜色

QPlainTextEdit可使用HTML方式设置文本颜色,代码如下:

#include 

const QString& makeText()
{
  static const QString texts[] = {
    QString::fromLatin1("Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua."),
    QString::fromLatin1("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat."),
    QString::fromLatin1("Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."),
    QString::fromLatin1("Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
    QString::fromLatin1("Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi."),
    QString::fromLatin1("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat."),
    QString::fromLatin1("Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat."),
    QString::fromLatin1("Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum."),
    QString::fromUtf8("HTML Meta-Characters: < > & \" ' and\nnon-ASCII characters: \xc3\xa4 \xc3\xb6 \xc3\xbc \xc3\x9f \xc3\x84 \xc3\x96 \xc3\x9c")
  };
  enum { NTexts = sizeof texts / sizeof *texts };
  return texts[qrand() % NTexts];
}

const QString formatHtml(const QString &qText, const QColor &qColor)
{
  QString qHtmlText
    = QString::fromLatin1("

"); for (const QChar qChar : qText) { switch (qChar.unicode()) { case '<': qHtmlText += QString::fromLatin1("<"); break; case '>': qHtmlText += QString::fromLatin1(">"); break; case '&': qHtmlText += QString::fromLatin1("&"); break; case '"': qHtmlText += QString::fromLatin1("""); break; case '\'': qHtmlText += QString::fromLatin1("'"); break; case '\n': qHtmlText += QString::fromLatin1("
"
); break;//不确定是否有效 default: qHtmlText += qChar; // everything else unchanged } } qHtmlText += QString::fromLatin1("

"
); return qHtmlText; } int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup GUI QPlainTextEdit qTxtEdit; qTxtEdit.show(); // install signal handlers QTimer qTimer; qTimer.setInterval(1000); // 1000 ms = 1 s QObject::connect(&qTimer, &QTimer::timeout, [&]() { const QColor qColor(qrand() % 4 == 1 ? 0xFF0000 : 0x000000); qTxtEdit.appendHtml(formatHtml(makeText(), qColor)); }); qTimer.start(); // runtime loop return app.exec(); }

WIN10系统下显示效果:

你可能感兴趣的:(QT)