效果如下:
1. 标记关键词/搜索关键词
本质上find函数是移动 corsor的位置并选择该词汇
所以在循环内部设置样式可以单独设置每次词汇的样式(如,搜索“新闻”这个词,在第一段新闻是H1的标题,在正文是不加粗的小四,我们想只改颜色不修改其他样式,这时候就应该获取到每个词的Format,所以在循环内部获取)
this->moveCursor(QTextCursor::Start);
QTextDocument *document = this->document();
QTextCursor highlightCursor = this->textCursor();
QTextCursor cursor(document);
cursor.beginEditBlock();
while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {
highlightCursor = document->find(text, highlightCursor);
QTextCharFormat colorFormat(highlightCursor.charFormat());
colorFormat.setForeground(Qt::red);
if (!highlightCursor.isNull()) {
highlightCursor.setCharFormat(colorFormat);
}
}
cursor.endEditBlock();
2.删除关键词同理
this->moveCursor(QTextCursor::Start);
QTextDocument *document = this->document();
QTextCursor highlightCursor = this->textCursor();
QTextCursor cursor(document);
cursor.beginEditBlock();
while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {
highlightCursor = document->find(text, highlightCursor);
QTextCharFormat colorFormat(highlightCursor.charFormat());
colorFormat.clearForeground();
if (!highlightCursor.isNull()) {
highlightCursor.setCharFormat(colorFormat);
}
}
cursor.endEditBlock();
注:这里继承了QTextEdit的类内部函数,如果你没继承可以将 this-> 换成 textEdit->