实现一个QAbstractItemModel迭代器
Implementing a QAbstractItemModel Iterator
我一直在努力了解如何为QAbstractItemModel开发一个标准样式的迭代器,但遇到了相当大的困难。我可以使用深度优先或广度优先算法来搜索模型,但当涉及到将这些模式应用于迭代器时,我不知道如何进行。如果有人能直接告诉我(可能有伪代码),或者他们有一个愿意分享的例子,我将不胜感激。
感谢
C++14
迭代器,用于给定角色的QAbstractItemModel
的行。它只在模型的行上迭代,列保持不变。
class ModelRowIterator : public std::iterator
<
std::input_iterator_tag, // iterator_category
QVariant, // value_type
int, // difference_type
const QVariant*, // pointer
QVariant // reference
>
{
QModelIndex index_;
int role_ = 0;
public:
ModelRowIterator() {}
ModelRowIterator(const QModelIndex& index, int role) : index_(index), role_(role) {}
ModelRowIterator& operator++()
{
if (index_.isValid())
index_ = index_.model()->index(index_.row()+1, index_.column());
return *this;
}
ModelRowIterator operator++(int)
{
ModelRowIterator ret = *this;
++(*this);
return ret;
}
bool operator==(const ModelRowIterator& other) const
{
return (!other.index_.isValid() && !index_.isValid()) // ending condition
|| (other.index_ == index_ && other.role_ == role_);
}
bool operator!=(const ModelRowIterator& other) const
{
return !(other == *this);
}
reference operator*() const
{
return index_.isValid() ? index_.data(role_) : QVariant{};
}
};
注意:std::iterator
在C++17
中已弃用。
用法:
QAbstractItemModel model;
int role = ...;
ModelRowIterator begin { model.index(0,0), role };
ModelRowIterator end {};
std::for_each(begin, end, [](const QVariant& v) { qDebug() << v; });
auto range = boost::make_range(begin, end);
boost::range::equal(range, [](const QVariant& v) { qDebug() << v; });
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '