QSortFilterProxyModel实现QTreeView的数据过滤

2 篇文章 0 订阅
#ifndef TREEVIEWSORTFILTERMODEL_H
#define TREEVIEWSORTFILTERMODEL_H

#include <QObject>
#include <QSortFilterProxyModel>
#include <QRegExp>

class TreeViewSortFilterModel : public QSortFilterProxyModel
{
	Q_OBJECT
public:
    TreeViewSortFilterModel(QObject *parent = 0);

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

};

#endif // TREEVIEWSORTFILTERMODEL_H
#include "TreeViewSortFilterModel.h"

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

}

bool TreeViewSortFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
	//    if(!sourceParent.isValid())
	//    {
	//        return false;
	//    }
	QAbstractItemModel *pModel = sourceModel();
	if (NULL == pModel)  return false;
	//如果本节点的父节点可见,那么本节点也要可见
	{
		QModelIndex source_index = sourceParent;
		while (source_index.isValid())
		{
			bool isContains = pModel->data(source_index).toString().contains(filterRegExp());
			if (isContains)  return true;

			source_index = sourceModel()->parent(source_index);
		}
	}
	//判断本身是否可见
	QModelIndex index;
	bool isContains = false;
	int columnCount = pModel->columnCount();
	int m_filterColumn = filterKeyColumn();
	for (int i = 0; i < columnCount; i++)
	{
		index = pModel->index(sourceRow, i, sourceParent);
		if (index.column() != m_filterColumn && -1 != m_filterColumn)	continue;	//根据所选过滤类型选择需要进行过滤的列

		isContains = pModel->data(index).toString().contains(filterRegExp());
		if (isContains)  return true;
	}
	//如果本节点的子节点可见,那么本节点也要可见
	{
		QModelIndex source_index = sourceModel()->index(sourceRow, 0, sourceParent);
		if (!source_index.isValid())
		{
			return false;
		}

		for (int k = 0; k < sourceModel()->rowCount(source_index); k++)
		{
			if (filterAcceptsRow(k, source_index))
			{
				return true;
			}
		}
	}
	return false;
}


	//构造代理model,设置过滤列为第1列
	m_ProxyModel = new TreeViewSortFilterModel(m_treeView);
	m_ProxyModel->setSourceModel(m_TreeViewModel);
	m_ProxyModel->setFilterKeyColumn(0);
	m_treeView->setModel(m_ProxyModel);
	//包含文本filterStr的满足
	QRegExp regExp(filterStr, Qt::CaseInsensitive, QRegExp::FixedString);
	m_ProxyModel->setFilterRegExp(regExp);
	//取消隐藏
	QRegExp regExp("*", Qt::CaseInsensitive, QRegExp::Wildcard);
	m_ProxyModel->setFilterRegExp(regExp);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值