qt treeview过滤
阅读原文时间:2023年07月14日阅读:3

一,不多说直接上代码

QSortFilterProxyModel可实现过滤排序。但是如果直接使用只能对于父项进行过滤

这里需要继承

头文件

#include

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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章