QTreeView / QAbstractItemModel - 删除导致异常

时间:2016-10-11 02:27:26

标签: c++ qt exception qtreeview qabstractitemmodel

我编写了一个派生自QAbstractModelItem的类。它用在QTreeView上。遗憾的是,官方文档示例未显示如何在模型上添加或删除项目。我认为这很容易做到,所以我通过它破解了。问题是删除所选对象会导致异常。例如:

用户单击QTreeView上的一行,并希望将其所有子项(如果有)删除。这是执行的代码:

MyModel.cpp:

// This gets called with the QModelIndex of the currently selected row.
void MyModel::remove(const QModelIndex &index) {
    if (!index.isValid()) 
        return;
    MyItem * selectedItem = static_cast<MyItem*>(index.internalPointer());
    beginRemoveRows(index, index.row(), index.row());
    // Call the method on the selected row object that will delete itself and all its children:
    selectedItem->destroy();
    endRemoveRows();
}

MyItem.h:

// A pointer list with child items.
std::vector<MyItem*> children;

MyItem.cpp:

// Deletes all children of this object and itself.
void MyItem::destroy(bool isFirst) {
    if (children.size() > 0) {
        // Each child needs to run this function, to ensure that all nested objects are properly deleted:
        for each (auto child in children)
            child->destroy(false);
        // Now that the children have been deleted from heap memory  clear the child pointer list:
        children.clear();
    }
    // This boolean determines wether this object is the selected row/highest object in the row hierachy. Remove this object from the parent's pointer list:
    if(isFirst)
        parent->removeChild(this);
    // And lastly delete this instance:
    if(!isFirst) // This will cause a memory leak, but it is necessary
        delete this; // <- because this throws an exception if I run this on the first object.
}

// Removes a single child reference from this instance's pointer list.
void MyItem::removeChild(MyItem * child)
{
    auto it = std::find(children.begin(), children.end(), child);
    children.erase(it);
}

现在,如果我们不介意轻微的内存泄漏,这样就行了。 ^^

但是如果我尝试在第一个/所选行对象上运行delete命令 - 则会出现以下两个异常之一:

  1. 这行有孩子: 抛出异常:读取访问冲突。这是0xDDDDDDDD。
  2. 该行没有孩子: 抛出异常:写入访问冲突。 _Parent_proxy为0x64F30630。
  3. 我保持代码简短,但希望它包含我的错误。或者有人知道一个很好的QTreeView / QAbstractItemModel示例,它显示了如何添加/删除项目吗?

    亲切的问候 空

1 个答案:

答案 0 :(得分:0)

我认为MyModel::remove方法存在错误。 beginRemoveRows将父索引作为第一个参数,而不是索引本身。 Yuo必须用这个代替这条线:

beginRemoveRows(index.parent(), index.row(), index.row());