先看下效果:

QTextEdit搜索匹配文本进行高亮_javascript


核心代码:

 

QString search_text = ui->lineEdit->text();
if (search_text.trimmed().isEmpty()) {
QMessageBox::information(this, tr("Empty search field"), tr("The search field is empty."));
} else {
QTextDocument *document = ui->textEdit->document();
bool found = false;
QTextCursor highlight_cursor(document);
QTextCursor cursor(document);
//开始
cursor.beginEditBlock();
QTextCharFormat color_format(highlight_cursor.charFormat());
color_format.setForeground(Qt::red);
while (!highlight_cursor.isNull() && !highlight_cursor.atEnd()) {
//查找指定的文本,匹配整个单词
highlight_cursor = document->find(search_text, highlight_cursor, QTextDocument::FindWholeWords);
if (!highlight_cursor.isNull()) {
if(!found)
found = true;
highlight_cursor.mergeCharFormat(color_format);
}
}
cursor.endEditBlock();
//结束
if (found == false) {
QMessageBox::information(this, tr("Word not found"), tr("Sorry,the word cannot be found."));
}
}