C++ removeRows()和QPersistentModelIndex
我已经实现了自己的C++ removeRows()和QPersistentModelIndex,c++,qt,model,qabstractitemmodel,qabstractlistmodel,C++,Qt,Model,Qabstractitemmodel,Qabstractlistmodel,我已经实现了自己的QAbstractListModel,它基于std::vector。现在我想在qgraphicscene中显示此模型的内容。为此,我实现了自己的QGraphicsItem,它将QPersistentModelIndex存储为指向数据的指针 我已经实现了如下方法: bool VectorModel::removeRows(int row, int count, const QModelIndex& parent) { if (row + count < _v
QAbstractListModel
,它基于std::vector
。现在我想在qgraphicscene
中显示此模型的内容。为此,我实现了自己的QGraphicsItem
,它将QPersistentModelIndex
存储为指向数据的指针
我已经实现了如下方法:
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;
}
发出的错误如下所示(删除第7个元素时):
好的,您不需要修改changePersistentIndex,调用beginRemoveRows和endRemoveRows将自动更新模型上当前存在的所有持久性索引。删除行后应具有的唯一无效QPersistentModelIndex是实际删除的行上的索引只需将删除元素后的每个索引的行数减少一即可。就我个人而言,我不喜欢使用持久性索引。谢谢你的回答!我试图这样做(请参阅更新),但仍然收到无效索引
错误。
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;
}
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)