qt

How to scroll to the specified line in QPlainTextEdit?


Assuming I have a line number in the variable ln.

int ln=25;

When I pass ln to QPlainTextEdit, the scrollbar will scroll to the line 25 in QPlainTextEdit.

How to implement this feature? Could anybody give me some advice? I would be very grateful


Solution

  • Use QPlaintextEdit::document to get the QTextDocument.

    Use QTextDocument::findBlockByLineNumber to get QTextBlock of a specific line number. Remember though, it starts from line 0, not line 1.

    Then create a QTextCursor using this QTextBlock and set it to your QPlainTextEdit.

    int ln=25;
    QTextCursor cursor(p_textEdit->document()->findBlockByLineNumber(ln-1)); // ln-1 because line number starts from 0
    p_textEdit->setTextCursor(cursor);