首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QAbstractItemModel迭代器的实现

QAbstractItemModel迭代器的实现
EN

Stack Overflow用户
提问于 2014-11-11 21:36:54
回答 1查看 500关注 0票数 3

我一直在努力研究如何为一个QAbstractItemModel开发一个标准风格的迭代器,现在我已经被困住了。我可以使用深度优先或广度优先算法搜索模型,但当涉及到将这些模式应用于迭代器时,我不知道如何继续。如果有人能直接给我指点(可能是伪代码),或者他们有一个他们愿意分享的例子,我会非常感激的。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-21 08:29:55

C++14迭代器对给定角色的QAbstractItemModel行进行迭代。它只在模型的行上迭代,列保持不变。

代码语言:javascript
复制
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::iteratorC++17中不受欢迎。

用法:

代码语言:javascript
复制
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; });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26875039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档