Search code examples
qtcursor-positionqtextedit

QTextEdit how to keep currently selected text line at the same position on the screen


I want my text cursor to be always at the same vertical position of QTextEdit.

As an example lets say i have (*I* = cursor, ==== delimit the edit box). Lets say *I* is 20 pixels from top.

============================================
Today is a nice weather
I wanted to go *I*for a walk. 
But finaly got caught in a rain.
============================================

now if i move my cursor down.

============================================
I wanted to go for a walk. 
But finaly got *I*caught in a rain.
Damn it.
============================================

Not that i can not simply count lines from, because i have embedded tables and the font size is different too.


Solution

  • You can manipulate directly the position of the scroll bars (QTextEdit::verticalScrollBar()) to keep the cursor position (QTextEdit::cursorRect()) relative to the window at the desired targetYPosition, by connecting the signal cursorPositionChanged() of the QTextEdit to a slot like this:

    void moveScrollBar() {
        int cursorY = textEdit->cursorRect().top();
        QScrollBar *vbar = textEdit->verticalScrollBar();
        vbar->setValue(vbar->value() + cursorY - targetYPosition);
    }