qt plaintextedit change message color

ε祈祈猫儿з 提交于 2020-06-28 07:38:44

问题


I'm trying to color a text depending on message, i tried a lot of stuff but they change all text color not just the message that i need , exactly that one that's an error.

if(Something)
    text = tr("");
if(SomethingElse)
    text = tr("");

ui->plainText->appendPlainText(text);

回答1:


From Qt. doc. about QPlainTextEdit:

Text can be formatted in a limited way, either using a syntax highlighter (see below), or by appending html-formatted text with appendHtml().

In the case of OP, I would recommend the latter.

This is done by surrounding the plain text with minimal HTML-markup:

<p style='color: #ff0000'> ... </p>

Another issue is that the plain text may contain characters which have meta-meaning in HTML, literally: < > & " '. To consider these, I added a simple formatter which transforms these to the resp. HTML entities.

Btw. it transforms "\n" to "<br/>" which may or may not be useful.

My sample testQPlainTextEdit-Colored.cc:

#include <QtWidgets>

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("<p style='color: ")
    % qColor.name(QColor::HexRgb)
    % QString::fromLatin1("'>");
  for (const QChar qChar : qText) {
    switch (qChar.unicode()) {
      case '<': qHtmlText += QString::fromLatin1("&lt;"); break;
      case '>': qHtmlText += QString::fromLatin1("&gt;"); break;
      case '&': qHtmlText += QString::fromLatin1("&amp;"); break;
      case '"': qHtmlText += QString::fromLatin1("&quot;"); break;
      case '\'': qHtmlText += QString::fromLatin1("&apos;"); break;
      case '\n': qHtmlText += QString::fromLatin1("<br/>"); break;
      default: qHtmlText += qChar; // everything else unchanged
    }
  }
  qHtmlText += QString::fromLatin1("</p>");
  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();
}

How it looks in Windows 10:




回答2:


Try this

if(youNeedRed)
    ui->plainTextEdit->appendHtml("<div style='color: red;'> RedText </div>");
else 
    ui->plainTextEdit->appendHtml("<div style='color: blue;'> BlueText </div>");

And Please refer Qt Rich Text HTML subset



来源:https://stackoverflow.com/questions/49665724/qt-plaintextedit-change-message-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!