QTextEdit with different text colors (Qt / C++)
Asked Answered
L

7

36

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.

Lectern answered 18/5, 2010 at 13:53 Comment(0)
H
25

Use text formated as HTML, for example:

textEdit->setHtml(text);

where text, is a HTML formated text, contains with colored lines and etc.

Homoeroticism answered 18/5, 2010 at 14:4 Comment(1)
No. This isn't necessary.Squirrel
P
42

Just a quick addition: an alternative to generating the html yourself, if you're populating the text box programatically, is to use textEdit->setTextColor(QColor&). You can create the QColor object yourself, or use one of the predefined colours in the Qt namespace (Qt::black, Qt::red, etc). It will apply the specified colour to any text you add, until it is called again with a different one.

Phina answered 18/5, 2010 at 15:5 Comment(3)
This is by far the simplest solution to do so. Works like a charm for example for logging, where each line is colored according to the message's severity.Kelula
but this only colors all the text present , i want to color each color with a diff color , can u please help me with that ?Kessel
If you are using a 'textEdit' object, it will color the text of each 'append' call with a different color.Quach
K
37

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);
Kingsbury answered 3/8, 2011 at 22:52 Comment(0)
H
25

Use text formated as HTML, for example:

textEdit->setHtml(text);

where text, is a HTML formated text, contains with colored lines and etc.

Homoeroticism answered 18/5, 2010 at 14:4 Comment(1)
No. This isn't necessary.Squirrel
T
12

Link to doc

A few quotes:

QTextEdit is an advanced WYSIWYG viewer/editor supporting rich text formatting using HTML-style tags. It is optimized to handle large documents and to respond quickly to user input.

.

The text edit can load both plain text and HTML files (a subset of HTML 3.2 and 4).

.

QTextEdit can display a large HTML subset, including tables and images.

This means mostly deprecated tags and as such does not include any current CSS, so I turned to this:

// save    
int fw = ui->textEdit->fontWeight();
QColor tc = ui->textEdit->textColor();
// append
ui->textEdit->setFontWeight( QFont::DemiBold );
ui->textEdit->setTextColor( QColor( "red" ) );
ui->textEdit->append( entry );
// restore
ui->textEdit->setFontWeight( fw );
ui->textEdit->setTextColor( tc );
Truly answered 8/11, 2012 at 10:45 Comment(1)
Does restore to black on macosWeichsel
H
12

Extending on https://mcmap.net/q/417798/-qtextedit-with-different-text-colors-qt-c:

QTextEdit::append() inserts a new paragraph with the previously set FontWeight / TextColor. insertHTML() or InsertPlainText() to avoid inserting a new paragraph (e.g. to achieve different formats in a single line) do not respect the font/color settings.

Instead use QTextCursor:

...
// textEdit->moveCursor( QTextCursor::End );
QTextCursor cursor( textEdit->textCursor() );

QTextCharFormat format;
format.setFontWeight( QFont::DemiBold );
format.setForeground( QBrush( QColor( "black" ) ) );
cursor.setCharFormat( format );

cursor.insertText( "Hello world!" );
...
Hibbs answered 25/6, 2013 at 8:56 Comment(2)
this answer taught me new thingsKessel
This wound up working for me. One line is one color, and the next line is a different color. In this example, after "Hello World", you would put lines format.setForeground( QBrush( QColor( "white" ) ) ); and cursor.setCharFormat( format ); and cursor.insertText( "This line is white" );.Bout
S
4

This is my solution for a very simple error logging using QTextEdit.

// In some common header file
enum class ReportLevel {
    Info,
    Warning,
    Error
};

// Signal in classes who report something
void reportStatus(ReportLevel level,
                   const QString& tag,
                   const QString& report);

// Slot in the class which receives the reports
void MyGreatClass::handleStatusReport(ReportLevel level,
                                    const QString& tag,
                                    const QString& report)
{
    switch(level) {
        case ReportLevel::Info:
            mTeReports->setTextColor(Qt::blue);
            break;
        case ReportLevel::Warning:
            mTeReports->setTextColor(QColor::fromRgb(255, 165, 0)); // Orange
            break;
        case ReportLevel::Error:
            mTeReports->setTextColor(Qt::red);
            break;
    }

    // mTeReoports is just an instance of QTextEdit
    mTeReports->insertPlainText(tag + "\t");
    mTeReports->setTextColor(Qt::black); // set color back to black
    // might want ot use #ifdef for windows or linux....
    mTeReports->insertPlainText(report + "\r\n");

    // Force the scroll bar (if visible) to jump to bottom
    mTeReports->ensureCursorVisible();
}

This is how it looks like:

enter image description here

Of course, you can go ahead and add date/time and other cool stuff :)

Stacy answered 24/1, 2019 at 8:55 Comment(1)
The problem is that original text colour is theme-dependent and may be anything, not only black.Savick
T
0

Wow, this is a immemorial problem...But anyway, it comes to me now, and just like @badgerr said, after you calling setTextColor(QColor& colorA), the color of the text you append after that will be colorA until you set the color again. It will not change the color of text you appended before you set the textColor.

ui->textBrowser->clear();
auto colorIte = colorList->begin();
while(colorIte != colorList->end())
{
    ui->textBrowser->setTextColor(*colorIte);
    ui->textBrowser->append(QString("RGB(%1, %2, %3)").arg(colorIte->red()) 
             .arg(colorIte->green()).arg(colorIte->blue()));
    colorIte++;
}

the colorList stores some QColor objects, this code snippet show the color in RGB format with the color it represents.

Tracheitis answered 23/11, 2023 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.