[PyQt] QAbstractItemModel parent() receives messy model index...

Dirk Wagener dwagen at stonethree.com
Mon Sep 10 09:40:01 BST 2007


I am using a QTreeView with my own QAbstractItemModel implementation.
My implementation of the parent method looks like this:

   1.     def parent(self, index):
   2.         if not index.isValid():
   3.             return QtCore.QModelIndex()
   4.         childItem = index.internalPointer()
   6.         # Make sure this item is valid! If not, we return an
      invalid model index.
   7.         if not isinstance(childItem, TreeNode):
   8.             logging.warning('Expected a TreeNode instance, but got
      something else.')
   9.             logging.warning('Object received: ' + str(childItem))
  10.             return QtCore.QModelIndex()      
  12.         parentItem = childItem.parent()
  13.         if parentItem == self.rootItem:
  14.             return QtCore.QModelIndex()
  15.         return self.createIndex(parentItem.row(), 0, parentItem)

The problem is this:
My underlying model data is of type TreeNode (my own class). I would 
expect the childItem (line 4) to always
be of type TreeNode, but sporadically I get something else! When that 
happens, lines 8, 9 and 10 executes and my program
throws an exception!
How is this possible? How can parent() receive a model index pointing to 
something that is NOT my underlying data class?
How do I handle this. Returning an invalid model index (line 10), does 
not work, since I get an exception after that.

Kind regards
Dirk Wagener

More information about the PyQt mailing list