c++ - 如何在 Qt (C++) 中搜索(过滤的)QSortFilterProxyModel?

标签 c++ qt search model qsortfilterproxymodel

我有一个有效的过滤器函数 (filterAcceptsRow),它根据第一列 (index0) 过滤分层的 QTreeView。我需要连接搜索 QLineEdit 以便让用户通过(过滤的)QTreeView 进行搜索。我不确定如何向此功能添加搜索算法。谁能帮我弄清楚?搜索算法应在所有 5 列 (index0-index4) 中搜索 QString

我的过滤函数:

bool ProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
    QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
    QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
    QModelIndex index3 = sourceModel()->index(sourceRow, 3, sourceParent);
    QModelIndex index4 = sourceModel()->index(sourceRow, 4, sourceParent);

    if (m_filterEnabled)
    {
        foreach (const QString &row, rows)
        {
            if (sourceModel()->data(index0).toString().contains(row) && m_shownRow)
                return true; //element should be shown
            else if (sourceModel()->data(index0).toString().contains(row) && !m_shownRow)
                return false; //element should NOT be shown
        }
        if (m_shownRow)
            return false;
        else
            return true;
    } else {
        return true; //no filter -> show everything
    }   
}

最佳答案

最好的方法是链接 2 个代理模型。

我为表格做了类似的东西,但相信对于树它会以同样的方式工作。

您创建从 QSortFilterProxyModel 派生的类并实现 filterAcceptsRow(这里是使用正则表达式的示例):

bool QubyxSearchFilterProxyModel::filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const
{
    for(int i = 0; i < sourceModel()->columnCount(); i ++)
    {
        QModelIndex index = sourceModel()->index(sourceRow, i, sourceParent);
        if(sourceModel()->data(index).toString().toLower().trimmed().contains(filterRegExp()))
            return true;
    }

    return false;  
}

您可以在处理搜索行编辑更改的插槽之一中设置正则表达式:

QRegExp regExp(widget->lineEditSearch->text().toLower(),Qt::CaseSensitive,QRegExp::FixedString);
searchProxyModel_->setFilterRegExp(regExp);

在树代码中:

searchProxyModel_->setSourceModel(model);
proxyModel_->setSourceModel(searchProxyModel_);

关于c++ - 如何在 Qt (C++) 中搜索(过滤的)QSortFilterProxyModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118911/

相关文章:

c++ - 如何在 boost::unordered_map 中为键使用自定义类型?

c++ - 复制并修改shared_ptr

c++ - std::initializer_list 无法从 <brace-enclosed initializer list> 推导出来

c++ - 当 QListView 选择因键盘事件而改变时发出信号?

search - 更改 ElasticSearch 或 LogStash 中的默认分析器

c++ - 返回值优化和构建结构的函数

C++ Qt 返回空 QString

c++ - 当QDataStream没有这种方法时,为什么可以将QVariant写入QDataStream?

php - 如何向返回图像的网站添加搜索功能?

html - Twitter Bootstrap 行过滤器/搜索框