QTreeview实现搜索功能查找功能

    xiaoxiao2025-06-13  21

    QTreeview查找功能的需求:

    1.搜索某个节点时,该节点的父节点和子节点都显示出来

    效果图如下:

     

    输入搜索内容后:

     

    核心代码如下:

    bool TableViewSortFilterModelBase::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { // if(!sourceParent.isValid()) // { // return false; // } QAbstractItemModel *pModel = sourceModel(); if(NULL == pModel) return false; //--------------如果本节点的父节点可见,那么本节点也要可见 { QModelIndex source_index = sourceParent; while (source_index.isValid()) { bool isContains = pModel->data(source_index).toString().contains(filterRegExp()); if(isContains) return true;   source_index = sourceModel()->parent(source_index); } } //--------------判断本身是否可见 QModelIndex index; bool isContains = false; int columnCount = pModel->columnCount(); for(int i=0;i<columnCount;i++) { index = pModel->index(sourceRow, i, sourceParent); if (index.column() != m_filterColumn && -1 != m_filterColumn) continue; //根据所选过滤类型选择需要进行过滤的列   isContains = pModel->data(index).toString().contains(filterRegExp()); if(isContains) return true; } //--------------如果本节点的子节点可见,那么本节点也要可见 { // check all decendant's QModelIndex source_index = sourceModel()->index(sourceRow, 0, sourceParent); if(!source_index.isValid()) { return false; }   for (int k=0; k<sourceModel()->rowCount(source_index); k++) { if (filterAcceptsRow(k, source_index)) { return true; } } } return false; }

     

    源码下载地址:https://download.csdn.net/download/liuguangzhou123/11206060

    最新回复(0)