从 QAbstractItemModel 中正确删除子树

Properly remove subtree from QAbstractItemModel

本文关键字:删除 QAbstractItemModel      更新时间:2023-10-16

我不清楚从 QAbstractItemModel 派生的自定义模型类中删除分支的正确方法是什么。我有一个应该刷新树节点的方法(删除所有子分支并插入新分支(。

void SessionTreeModel::refresh(const QModelIndex &index, const DbObjectI *object)
{
auto item = getItem(index);
assert(item != nullptr);
if (item != nullptr)
{
if (item->childCount() > 0)
{
beginRemoveRows(index, 0, item->childCount() - 1);
item->removeAll();
endRemoveRows();
}
if (object != nullptr && object->getChildCount() > 0)
{
beginInsertRows(index, 0, static_cast<int>(object->getChildCount()) - 1);
item->appendChildren(object);
endInsertRows();
}
}
}
void SessionTreeItem::removeAll()
{
for (auto& child : childItems_)
{
child->removeAll();
}
childItems_.clear();
}

问题是,当调用"beginRemoveRows(("时,应用程序经常在几次刷新后崩溃,根据调用堆栈,问题是SessionTreeModel::p arent((被调用时有一个包含悬空内部指针的索引。

QModelIndex SessionTreeModel::parent(const QModelIndex &child) const
{
if (child.isValid())
{
auto childItem = getItem(child);
auto parentItem = childItem->parent();
if (parentItem != nullptr &&
parentItem != rootObject_.get())
{
return createIndex(static_cast<int>(parentItem->childCount()),
0, parentItem);
}
}
return QModelIndex{};
}

看起来树视图正在保存已删除的项目的索引,并试图获取其父项。

你能告诉我可能出了什么问题吗?

首先,我要感谢谢夫的评论。我很高兴我不必朝这个方向走;)

经过几个小时的深入研究我的代码,我终于发现了问题所在。真是个愚蠢的人!在 parent(( 方法中,索引是使用 parentItem->childCount(( 而不是 parentItem->row(( 创建的。