前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qt官方示例-文本查找器

Qt官方示例-文本查找器

作者头像
Qt君
发布2020-06-10 09:06:50
1.4K0
发布2020-06-10 09:06:50
举报
文章被收录于专栏:跟Qt君学编程跟Qt君学编程

❝该例子演示用户界面是在运行时从程序资源中加载,并实现文本查找的功能。 ❞

  程序中的.ui界面文件都是使用QUiLoader动态加载的。

动态加载.ui文件

  通过使用QUiLoad动态加载textfinder.ui为QWidget界面。

代码语言:javascript
复制
static QWidget *loadUiFile(QWidget *parent)
{
    QFile file(":/forms/textfinder.ui");
    file.open(QIODevice::ReadOnly);

    QUiLoader loader;
    return loader.load(&file, parent);
}

文本搜索与高亮

  • 使用QTextDocument::find搜索文本,获取文本的位置。
  • 通过设置QTextCursor::mergeCharFormat设置本文格式(高亮)。
代码语言:javascript
复制
// 下面片段代码已省略部分无关代码
void TextFinder::on_findButton_clicked()
{
 /* 需要搜索的文本 */
    QString searchString = ui_lineEdit->text();
    /* 文本框的全部内容 */
    QTextDocument *document = ui_textEdit->document();

 ...
 /* 高亮本文配置 */
 QTextCursor highlightCursor(document);
 ...
    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);
        }
    }
 ...
}

关于更多

  • 「QtCreator软件」可以找到:
  • 或在以下「Qt安装目录」找到:
代码语言:javascript
复制
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\uitools\textfinder
  • 「相关链接」
代码语言:javascript
复制
https://doc.qt.io/qt-5/qtuitools-textfinder-example.html
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 动态加载.ui文件
  • 文本搜索与高亮
  • 关于更多
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档