我目前正在开发一个应用程序,该应用程序使用自定义模型作为 Qt 模型/ View 结构的扩展。一个名为 MyModel 的模型存储一个对象(比如 std::vector ),它有几千个元素,MyModel 中的数据使用标准 QTableView 查看。但是,该应用程序支持对表中查看的数据进行一些简单的基本过滤,包括按相关性、上传日期等进行过滤。
QSortFilterProxyModel 允许根据正则表达式对模型数据进行(排序和)过滤,但遗憾的是,bool filterAcceptsRow( int const &, QModelIndex const & ) 中定义的过滤技术不允许传递自定义仿函数,因此仿函数用作过滤函数,而不是在 filterAcceptsRow 中进行过滤。
这就是我要说的,假设有人想在一个已经生成的乘法表(12 x 12)中找出所有偶数,目前我认为这是可以通过 QSortFilterProxyModel::filterAcceptsRow( ... ) 实现的
QSortFilterProxyModel::filterAcceptsRow( int source_row, ... )
{
return sourceModel()->data( source_row ).toInt() % 2 == 0;
}
我想要的不仅仅是按偶数过滤,有没有一种方法可以通过将不同的仿函数传递给 filterAcceptsRow(...) 来进行各种过滤?像 std::sort( , , lambda_expression ) 或 std::for_each( , , lambda ) 等,以便按相关性、日期、时间进行过滤将调用相同的函数,但具有不同的仿函数。
编辑:对于非常糟糕的格式,我深表歉意,我的手机可以做的非常少
最佳答案
根据 docs - 不,不是。 filterAcceptsRow()
的目的是提供自定义机制。
Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions.
因此,您可以通过一些修改来实现您的自定义 QSortFilterProxyModel,这些修改将支持 filterAcceptsRow()
中的仿函数。例如:
class FilterFunc
{
protected:
const QSortFilterProxyModel * proxy_;
public:
FilterFunc() : proxy_(0) {}
FilterFunc(const QSortFilterProxyModel * p) : proxy_(p) {}
bool operator()(int source_row, const QModelIndex & source_parent) {return true;}
};
class CustomSortFilterProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
FilterFunc filter_;
protected:
virtual bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const {
return filter_(source_row, source_parent);
}
public:
void setFilter(FilterFunc f) {filter_ = f;}
};
用法:
struct CustomFilter : public FilterFunc
{
bool operator()(int source_row, const QModelIndex & source_parent) {
return proxy_->sourceModel()->data( source_row ).toInt() % 2 == 0;
}
};
//...
CustomSortFilterProxyModel pm;
pm.setFilter(CustomFilter(&pm));
...
//operations that will call filterAcceptsRow()
要使用 C++11 lambda - 将 FilterFunc
替换为 std::function
,将第三个参数添加到 filterAcceptsRow()
- 的对象QSortFilterProxyModel
类型,并使用 std::bind
。
关于c++ - QSortFilterProxyModel::filterAcceptRows 是否可自定义以接受仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545633/