qstring 字符串查找_怎样用QT查找字符串并标记要查找的内容

展开全部

用QT查找字符串并标记要查找的内容32313133353236313431303231363533e78988e69d8331333363373762,使用以下代码即可实现: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"));

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值