c++ - QModelIndex becomes invalid when removing rows -


i'm subclassing qabstractitemmodel display items in qtreeview, , within subclass (projectmodel), have function delete currently-selected index in tree view. component class used represent members of 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(); } 

the parent , child indicies , raw pointers before call beginremoverows; debugger shows point correct item , parent. however, program crashes after calling beginremoverows. specifically, crashes in projectmodel::parent():

qmodelindex projectmodel::parent(const qmodelindex &index) const {         if (!index.isvalid())         return qmodelindex();      component* item = getitem(index);        //fails cast index internal pointer valid component*     component* parentitem = item->parent();      if (parentitem == _rootnode)         return qmodelindex();      return createindex(parentitem->row(), 0, parentitem); } 

when break on crash , examine debugger output, shows variable item in parent() function garbage. somehow looks qmodelindex gets corrupted between call deletecomponent , call parent. there blatantly wrong i'm doing, or problem perhaps more subtle?

this expected.

non-persistent indices valid until change structure of model. structural change change signaled other emitting datachanged.

structural changes must considered barriers index lifetime: must discard non-persistent indices held before structural change.

depending on deletecomponent called, happens caller holds indices, deletecomponent invalidates them all, , you're in undefined behavior territory there onwards.

you need use persistent indices if want them stay valid on structural changes, , they'll valid if given item still exists. if you're using own model, need explicitly support persistent indices, , users of model must use them.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -