Chinaunix首页 | 论坛 | 博客
  • 博客访问: 385596
  • 博文数量: 158
  • 博客积分: 1227
  • 博客等级: 少尉
  • 技术积分: 946
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-20 16:19
文章分类
文章存档

2016年(1)

2015年(1)

2012年(107)

2011年(49)

分类:

2011-05-31 10:32:54

要在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.");

        }

    }

}

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