从 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(( 创建的。
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 如何从存储在std::映射中的std::集中删除元素
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数