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
?
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);