我一直在努力思考如何为 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; });
关于c++ - 实现 QAbstractItemModel 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875039/