I've researched this extensively but haven't found a satisfactory solution yet:
How do I append text at the end of QTextEdit widget without triggering a scroll to the bottom of the widget when either of these conditions is met:
- The user has selected some text.
- The user has scrolled away from the bottom.
(In all other cases, a scroll to the bottom of the QTextEdit widget should be triggered.)
Here is the code I'm currently using to append text at the bottom of a QTextEdit widget:
widget.textCursor().insertText(text);
if (old_cursor.hasSelection())
widget.setTextCursor(old_cursor);
const QTextCursor old_cursor = widget.textCursor();
widget.moveCursor(QTextCursor::End);
widget.textCursor().insertText(text);
if (old_cursor.hasSelection())
widget.setTextCursor(old_cursor);
else widget.moveCursor(QTextCursor::End);
To copy to clipboard, switch view to plain text mode
This partially takes care of condition 1: the problem is that the view will still scroll until only the last line of the selection is visible, at which point it will indeed stop scrolling.
Condition 2 is not taken care of at all: some posts suggest to save the position of the vertical scrollbar and restore it after the text was appended, however I don't think this is correct since the scrollbar should move upward when text is appended, even though the view stays still.
Note that I'm using QTextCursor::insertText() instead of QTextEdit::append() because I need to adjust the color of the text being appended, regardless of whether the user has selected text or not.
Any help greatly appreciated!
Bookmarks