从QAbstractItemModel正确删除子树

问题描述 投票:0回答:1

对我来说,不清楚从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 :: parent()被调用并带有索引悬空的内部指针。

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{};
}

似乎树形视图为已被删除并试图获取其父项的项保留索引。

您能告诉我出什么问题吗?

c++ qt crash qabstractitemmodel
1个回答
0
投票

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

经过花了几个小时研究我的代码,我终于找到了问题。确实是一个愚蠢的人!在parent()方法中,使用parentItem-> childCount()而不是parentItem-> row()创建索引。

© www.soinside.com 2019 - 2024. All rights reserved.