繁体   English   中英

在Qt中高效地将文本添加(丰富)到QTextEdit或QTextBrowser中

[英]Performantly appending (rich) text into QTextEdit or QTextBrowser in Qt

QTextEdit可以简单地使用append()附加文本。 但是,如果文档是富文本格式,则每次您附加到文档时,显然都会对其进行重新解析。 这似乎在Qt中有点陷阱。

如果您将编辑框用作日志窗口,并且由于外部信号而连续快速附加文本,则附加操作可以轻松挂起您的应用程序,而不会显示中间附加内容,直到每个附加操作完成为止。

如何在不降低整个UI速度的情况下将丰富文本添加到QTextEdit?

如果您希望每个附加项实际上分别快速且独立地显示(而不是等到它们全部显示后才显示),则需要访问内部QTextDocument:

void fastAppend(QString message,QTextEdit *editWidget)
{
    const bool atBottom = editWidget->verticalScrollBar()->value() == editWidget->verticalScrollBar()->maximum();
    QTextDocument* doc = editWidget->document();
    QTextCursor cursor(doc);
    cursor.movePosition(QTextCursor::End);
    cursor.beginEditBlock();
    cursor.insertBlock();
    cursor.insertHtml(message);
    cursor.endEditBlock();

    //scroll scrollarea to bottom if it was at bottom when we started
    //(we don't want to force scrolling to bottom if user is looking at a
    //higher position)
    if (atBottom) {
        scrollLogToBottom(editWidget);
    }
}

void scrollLogToBottom(QTextEdit *editWidget)
{

    QScrollBar* bar =  editWidget->verticalScrollBar();
    bar->setValue(bar->maximum());
}

滚动到底部是可选的,但在日志记录中使用时,这是UI行为的合理默认值。

另外,如果您的应用程序同时执行许多其他处理,则在fastAppend的末尾附加此内容将优先考虑实际使消息尽快显示:

    //show the message in output right away by triggering event loop
    QCoreApplication::processEvents();

这实际上似乎是Qt中的一种陷阱。 我知道为什么QTextEdit中没有直接的fastAppend方法吗? 还是对此解决方案有警告?

(我的公司实际上已向KDAB支付了此建议,但这似乎太愚蠢了,以至于我认为这应该是更常见的知识。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM