【发布时间】: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 了吗? -
我现在试了一下,效果很好。