c++ - 实现 QAbstractItemModel 迭代器

标签 c++ qt iterator iteration 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::iteratorC++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/

相关文章:

c++ - GNU GCC (g++) : Why does it generate multiple dtors?

c++ - 使用没有初始化的类成员函数

python - Python 字典列表的 C++ 等价物?

c++ - 如何以我的系统区域设置语言获取语言/国家/地区名称

c++ - 使用动态创建的 QRadioButtons 切换动态创建的对象

c++ - 迭代器等价于空指针?

c++ - 来自具有大小的 char * 缓冲区的双向迭代器

c++ - 将 va_arg 传递给函数两次会得到相同的值

python - 你有 py-poppler-qt 的例子吗?

C++ 从具有取消引用类型类型的函数返回引用?