zoukankan      html  css  js  c++  java
  • qt treeview过滤

    一,不多说直接上代码

    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);
  • 相关阅读:
    第04章-面向切面的Spring
    第03章-高级装配
    第02章-装配Bean
    第01章-Spring之旅
    IntelliJ IDEA打可运行jar包时的错误
    序列化+fastjson和java各种数据对象相互转化
    TinkerPop中的遍历:图的遍历策略
    TinkerPop中的遍历:图的遍历中谓词、栅栏、范围和Lambda的说明
    asp.net动态网站repeater控件使用及分页操作介绍
    HTML入门标签汇总
  • 原文地址:https://www.cnblogs.com/tianmochou/p/7607685.html
Copyright © 2011-2022 走看看