要在QTextEdit中高亮搜索到的字符串, 使用它的QTextDocument和QTextCursor:
void TextFinder::on_findButton_clicked() {
QString searchString = ui_lineEdit->text();
QTextDocument *document = ui_textEdit->document();
bool found = false;
if (isFirstTime == false)
document->undo();
if (searchString == "") {
QMessageBox::information(this, tr("Empty Search Field"),
"The search field is empty. Please enter a word and click Find.");
} else {
QTextCursor highlightCursor(document);
QTextCursor cursor(document);
//***************开始***************
cursor.beginEditBlock();
QTextCharFormat plainFormat(highlightCursor.charFormat());
QTextCharFormat colorFormat = plainFormat;
colorFormat.setForeground(Qt::red);
while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {
highlightCursor = document->find(searchString, highlightCursor,
QTextDocument::FindWholeWords);
if (!highlightCursor.isNull()) {
found = true;
highlightCursor.movePosition(QTextCursor::WordRight,
QTextCursor::KeepAnchor);
highlightCursor.mergeCharFormat(colorFormat);
}
}
cursor.endEditBlock();
//***************结束***************
isFirstTime = false;
if (found == false) {
QMessageBox::information(this, tr("Word Not Found"),
"Sorry, the word cannot be found.");
}
}
}