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

前端 未结 1 1487
清歌不尽
清歌不尽 2020-12-22 02:26

QTextEdit can be appended text to simply using append(). However, if the document is rich text, every time you append to the document, it is apparently reparsed. This seems

相关标签:
1条回答
  • 2020-12-22 03:02

    If you want each append to actually show quickly & separately (instead of waiting until they've all been appended before they are shown), you need to access the internal 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());
    }
    

    The scrolling to bottom is optional, but in logging use it's a reasonable default for UI behaviour.

    Also, if your app is doing lots of other processing at the same time, appending this at the end of fastAppend, will prioritize actually getting the message displayed asap:

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

    This actually seems a kind of trap in Qt. I would know why there isn't a fastAppend method directly in QTextEdit? Or are there caveats to this solution?

    (My company actually paid KDAB for this advice, but this seems so silly that I thought this should be more common knowledge.)

    0 讨论(0)
提交回复
热议问题