【问题标题】:QTreeView QSortFilterProxyModel trigger filterQTreeView QSortFilterProxyModel 触发过滤器
【发布时间】:2014-06-12 17:11:48
【问题描述】:

这是我的程序:

#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <QTreeView>


class MySortFilterProxyModel : public QSortFilterProxyModel
{
public:
    MySortFilterProxyModel();
    void updateFilter(int filterType);
protected:
    bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
    bool lessThan(const QModelIndex &left,const QModelIndex &right) const;
private:
    int _filterType;
};

MySortFilterProxyModel::MySortFilterProxyModel()
    : _filterType(0)
{
}

bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{

    QStandardItemModel* source = static_cast<QStandardItemModel*>(sourceModel());
    QModelIndex modelIndex = source->index(sourceRow, 0, sourceParent);
    QStandardItem* item = source->itemFromIndex(modelIndex);

    QVariant v = item->data(Qt::UserRole);

    int itemType = v.toInt();

    if(itemType == _filterType)
        return true;

    return false;
}

bool MySortFilterProxyModel::lessThan(const QModelIndex &left,const QModelIndex &right) const
{
    QVariant leftData = sourceModel()->data(left);
    QVariant rightData = sourceModel()->data(right);

    if(leftData.type() == QVariant::String && rightData.type() == QVariant::String)
    {
        QString leftString = leftData.toString();
        QString rightString = rightData.toString();

        return QString::localeAwareCompare(leftString, rightString) < 0;
    }

    return false;
}

void MySortFilterProxyModel::updateFilter(int filterType)
{
    _filterType = filterType;
    // how can i trigger filteracceptRows here ??
}

int main(int argc, char** argv)
{
    QApplication qtApp(argc, argv);

    MySortFilterProxyModel mySortFilterProxyModel;
    QStandardItemModel standardModel;
    QTreeView treeView;

    mySortFilterProxyModel.setSourceModel(&standardModel);
    treeView.setModel(&standardModel);
    treeView.setSortingEnabled(true);

    treeView.show();

    return qtApp.exec();
}

每次我 AppendRow 到 standardModel 排序和过滤工作。 如何在不向标准模型添加或删除某些内容的情况下触发过滤? 我想通过右键单击过滤 QTreeView 上的行,但我找不到在我的 void MySortFilterProxyModel::updateFilter(int filterType) 函数上触发 filterAcceptRows 的方法。 为每个可能的 filterType 值设置多个 MySortFilterProxyModel 类实例并根据 filterType 切换它们可能有效,但有更好的解决方案吗?

【问题讨论】:

  • QTreeView::sortByColumn() 不是在列上调用排序吗?
  • 是的,但我的问题是触发 filterAcceptRows。据我所知,没有像 QTreeView::filter() 这样的功能。
  • 您尝试拨打invalidate() slot 了吗?
  • 我现在试了一下,效果很好。

标签: c++ qt


【解决方案1】:

在 updateFilter 上调用 invalidate() 对我有用。

void MySortFilterProxyModel::updateFilter(int filterType)
{
    _filterType = filterType;
    invalidate();
}

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2019-11-20
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多