Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3426197
  • 博文数量: 864
  • 博客积分: 14125
  • 博客等级: 上将
  • 技术积分: 10634
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-27 16:53
个人简介

https://github.com/zytc2009/BigTeam_learning

文章分类

全部博文(864)

文章存档

2023年(1)

2021年(1)

2019年(3)

2018年(1)

2017年(10)

2015年(3)

2014年(8)

2013年(3)

2012年(69)

2011年(103)

2010年(357)

2009年(283)

2008年(22)

分类: C/C++

2009-08-01 16:29:18

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

        }

    }

}

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