我已经实现了自己的QAbstractListModel
,它是基于std::vector
的。现在我想在QGraphicsScene
中显示这个模型的内容。为此,我实现了自己的QGraphicsItem
,它将QPersistentModelIndex
存储为指向数据的指针。
我按照以下方式实现了removeRows
方法:
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
错误:
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个元素时):
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)
发布于 2016-02-05 15:29:24
好吧,您不需要篡改changePersistentIndex,调用beginRemoveRows和endRemoveRows将自动更新模型中当前存在的所有持久索引。删除行后唯一应该具有的无效QPersistentModelIndex是实际已删除的行的索引。
https://stackoverflow.com/questions/32865841
复制相似问题