以下代码在找到时不会突出显示搜索字词。实际上,在按下“下一步”按钮后,光标会从QPlainTextEdit(称为ui-> gt 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);
}
}
答案 0 :(得分:2)
首先,每次按下下一个按钮时,您的代码都会在文档的开头创建一个新光标,因此您将始终从头开始搜索。其次,您必须了解您操作的光标与QPlainTextEdit
中的光标无关:您操纵副本。如果要影响文本编辑,则必须使用setTextCursor
修改其光标。这是一个有效的解决方案:
void TextEditor::findNextInstanceOfSearchTerm()
{
QString searchTerm = this->edtFind->text();
if(this->TextDocument == NULL)
{
this->TextDocument = ui->Editor->document();
}
// get the current cursor
QTextCursor documentCursor = ui->Editor->textCursor();
documentCursor = this->TextDocument->find(searchTerm,documentCursor);
if(!documentCursor.isNull())
{
// needed only if you want the entire word to be selected
documentCursor.select(QTextCursor::WordUnderCursor);
// modify the text edit cursor
ui->Editor->setTextCursor(documentCursor);
}
else
{
ui->statusbar->showMessage(
"\""+searchTerm+"\" could not be found",MESSAGE_DURATION);
}
}
作为旁注,您可能想知道QPlainTextEdit
提供了find
方法,因此这可能是实现您想要的更简单的方法:
void TextEditor::findNextInstanceOfSearchTerm()
{
QString searchTerm = this->edtFind->text();
bool found = ui->Editor->find(searchTerm);
if (found)
{
QTextCursor cursor = ui->Editor->textCursor();
cursor.select(QTextCursor::WordUnderCursor);
ui->Editor->setTextCursor(cursor);
}
else
{
// set message in status bar
}
}
答案 1 :(得分:1)
QTextCursor::EndOfWord
QPlainTextEdit::setExtraSelections
选择/突出显示QPlainTextEdit 您已经拥有了可突出显示单词的光标,但您没有将其应用于文本编辑