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

本文介绍了一个项目,使用HistoryModel类管理历史输入信息,支持搜索和关键词匹配。源码展示了如何使用QMultiMap存储和排序历史数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦回阑珊

一毛不嫌多,一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值