首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >removeRows()和QPersistentModelIndex

removeRows()和QPersistentModelIndex
EN

Stack Overflow用户
提问于 2015-09-30 12:16:38
回答 1查看 2.7K关注 0票数 1

我已经实现了自己的QAbstractListModel,它是基于std::vector的。现在我想在QGraphicsScene中显示这个模型的内容。为此,我实现了自己的QGraphicsItem,它将QPersistentModelIndex存储为指向数据的指针。

我按照以下方式实现了removeRows方法:

代码语言:javascript
运行
复制
bool VectorModel::removeRows(int row, int count, const QModelIndex& parent) {
    if (row + count < _vector.size()) {
        beginRemoveRows(QModelIndex(), row, row + count);
        _vector.erase(_vector.begin() + row, _vector.begin() + row + count);
        endRemoveRows();
        return true;
    }
    return false;
}

现在,由于我删除了一些元素,以下元素的索引将发生变化。因此,需要对QPersistentModelIndex进行调整。

我已经在changePersistentIndex()中找到了QAbstractItemModel方法,并且我知道可以使用persistentIndexList()获得所有持久索引。但是,我不知道如何使用这种方法相应地调整索引。这是如何做到的呢?

更改这些索引是否足以防止Invalid index错误?

更新

我已经用@Sebastian的增强功能更改了removeRows(),但是它仍然不能像预期的那样工作,并且我收到了Invalid index错误:

代码语言:javascript
运行
复制
bool LabelModel::removeRows(int row, int count, const QModelIndex& parent) {
    Q_UNUSED(parent)
    if (row + count < _vector.size()) {
        beginRemoveRows(QModelIndex(), row, row + count);
        _vector.erase(_vector.begin() + row, _vector.begin() + row + count);
        endRemoveRows();

        auto pil = persistentIndexList();
        for(int i = 0; i < pil.size(); ++i)
        {
            if (i >= row + count) {
                changePersistentIndex(pil[i], pil[i-count]);
            }
        }
        return true;
    }
    return false;
}

发出的错误如下所示(删除第7个元素时):

代码语言:javascript
运行
复制
QAbstractItemModel::endRemoveRows:  Invalid index ( 7 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 8 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 9 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 10 , 1 ) in model QAbstractListModel(0x101559320)
QAbstractItemModel::endRemoveRows:  Invalid index ( 6 , 1 ) in model QAbstractListModel(0x101559320)
EN

回答 1

Stack Overflow用户

发布于 2016-02-05 15:29:24

好吧,您不需要篡改changePersistentIndex,调用beginRemoveRows和endRemoveRows将自动更新模型中当前存在的所有持久索引。删除行后唯一应该具有的无效QPersistentModelIndex是实际已删除的行的索引。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32865841

复制
相关文章

相似问题

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