《QT实用小工具·四十三》历史编辑器(支持历史搜索 & 关键字匹配)

1、概述
源码放在文章末尾

该项目实现了在输入框中输入部分信息能全部展现之前的历史输入信息,支持历史搜索和关键词匹配,项目demo演示如下所示:
在这里插入图片描述

项目部分代码如下所示:

#include "historymodel.h"
#include <QMultiMap>

HistoryModel::HistoryModel()
{
    /**
     * @note historyData <QList>
     * 用于存储历史记录。
     * 可自由填充,我这里直接手动填充了。
     */
    qsrand(uint(time(nullptr)));

    for (int i = 0; i < 20; ++i) {
        QString randStr;
        for (int j = 0; j < 10; ++j) {
            randStr += QString::number(qrand() % 10);
        }
        m_historyData.push_back(randStr);
    }

    m_data = m_historyData;
}

int HistoryModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_data.count();
}

int HistoryModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 1;
}

QVariant HistoryModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= m_data.count())
        return QVariant();

    switch (role) {
        case Qt::DisplayRole:
            return m_data.at(index.row());

    default:
        break;
    }

    return QVariant();
}

void HistoryModel::sortByKey(const QString &key)
{
    if (key.isEmpty()) {
        beginResetModel();
        m_data = m_historyData;
        endResetModel();
    } else {
        QMultiMap<int, QString> temp;
        for (auto str : m_historyData) {
            int ret = str.indexOf(key);
            if (ret == -1) continue;
            else temp.insert(ret, str);
        }

        beginResetModel();
        m_data.clear();
        if (!temp.isEmpty()) {
            //也可 for range-based
            for (auto it = temp.begin(); it != temp.end(); it++) {
                m_data.push_back(it.value());
            }
        }
        endResetModel();
    }
}

源码下载

最近更新

  1. TCP协议是安全的吗?

    2024-04-28 08:56:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-28 08:56:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-28 08:56:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-28 08:56:03       20 阅读

热门阅读

  1. js 延迟加载的⽅式有哪些

    2024-04-28 08:56:03       13 阅读
  2. 最短路(Dijkstra, Bellman-Ford, SPFA, Floyd)

    2024-04-28 08:56:03       12 阅读
  3. 数据结构与算法-图论-DFS/BFS

    2024-04-28 08:56:03       13 阅读
  4. 【笔记】 - Git

    2024-04-28 08:56:03       12 阅读
  5. isort库,一款超级神奇排序和格式化Python工具

    2024-04-28 08:56:03       15 阅读
  6. 解决eureka服务注册名报错

    2024-04-28 08:56:03       14 阅读
  7. 数字化转型之路:企业信息化建设的关键步骤

    2024-04-28 08:56:03       14 阅读
  8. HTML实体编码

    2024-04-28 08:56:03       11 阅读
  9. 多进程控制

    2024-04-28 08:56:03       21 阅读
  10. C++ 如何高效的使用 STL 容器?

    2024-04-28 08:56:03       17 阅读
  11. 数据库系统工程师之数据结构

    2024-04-28 08:56:03       17 阅读