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

发布于 2024-09-02 03:54:38 字数 166 浏览 7 评论 0原文

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

这在 QTextEdit 框中可能吗?如果没有,获得这种行为的最简单方法是什么?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

旧情别恋 2024-09-09 03:54:38

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

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.

-黛色若梦 2024-09-09 03:54:38

唯一对我有用的是 html。

代码片段如下。

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

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);
等往事风中吹 2024-09-09 03:54:38

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

textEdit->setHtml(text);

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

Use text formated as HTML, for example:

textEdit->setHtml(text);

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

晌融 2024-09-09 03:54:38

文档链接

一些引用:

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

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

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

这意味着大部分标签已被弃用,因此不包含任何当前的 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 );

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 );
旧情勿念 2024-09-09 03:54:38

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

QTextEdit::append()< /code> 使用先前设置的 FontWeight / TextColor 插入一个新段落。
insertHTML()InsertPlainText() 以避免插入新段落(例如,在单行中实现不同的格式),不考虑字体/颜色设置。

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

Extending on 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.

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!" );
...
耳根太软 2024-09-09 03:54:38

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

日裸衫吸 2024-09-09 03:54:38

哇,这是一个古老的问题......但无论如何,它现在出现在我身上,就像@badgerr所说,在你调用setTextColor(QColor& colorA)之后,你之后附加的文本的颜色将是colorA,直到你再次设置颜色。它不会更改您在设置 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++;
}

colorList 存储一些 QColor 对象,此代码片段以 RGB 格式显示颜色及其代表的颜色。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文