逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::

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

        }

    }

}

posted on 2009-05-24 19:36 逛奔的蜗牛 阅读(4173) 评论(3)  编辑 收藏 引用 所属分类: Qt自定义Widget

评论

# re: QtWidget: TextFinder(高亮搜索到的字符串) 2010-08-16 15:32 lijunsong
那个 movePosition 是多余的……  回复  更多评论
  

# re: QtWidget: TextFinder(高亮搜索到的字符串) 2012-05-11 22:19 gaoshixian
介个哥们是我瓜大的吧  回复  更多评论
  

# re: QtWidget: TextFinder(高亮搜索到的字符串) 2012-10-16 15:34 毛竹
如果是在ListView上呢,要怎么标记高亮  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理