Move cursor inside QTextEdit

I have a form with a QTextEdit on it called translationInput . I am trying to provide editing features for the user.

This QTextEdit will contain HTML text. I have a set of buttons, such as bold , Italic, etc., which should add the appropriate tags to the document. If the button is pressed when no text is selected, I just want to insert a couple of tags, for example, <b></b> . If any text is selected, I want the tags to appear to the left and right of it.

It works great. However, I also want the cursor to be placed before the closing tag after that, so the user can continue to enter text inside the new tag without having to manually move the cursor. By default, the cursor appears immediately after the added text (so in my case, right after the closing tag).

Here is 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 does nothing, the cursor does not move, although movePosition() returns true , which means that all operations were completed successfully.

I also tried to do this using QTextCursor::PreviousCharacter instead of QTextCursor::Left and tried to move it before and after returning focus to the edit, which does not change anything.

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

+8
c ++ qt qtextedit qtextcursor
source share
1 answer

I solved the problem, delving into the documents.

The textCursor() function returns a copy of the cursor from QTextEdit . So, to change the actual one, you need to use the setTextCursor() function:

 QTextCursor tmpCursor = ui.translationInput->textCursor(); tmpCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4); ui.translationInput->setTextCursor(tmpCursor); 
+9
source share

All Articles