Moving the cursor inside of QTextEdit
Asked Answered
C

2

14

I have a form with a QTextEdit on it, which is called translationInput. I am trying to provide the editing functionality for the user.

This QTextEdit will contain HTML-formatted text. I have a set of buttons, like "bold", "Italic", and so on, which should add the corresponding tags into the document. If the button is pressed when no text is selected, I just want to insert a pair of tags, for example, <b></b>. If some text is selected, I want the tags to appear left and right from it.

This works fine. However, I also want the cursor to be placed before the closing tag after that, so the user will be able to continue typing inside the new-added tag without needing to reposition the cursor manually. By default, the cursor appears right after the new-added text (so in my case, right after the closing tag).

Here's the code that I have for the Italic button:

//getting the selected text(if any), and adding tags.
QString newText = ui.translationInput->textCursor().selectedText().prepend("<i>").append("</i>");
//Inserting the new-formed text into the edit
ui.translationInput->insertPlainText( newText );
//Returning focus to the edit
ui.translationInput->setFocus();
//!!! Here I want to move the cursor 4 characters left to place it before the </i> tag.
ui.translationInput->textCursor().movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4);

However, the last line doesn't do anything, the cursor doesn't move, even though the movePosition() returns true, which means that all of the operations were successfully completed.

I've also tried doing this with QTextCursor::PreviousCharacter instead of QTextCursor::Left, and tried moving it before and after returning the focus to the edit, that changes nothing.

So the question is, how do I move the cursor inside my QTextEdit?

Cousin answered 27/7, 2012 at 7:31 Comment(0)
C
16

Solved the issue by digging deeper into the docs.

The textCursor() function returns a copy of the cursor from the QTextEdit. So, to modify the actual one, setTextCursor() function must be used:

QTextCursor tmpCursor = ui.translationInput->textCursor();
tmpCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4);
ui.translationInput->setTextCursor(tmpCursor);
Cousin answered 27/7, 2012 at 7:47 Comment(3)
You can directly move the text cursor by using moveCursor(): ui.translationInput->moveCursor(QTextCursor::Left, QTextCursor::MoveAnchor, 4);Urnfield
I think the above comment should be turned into an answer.Espinosa
The moveCursor() example in above comment is wrong. This function only takes 2 arguments: void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor)Very
G
1

In PyQt (move cursor to the end of the document):

txt = QTextEdit()
txt.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
Guntar answered 25/11, 2022 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.