Important: Please read the Qt Code of Conduct -

Handle QTextBlock with multples lines (Html) to display line numbers

  • Hello,

    I've created a text editor quite similar to this one (Qt 4.8):

    Primarily it consists of a QPlainTextEdit and a line number bar on the left. The QPlainTextEdit might also
    contain text formatted as HTML (added with appendHthml() function).

    If the QPlainTextEdit contains plain text, the line numbers are correct and each text line is in its own QTextBlock.
    Therefore the function lineNumberAreaPaintEvent() (see example above) works correclty.
    But once HTML formatted text is added, QPlainTextEdit consists of a single QTextBlock that contains all text.
    Therefore the function lineNumberAreaPaintEvent() does not work correctly anymore.

    The following code of the function lineNumberAreaPaintEvent()

    while (block.isValid() && top <= event->rect().bottom()) {
            if (block.isVisible() && bottom >= event->rect().top()) {
            block =;
            top = bottom;
            bottom = top + qRound(blockBoundingRect(block).height());

    is very important to prevent unnecessary draw events that will otherwise hurt scroll performance when working with very large documents. Is there maybe a way to have every line of the HTML formatted text in its own QTextBlock so that the function will work again? Or can you find out which lines of a QTextBlock are currently displyed to paint only the necessary line numbers?

    Thank you very much

  • For everyone who is interested; The above example/text editor works correctly if the Html text is formatted correclty. Each line must be in its own paragraph (<p> tag), then Qt is able to create invidiual QTextBlock objects for each line. <br> does not work.

Log in to reply