将光标移动到QTextEdit内部

Sin*_*all 9 c++ qt qtextedit qtextcursor

我有一个表格,上面有一个QTextEdit叫做的表格translationInput.我正在尝试为用户提供编辑功能.

QTextEdit将包含HTML格式的文本.我有一组按钮,如" 粗体 "," 斜体 "等,它们应该将相应的标签添加到文档中.如果在没有选择文本时按下按钮,我只想插入一对标签,例如<b></b>.如果选择了某些文本,我希望标签从中向左和向右显示.

这很好用.但是,我还希望在此之后将光标放在结束标记之前,这样用户就可以继续在新添加的标记内输入,而无需手动重新定位光标.默认情况下,光标出现新添加的文本之后(所以在我的情况下,就在结束标记之后).

这是我对Italic按钮的代码:

//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);
Run Code Online (Sandbox Code Playgroud)

但是,最后一行没有做任何事情,即使movePosition()返回true,光标也不会移动,这意味着所有操作都成功完成.

我也尝试过这样做QTextCursor::PreviousCharacter而不是QTextCursor::Left,并尝试在将焦点返回到编辑之前和之后移动它,这一切都没有改变.

所以问题是,如何将光标移动到我的内部QTextEdit

Sin*_*all 10

通过深入研究文档解决了这个问题.

textCursor()函数从中返回光标的副本QTextEdit.因此,要修改实际的,setTextCursor()必须使用以下函数:

QTextCursor tmpCursor = ui.translationInput->textCursor();
tmpCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4);
ui.translationInput->setTextCursor(tmpCursor);
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用`moveCursor()`直接移动文本光标:`ui.translationInput-> moveCursor(QTextCursor :: Left,QTextCursor :: MoveAnchor,4); (12认同)