QT TreeView自定义Model 实现自定义过滤筛选数据

简介

通常我们使用QSortFilterProxyModel过滤数据时,只会过滤树的父节点,符合条件的子节点不会被显示出来,因此我们需要继承QSortFilterProxyModel,重写filterAcceptsRow函数可以实现符合条件的子节点也显示出来。
.h

#include <QSortFilterProxyModel>

class SelectFileSortFilterProxyModel : public QSortFilterProxyModel
{
    Q_OBJECT
public:

    explicit SelectFileSortFilterProxyModel(QObject *parent = nullptr);
    ~SelectFileSortFilterProxyModel() = default;

protected:
    bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;

};

.cpp

#include "SelectFileSortFilterProxyModel.h"

SelectFileSortFilterProxyModel::SelectFileSortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent)
{

}

bool SelectFileSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    bool relust = QSortFilterProxyModel::filterAcceptsRow(source_row,source_parent);
    if(relust)
    {   //本来就符合条件直接返回
        return true;
    }
    else
    {   //若节点不符合判断条件,判断其下是否有子节点,若有则需要显示
    //可根据需求自行修改下面的判断内容
        QModelIndex source_index = sourceModel()->index(source_row, 0, source_parent);
        if(sourceModel()->rowCount(source_index)>0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return relust;
}

用法:

//新建排序model
m_sortmodel = new SelectFileSortFilterProxyModel(this);
//将model设置到treeview中
ui->treeView->setModel(m_sortmodel);
//新建数据model
m_model = new SelectFileModel;
//将数据model设置到过滤model中
m_sortmodel->setSourceModel(m_model);

效果:
在这里插入图片描述
在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值