我已经实现了我自己的QAbstractListModel
,它基于std::vector
. 我现在想在QGraphicsScene
. 为此,我实现了我自己的QGraphicsItem
,它将 a 存储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
错误?
更新
我已经removeRows()
用@Sebastian Lange 的增强功能改变了它,但是它仍然没有按预期工作并且我收到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)