将光标移动到 QTextEdit 内部

2024-03-22

我有一个表格QTextEdit其上,称为translationInput。我正在尝试为用户提供编辑功能。

This QTextEdit将包含 HTML 格式的文本。我有一组按钮,例如“bold", "Italic”等等,这应该将相应的标签添加到文档中。如果在没有选择文本的情况下按下按钮,我只想插入一对标签,例如,<b></b>。如果选择了某些文本,我希望标签显示在其左侧和右侧。

这很好用。但是,我也希望将光标放置在在结束标签之前之后,用户将能够继续在新添加的标签内键入内容,而无需手动重新定位光标。默认情况下,光标显示在右侧after新添加的文本(在我的例子中,就在结束标记之后)。

这是我的代码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);

然而,最后一行没有做任何事情,光标没有移动,即使movePosition()回报true,这意味着所有操作均已成功完成。

我也尝试过这样做QTextCursor::PreviousCharacter代替QTextCursor::Left,并尝试在将焦点返回到编辑之前和之后移动它,但这没有任何改变。

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


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

The textCursor()函数返回一个copy光标从QTextEdit。因此,要修改实际的,setTextCursor()必须使用函数:

QTextCursor tmpCursor = ui.translationInput->textCursor();
tmpCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4);
ui.translationInput->setTextCursor(tmpCursor);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将光标移动到 QTextEdit 内部 的相关文章

随机推荐