• 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);
  • 相关阅读:
    About try...expect...else
    About from __future__ import absolute_import
    How to 安装apache和配置自定义目录, run CGI or py
    Caffe
    About os.environ
    TensorFlow
    Keras
    SQL自定义函数,把sql中小数点后的多于0去掉
    .net杂记 (调用EXE 获取路径 target VB DIV C# Split 页面之间传递值 更改session时间 EXCEL操作 控制电子邮件Mail input记录值的窍门)
    orcle分析函数
  • 原文地址:https://www.cnblogs.com/tianmochou/p/7607685.html
Copyright © 2020-2023  润新知