PDA

View Full Version : QAbstractItemModel::beginRemoveRows/endRemoveRows



SiS-Shadowman
12th July 2010, 09:56
I've been using Qt for over a year and I really like this software, however I have some big issues concerning the removal of rows in a tree model.

I've created a tree structure,


class Node
{
weak_ptr<Node> parent;
std::vector<shared_ptr<Node>> children;
QString name;
}

and implemented QAbstractItemModel to display the name in a QTreeView. The view correctly displays the data and I can easily add new rows, however removing them causes crashes. This is because during the painting process, the view calls my model with QModelIndexes that should have been removed (this happens after beginRemoveRows/endRemoveRows). Currently I rely on the fact that when I am given a QModelIndex, I can fetch the internal pointer and cast it to one of my nodes (since that is how I've created that index).

Acoording to the documentation I have to call beginRemoveRows before touching the underlying data of my model and endRemoveRows after I've changed it. However when I do it like this, the view tries to paint QModelIndexes that are no longer valid for this model. This would not be a problem if I could store a QVariant instead of a void pointer (the problem is that no shared_ptr is holding the node anymore, thefore an access violation occurs).

I could solve this problem if I simply keep a set of all "valid" nodes in my model but I would really hate to do so.
This problem occurs in Qt 4.6.1.
Does anyone have a suggestion on what might be going wrong and if there's a fix for that?

*edit*
It seems I have fixed the problem now. Due to this forum I found ModelTest which I applied to my model. Seems that my parent implementation (and others) was quite flawed.
I wish I had known this test before, it's an awesome tool to find bugs in tree models.