码迷,mamicode.com
首页 > 其他好文 > 详细

qt treeview过滤

时间:2017-09-28 18:12:06      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:val   regexp   column   ber   span   文件   cer   需要   qstring   

一,不多说直接上代码

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);

qt treeview过滤

标签:val   regexp   column   ber   span   文件   cer   需要   qstring   

原文地址:http://www.cnblogs.com/tianmochou/p/7607685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!