使用QTextCursor实现查找功能

来源:互联网 发布:windows phone浏览器 编辑:程序博客网 时间:2024/05/16 17:12

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");
        }
    }
}

1 0
原创粉丝点击