文章评分
次,平均分 :
[收起]
文章目录
效果预览:
代码分享:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
QString searchString = ui->lineEdit_2->text(); QTextDocument *document = ui->description->document(); ui->description->setHtml(ui->description->document()->toPlainText()); int number=0; bool found = false; QTextCursor highlightCursor(document); QTextCharFormat plainFormat(highlightCursor.charFormat()); QTextCharFormat colorFormat = plainFormat; colorFormat.setForeground(Qt::red); if(ui->description->toPlainText()==""){ QMessageBox::information(this, tr("description first"), "Sorry, please display the description first!"); } else{ ui->result->setPlainText(""); QString resultstring="搜索结果:"; QString laststring; /*while循环体是本代码的关键-——开始——*/ while (!highlightCursor.isNull() && !highlightCursor.atEnd()) { if(ui->daxiaocheckBox->isChecked()==true){ highlightCursor = document->find(searchString, highlightCursor,QTextDocument::FindCaseSensitively); }//这个是实现大小写区分效果的代码,你可能不需要 else highlightCursor = document->find(searchString, highlightCursor); if (!highlightCursor.isNull()) { number++; found = true; highlightCursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,0); highlightCursor.mergeCharFormat(colorFormat); laststring=QString::number(highlightCursor.position(),10); if(ui->onlyTwo->isChecked()==true){ if(number<=1) resultstring+="n occurrence"+QString::number(number,10)+":—— position:"+QString::number(highlightCursor.position(),10); }//这个是实现大小写区分效果的代码,你可能不需要 else resultstring+="n occurrence"+QString::number(number,10)+":—— position:"+QString::number(highlightCursor.position(),10); } } /*关键代码结束*/ if(number>1&&ui->onlyTwo->isChecked()==true) resultstring+="n occurrence"+QString::number(number,10)+":—— position:"+laststring; ui->result->setPlainText(resultstring); if (found == false) { QMessageBox::information(this, tr("Word Not Found"), "Sorry, the word cannot be found."); } else { QMessageBox::information(this, tr("Word was Found"), "the word '"+searchString+"' was found for "+QString::number(number,10)+((number>1)? " times":" time")); } } |
代码解析将在笔者后续有空闲时间补全,请读者结合自身实际和关键代码分析,以为己用。代码交流,欢迎大家留言

关注我的微信,获取文章更新
如果你觉得这篇文章对你有用,可以点击下面的“赞助作者”打赏作者!
转载注明原文出处:王柏元的博客>>https://wangbaiyuan.cn/how-to-use-qt-to-find-content-you-want-to-find-a-string-and-tag.html
暂无评论