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++ - 在 ROS 上下文中使用基于 CUDA 的函数的正确方法

c++ - Qt 手势。没有收到 qgesture 事件

C# 查找相关文档片段用于搜索结果显示

c++ - C++中的树遍历

c++ - 从 std::list 中清除元素的顺序是什么?

c++ - 在 qt 4.5 中,是否可以在静态链接插件中拥有资源?

c++ - Qt:3D水平条形图

java - Hibernate搜索可以与eclipse JPA提供程序一起使用吗?

Android:搜索 Intent 不起作用

c++ - volatile关键字有什么用?