大家好!小生刚接触QT,遇到了不少问题,在此请高手专家们不吝赐教,能够给予指点迷津,谢谢:)
需求是这样的:对TextEdit中的文本搜索关键字并进行高显,关键字是在LineEdit中输入的。
需注意的问题是:高亮搜索到关键字时,前一次搜索到的关键字不再高亮。
下面是程序中的部分代码:
void MainWidget::search() {
QString searchString = lineEdit->text();
QTextDocument *document = textEdit->document();
//为防止第二次搜索另一个关键字时,第一次的关键字仍然高显,故对文本进行了背景色为白色设置
QTextCursor cursor(document);
cursor.select(QTextCursor::document);
QTextCharFormat whiteFormat(cursor.charFormat());
whiteFormat.setBackground(Qt::white);
cursor.mergeCharFormat(whiteFormat);
//高显关键字,使关键字为红色
QTextCursor highlightCursor(document);
QTextCharFormat colorFormat(highlightCursor.charFormat());
colorFormat.setBackground(Qt::red);
while(!highlightCursor.isNull()&&!highlightCursor.atEnd()){
highlightCursor = document->find(searchString, highlightCursor);
if (!highlightCursor.isNull()) {
highlightCursor.block();
highlightCursor.mergeCharFormat(colorFormat);
}
}
}
问题缺陷是:
当对大量的数据(字符串)进行搜索高亮处理时,效率很低,第一次搜索完,该搜索第二次关键字时,中间停顿一会儿5s多,第二个关键字才会亮,原因应该是再次对所有文本进行了白色背景涂色吧?应该与find方法的效率没有关系吧?如何才能实现即时高显,中间不会停顿呢?还望高手能给予指点.Thx!