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/

相关文章:

php - 如何链接到搜索结果中主题的正确页面?

c# - 在无序日志文件中搜索

mysql - 如何在codeigniter中搜索文本?

c++ - 三角形问题

c++ - 如何将网络摄像机的图像显示为实时视频,同时在 Qt 中进行一些音频处理?

c++ - 继承QTime,自定义时间格式

c++ - 自定义 QDateEdit 样式

c# - 在 C# 中管理返回的字符串指针

c++ - 在类中声明了char数组后,如何修改它?

c++ - 使用 MFC 拦截来自 child 的 child 的消息