QTextEdit with different text colors (Qt / C++)

user924 picture user924 · May 18, 2010 · Viewed 68k times · Source

I have a QTextEdit box that displays text, and I'd like to be able to set the text color for different lines of text in the same QTextEdit box. (i.e. line 1 might be red, line 2 might be black, etc.)

Is this possible in a QTextEdit box? If not, what's the easiest way to get this behavior?

Thanks.

Answer

paie picture paie · Aug 4, 2011

The ONLY thing that worked for me was html.

Code snippet follows.

QString line = "contains some text from somewhere ..."
    :
    :
QTextCursor cursor = ui->messages->textCursor();
QString alertHtml = "<font color=\"DeepPink\">";
QString notifyHtml = "<font color=\"Lime\">";
QString infoHtml = "<font color=\"Aqua\">";
QString endHtml = "</font><br>";

switch(level)
{
    case msg_alert: line = alertHtml % line; break;
    case msg_notify: line = notifyHtml % line; break;
    case msg_info: line = infoHtml % line; break;
    default: line = infoHtml % line; break;
}

line = line % endHtml;
ui->messages->insertHtml(line);
cursor.movePosition(QTextCursor::End);
ui->messages->setTextCursor(cursor);