PDA

View Full Version : QTreeView with QAbstractItemModel



Fletcher
10th December 2009, 21:37
I've subclassed both of the subject line classes in order to create a simple tree where the user can drag and drop the nodes to rearrange the tree. Everything was working fine until I wanted to essentially "reload" the tree (in case of a database change, for instance). Now the program is unstable and will crash at random, I believe because my QModelIndex.internalPointer()s become invalid (I found one pointing to a random place in memory in the QAbstractItemModel.parent() implementation).

The thing is, I am not saving QModelIndexes anywhere in my code and the program is crashing in the event loop during calls to parent(). So I do not understand how the pointers become invalid.

To reload the tree, I am deleting and recreating the underlying tree entirely and then emitting signal layoutChanged(). I feel this must be where I am messing up.

Anyway, I have no idea where to look really, and I can't just post my entire code. How would you go about switching the underlying tree?

squidge
10th December 2009, 21:47
Are you emitting layoutAboutToBeChanged too? You need both. This one before you make the changes, and layoutChanged afterwards.

AwareWolf
10th December 2009, 21:48
To reload the tree, I am deleting and recreating the underlying tree entirely and then emitting signal layoutChanged().

Are you actually deleteing the tree (view) or the QAbstractItemModel? Or are you just setting the root node of the QAbstractItemModel to a new root node?

Fletcher
10th December 2009, 22:54
I am using layoutAboutToBeChanged().

Here's what I'm doing. It's PyQt. I have a tree made of TreeItem()s (my node class)



# in subclass of QAbstractItemModel
def recreateTree(self):
self.emit(QtCore.SIGNAL('layoutAboutToBeChanged()' ))
self.root = TreeItem(None)
# omitted code to generate the other nodes and add them to root
self.emit(QtCore.SIGNAL('layoutChanged()'))


When I reassign self.root, Python automatically deletes the old tree (or should) since there's no other reference to it.

Fletcher
11th December 2009, 00:02
After looking through the API a bit more I've changed my function a bit and it *seems to be working*. I really hate this feeling though, where I do not really understand what the API is doing behind my back.



# in subclass of QAbstractItemModel
def recreateTree(self):
self.root = TreeItem(None)
# [omitted code to generate the other nodes and add them to root]
self.reset() # default implementation. I don't really know what it does