具有不同文本颜色的 QTextEdit (Qt / C++)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2857864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:18:13  来源:igfitidea点击:

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

c++qtcolorsqtextedit

提问by user924

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

我有一个QTextEdit显示文本的框,我希望能够在同一个QTextEdit框中为不同的文本行设置文本颜色。(即第 1 行可能是红色,第 2 行可能是黑色等)

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

这可能在一个QTextEdit盒子里吗?如果没有,获得这种行为的最简单方法是什么?

Thanks.

谢谢。

采纳答案by mosg

Use text formated as HTML, for example:

使用格式为 HTML 的文本,例如:

textEdit->setHtml(text);

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

其中text,是 HTML 格式的文本,包含彩色线条等。

回答by paie

The ONLYthing that worked for me was html.

为我工作的事情是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);

回答by badgerr

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.

只是一个快速补充:如果您以编程方式填充文本框,则可以使用textEdit->setTextColor(QColor&). 您可以自己创建 QColor 对象,或使用 Qt 命名空间中的预定义颜色之一(Qt::black、Qt::red 等)。它会将指定的颜色应用于您添加的任何文本,直到使用不同的颜色再次调用它。

回答by none

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.

QTextEdit 是一个先进的 WYSIWYG 查看器/编辑器,支持使用 HTML 样式标签的富文本格式。它经过优化,可处理大型文档并快速响应用户输入。

.

.

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

文本编辑器可以加载纯文本和 HTML 文件(HTML 3.2 和 4 的子集)。

.

.

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

QTextEdit 可以显示一个大的 HTML 子集,包括表格和图像。

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

这意味着大多数已弃用的标签,因此不包含任何当前的 CSS,所以我转向了这个:

// 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 );

回答by handle

Extending on https://stackoverflow.com/a/13287446/1619432:

https://stackoverflow.com/a/13287446/1619432 上扩展:

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.

QTextEdit::append()使用先前设置的 FontWeight / TextColor 插入一个新段落。 insertHTML()或者InsertPlainText()为了避免插入一个新段落(例如,在一行中实现不同的格式)不尊重字体/颜色设置。

Instead use QTextCursor:

而是使用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!" );
...

回答by Saeid Yazdani

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

这是我使用 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 :)

当然,您可以继续添加日期/时间和其他很酷的东西:)