实现文本查找功能可以用QTextCursor

QTextCursor是文本光标

下面是查找功能代码:

void Widget::findBtnClicked()
{
    bool found = false;
    //想要查找的信息
    QString Info = lineEdit->text();
    //获取文本文档
    QTextDocument *document = textEdit->document();
    //如果不是第一次查找就取消上一次查找操作,响应开始到结束阶段的操作
    if(isfirst == false){
        document->undo();
    }
    if(Info.isEmpty())
    {
        QMessageBox::information(this,"Info is empty","the search field is empty,please enter a word and click find");
    }else
    {
        //创建文本文档里面的文本光标
        QTextCursor cursor(document);
        QTextCursor editCursor(document);

        //开始
        editCursor.beginEditBlock();
        QTextCharFormat midvar(cursor.charFormat());
        QTextCharFormat colorFormat = midvar;
        colorFormat.setForeground(Qt::red);

        while(!cursor.isNull()&&!cursor.atEnd())
        {
            //个人理解为cursor表示的就是本文里面要查找的内容
            cursor = document->find(Info,cursor,QTextDocument::FindWholeWords);
            if(!cursor.isNull())
            {
                found = true;
                cursor.mergeCharFormat(colorFormat);
            }
//            cursor.movePosition(QTextCursor::WordRight,QTextCursor::KeepAnchor);
            //设置查找信息的颜色,根据函数里的参数类型创建了上面的QTextCharFormat colorFormat
        }
        //结束
        editCursor.endEditBlock();
        isfirst = false;

        if(found == false)
        {
            isfirst = true;
            QMessageBox::information(this,"Word Not Found","Sorry,the word cannot be found");
        }
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值