QModelIndex becomes invalid when deleting rows

I am subclassing QAbstractItemModel

to display items in QTreeView

, and in this subclass ( projectModel

) I have a function to remove the currently selected index in the tree view. Component

is the class used to represent all members of the model:

void
projectModel::deleteComponent()
{
    QModelIndex child_index = _treeview->selectionModel()->currentIndex();
    Component* child = static_cast<Component*>(child_index.internalPointer());

    Component* parent = child->Parent();
    QModelIndex parent_index = createIndex(parent->row(), 0, parent);

    int row = child->row();

    beginRemoveRows(parent_index, row, row);
    parent->delete_child(child);
    endRemoveRows();
}

      

Parent and child characters and raw pointers are fine just before the call beginRemoveRows

; The debugger shows that they point to the correct element and its parent. However, the program is called after being called beginRemoveRows

. Specifically, it falls into projectModel::parent()

:

QModelIndex
projectModel::parent(const QModelIndex &index) const
{    
    if (!index.isValid())
        return QModelIndex();

    Component* item = getItem(index);        //Fails to cast index internal pointer to a valid Component*
    Component* parentItem = item->Parent();

    if (parentItem == _rootnode)
        return QModelIndex();

    return createIndex(parentItem->row(), 0, parentItem);
}

      

When I crash the crash and check the debugger output, it shows that the variable item

in the function parent()

is garbage. Somehow it looks like mine is QModelIndex

corrupted between call deleteComponent

and call parent

. Is there something glaring I am doing, or is the problem perhaps more subtle?

+3


source to share


1 answer


This is fully expected.

Volatile indexes are valid until you change the structure of the model. A structural change is any change that is signaled differently than radiation dataChanged

.

Structural change should be seen as barriers to the life of the index: you should discard any volatile indexes held in place prior to structural change.



Depending on where it is called deleteComponent

, the chance that the caller has some indices deleteComponent

invalidates them and you are now in the scope of undefined behavior.

You need to use persistent indexes if you want them to remain valid for structural changes, and even then they will only be valid if the given item still exists. If you are using your own model, you need to explicitly maintain persistent indexes, and the users of your model must use them.

+7


source







All Articles