QString search_text = ui->lineEdit->text();
if (search_text.trimmed().isEmpty())
{
return;
}
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); //字体颜色
color_format.setBackground(Qt::blue); //背景颜色
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();
}
取消高亮的例子
QString search_text = ui->lineEdit->text();
if (search_text.trimmed().isEmpty())
{
return;
}
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.clearForeground(); // 清除前景色
color_format.clearBackground(); // 清除背景色
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();
}