CrystalJake
CrystalJake

Reputation: 897

How to delete an item from model view?

I am using QTreeView and QAbstractItemModel to establish view whose data also comes from a tree structure. But when I delete a node from a tree structure(data source), then I found that the model view can't automatically adjust itself, it also use the invalid pointer which I don't know it points to which memory block. I don't know how to refresh or what I need to do to fix this problem.

Upvotes: 0

Views: 2221

Answers (1)

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

To delete data from the model, use beginRemoveRows() and endRemoveRows(). beginRemoveRows tells the model that you will now change the underlying data structure. Then change the structure and call endRemoveRows when done. endRemoveRows will then trigger the notifications to update the views:

beginRemoveRows(QModelIndex(), 0, 0);
m_topLevelNodes.remove(0);
endRemoveRows();

This removes the first top-level row (and its children), assuming that the underlying structure in your model keeps the top-level tree items in a container named m_topLevelNodes.

Upvotes: 3

Related Questions