使用QTextCursor选择一段文本 [英] Selecting a piece of text using QTextCursor
问题描述
使用Qt框架选择文本时遇到问题。例如,如果我有这个文件:没有时间休息。我想选择ime for r并从文档中删除这一段文字,我应该如何使用QTextCursor?这是我的代码:
Having problems with selecting pieces of text using the Qt framework. For example if i have this document : "No time for rest". And i want to select "ime for r" and delete this piece of text from the document, how should i do it using QTextCursor? Here is my code:
QTextCursor *cursor = new QTextCursor(ui->plainTextEdit->document());
cursor->setPosition(StartPos,QTextCursor::MoveAnchor);
cursor->setPosition(EndPos,QTextCursor::KeepAnchor);
cursor->select(QTextCursor::LineUnderCursor);
cursor->clearSelection();
不幸的是,它会从文本中删除整行。我尝试使用其他选择类型,如WordUnderCursor或BlockUnderCursor,但没有结果。还是有更好的方法吗?提前感谢。
Unfortunately it deletes the whole line from the text. I've tried using other selection types like WordUnderCursor or BlockUnderCursor, but no result. Or maybe there is a better way to do it? Thanks in advance.
推荐答案
您的代码有几个问题:
-
cursor-> select(QTextCursor :: LineUnderCursor);
行选择整个当前行。你不想删除整行,那么为什么要这样写呢?删除此行代码。 -
clearSelection()
只是取消选择所有内容。 c。使用removeSelectedText()
。 - 不要创建
QTextCursor
code> new 。这是正确的,但不是必需的。你应该尽可能避免指针。QTextCursor
通常由值或引用传递。您还可以使用QPlainTextEdit :: textCursor
获取编辑光标的副本。
cursor->select(QTextCursor::LineUnderCursor);
line selects whole current line. You don't want to delete whole line, so why would you write this? Remove this line of code.clearSelection()
just deselects everything. UseremoveSelectedText()
instead.- Don't create
QTextCursor
usingnew
. It's correct but not needed. You should avoid pointers when possible.QTextCursor
is usually passed by value or reference. Also you can useQPlainText:textCursor
to get a copy of the edit cursor.
所以,代码应该像这样:
So, the code should look like that:
QTextCursor cursor = ui->plainTextEdit->textCursor();
cursor.setPosition(StartPos, QTextCursor::MoveAnchor);
cursor.setPosition(EndPos, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
这篇关于使用QTextCursor选择一段文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!