实现一个QAbstractItemModel迭代器

暗黑

我一直在尝试着如何为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; });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章