QSortFilterProxyModel过滤QTreeView中的文件

来源:互联网 发布:软件著作权和专利 编辑:程序博客网 时间:2024/05/16 16:05

程序是用QTreeView显示QFileSystemModel的内容,通过QSortFilterProxyModel实现过滤。

 

   pLocalViewModel = new(std::nothrow) QFileSystemModel();

   if (NULL == pLocalViewModel)

   {

       Q_ASSERT(false);

       return false;

   }

 

   pLocalProxyViewModel = new(std::nothrow) MySortFilterProxyModel();

   if (NULL == pLocalProxyViewModel)

   {

       Q_ASSERT(false);

       return false;

   }

   

   pLocalProxyViewModel->setSourceModel(pLocalViewModel);

   pLocalProxyViewModel->setFilterKeyColumn(0);   

   pLocalProxyViewModel->setDynamicSortFilter(true);

 

   // pLocalTreeView config   

   pLocalTreeView = new(std::nothrow) QTreeView();

   if (NULL == pLocalTreeView)

   {

       Q_ASSERT(false);

       return false;

   }

   

   pLocalTreeView->setModel(pLocalProxyViewModel);

 

通过QLineEdit输入关键字做过滤,当QLineEdit有字符变化时,就会触发过滤。

connect(filterLineEdit,SIGNAL(textChanged(const QString &)), this, SLOT(applyFilter(const QString&)));

 

void TPFileManagerPanel::applyFilter(constQString &text)

{

   QRegExp  regExp(text,Qt::CaseInsensitive, QRegExp::Wildcard);

 

   if (NULL != pCurrentProxyModel && NULL != pCurrentTreeView)

   {

       pCurrentProxyModel->setFilterRegExp(regExp);

   }

}

 

对于QTreeView中已经展开的节点,要求能过滤出所有满足条件的节点。如果子节点满足,父节点需要显示;如果没有子节点满足,父节点不显示。

 

参考< QSortFilterProxyModel实现QTreeView的过滤的缺点和改进>这篇博客,http://blog.csdn.net/lutx/article/details/7161467;

实现自己的MySortFilterProxyModel。发现当没有子项能够满足条件时,此时逐字符清空QLineEdit, QTreeView直接显示系统的根目录,且无法再变回原设定的rootIndex。

 

针对上述情况,做了以下改进,

 

boolMySortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex&source_parent) const

{

   bool bRet = isParentRoot(source_parent);   

   if (bRet)

   {

       bool filter = QSortFilterProxyModel::filterAcceptsRow(source_row,source_parent); 

     

       if (filter) 

       { 

            return true; 

       } 

       else 

       { 

            // check all decendant's 

            QModelIndex source_index =sourceModel()->index(source_row, 0, source_parent); 

           for (int k=0;k<sourceModel()->rowCount(source_index); k++) 

            { 

                if (filterAcceptsRow(k,source_index)) 

                { 

                    return true; 

                } 

            } 

       }         

       return false; 

   }

   

   return true;

}

 

boolMySortFilterProxyModel::isParentRoot(const QModelIndex &index) const

{

   QFileSystemModel *sm =qobject_cast<QFileSystemModel*>(sourceModel());

 

   if (index.isValid())

   {

       if (index == sm->index(sm->rootPath()))

       {

            return true;

       }

       else

       {

            returnisParentRoot(index.parent());

       }

   }

 

   return false;

}

 

经过验证,此时不论过滤条件如何改变,QTreeView不再显示错误。

 

 

0 0
原创粉丝点击