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?

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105

2 Answers2

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);
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • 17
    You can directly move the text cursor by using `moveCursor()`: `ui.translationInput->moveCursor(QTextCursor::Left, QTextCursor::MoveAnchor, 4);` – iliis May 07 '14 at 09:46
  • 1
    I think the above comment should be turned into an answer. – Tomáš Zato Aug 29 '17 at 18:23
  • 1
    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)` – Jruv Mar 02 '21 at 06:16
0

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

txt = QTextEdit()
txt.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
nvd
  • 2,995
  • 28
  • 16