我一直在努力研究如何为一个QAbstractItemModel开发一个标准风格的迭代器,现在我已经被困住了。我可以使用深度优先或广度优先算法搜索模型,但当涉及到将这些模式应用于迭代器时,我不知道如何继续。如果有人能直接给我指点(可能是伪代码),或者他们有一个他们愿意分享的例子,我会非常感激的。
谢谢
发布于 2020-11-21 08:29:55
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; });https://stackoverflow.com/questions/26875039
复制相似问题