一,不多说直接上代码
QSortFilterProxyModel可实现过滤排序。但是如果直接使用只能对于父项进行过滤
这里需要继承
头文件
#include <QSortFilterProxyModel>
class TreeProxyFilter:public QSortFilterProxyModel
{
public:
TreeProxyFilter(QObject *parent = Q_NULLPTR);
protected:
bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const;
private:
bool ShowThis(const QModelIndex index) const;
};cpp文件 bool TreeProxyFilter::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
return ShowThis(index);
}
bool TreeProxyFilter::ShowThis(const QModelIndex index) const
{
bool retVal = false;
//Gives you the info for number of childs with a parent
if ( sourceModel()->rowCount(index) > 0 )
{
for( int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++)
{
QModelIndex childIndex = sourceModel()->index(nChild,0,index);
if ( ! childIndex.isValid() )
break;
retVal = ShowThis(childIndex);
if (retVal)
{
break;
}
}
}
else
{
QModelIndex useIndex = sourceModel()->index(index.row(), 0, index.parent());
QString type = sourceModel()->data(useIndex, Qt::DisplayRole).toString();
if (!type.contains(filterRegExp()))
{
retVal = false;
}
else
{
retVal = true;
}
}
return retVal;
}重写filterAcceptsRow方法,在该方法里对过滤项进行筛选。 二。使用 proxyModel = new TreeProxyFilter(this);
proxyModel->setSourceModel(model);
proxyModel->setFilterKeyColumn(0);
connect(ui->filterLineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(factorFilter()));
ui->treeView->setModel(proxyModel);
时间: 2024-10-13 12:27:05