为什么此代码不突出显示找到的搜索词?
下面的代码在找到搜索词时不会突出显示该搜索词。事实上,按下“下一步”按钮后,光标会从 QPlainTextEdit(称为 ui->Editor)中消失。是什么原因造成的?
void TextEditor::findNextInstanceOfSearchTerm()
{
QString searchTerm = this->edtFind->text();
if(this->TextDocument == NULL)
{
this->TextDocument = ui->Editor->document();
}
QTextCursor documentCursor(this->TextDocument);
documentCursor = this->TextDocument->find(searchTerm,documentCursor);
if(!documentCursor.isNull())
{
documentCursor.select(QTextCursor::WordUnderCursor);
}else
{
ui->statusbar->showMessage("\""+searchTerm+"\" could not be found",MESSAGE_DURATION);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,每次按“下一步”按钮时,代码都会在文档的开头创建一个新光标,因此您将始终从头开始搜索。其次,您必须了解您操作的光标与 QPlainTextEdit 中的光标无关:您操作的是一个副本。如果要影响文本编辑,则必须使用
setTextCursor
。这是一个可行的解决方案:作为旁注,您可能想知道
QPlainTextEdit
提供了find
方法,所以这可能是实现您想要的效果的更简单的方法:Firstly, your code creates a new cursor at the beginning of the document each time you press the next button, so you will always search from the beginning. Secondly, you must understand that the cursor you manipulate has nothing to do with the one in your
QPlainTextEdit
: you manipulate a copy. If you want to impact the text edit, you must modify its cursor usingsetTextCursor
. Here is a working solution:As a side note, you might want to know that
QPlainTextEdit
provides afind
method, so this might be an easier way to achieve what you want:QTextCursor::EndOfWord
QPlainTextEdit::setExtraSelections
来选择/突出显示QPlainTextEdit中的某些内容简单地说,您已经有了可以突出显示单词的光标,但您没有将其应用于文本编辑
QTextCursor::EndOfWord
QPlainTextEdit::setExtraSelections
to select/highlight something in QPlainTextEditSimply you already have cursor that would highlight word, but you didn't apply it to text edit