Chinaunix首页 | 论坛 | 博客
  • 博客访问: 403506
  • 博文数量: 168
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 0
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-09 13:46
文章分类

全部博文(168)

文章存档

2015年(51)

2014年(30)

2013年(87)

我的朋友

分类: C/C++

2015-04-09 14:51:30

要在QTextEdit中高亮搜索到的字符串, 使用它的QTextDocument和QTextCursor: 


void TextFinder::on_findButton_clicked() {

    QString searchString = ui_lineEdit->text();

    QTextDocument *document = ui_textEdit->document();


    bool found = false;


    if (isFirstTime == false)

        document->undo();


    if (searchString == "") {

        QMessageBox::information(this, tr("Empty Search Field"),

                "The search field is empty. Please enter a word and click Find.");

    } else {


        QTextCursor highlightCursor(document);

        QTextCursor cursor(document);


        //***************开始***************

        cursor.beginEditBlock();


        QTextCharFormat plainFormat(highlightCursor.charFormat());

        QTextCharFormat colorFormat = plainFormat;

        colorFormat.setForeground(Qt::red);


        while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {

            highlightCursor = document->find(searchString, highlightCursor,

                    QTextDocument::FindWholeWords);


            if (!highlightCursor.isNull()) {

                found = true;

                highlightCursor.movePosition(QTextCursor::WordRight,

                        QTextCursor::KeepAnchor);

                highlightCursor.mergeCharFormat(colorFormat);

            }

        }


        cursor.endEditBlock();

        //***************结束***************

        

        isFirstTime = false;


        if (found == false) {

            QMessageBox::information(this, tr("Word Not Found"),

                    "Sorry, the word cannot be found.");

        }

    }

}

阅读(1528) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~