I have a custom QAbstractItemModel connected to a QTreeView. The model supports a basic two-tiered item hierarchy with nodes and sub-nodes. The code that i have attempts to sort the sub-nodes based on an internal attribute whenever they are added or updated.

for example:
Qt Code:
  1. Node* TreeModel::addSubNode(Node* parent)
  2. {
  3. Node* subnode = new Node(Node::SubNode, parent->getId());
  4.  
  5. QModelIndex parentIndex = getIndexForNode(parent);
  6. int position = parent->getChildCount();
  7.  
  8. beginInsertRows(parentIndex, position, position);
  9. parent->addChild(subnode);
  10. endInsertRows();
  11.  
  12. emit layoutAboutToBeChanged();
  13. parent->sortSubNodes();
  14. emit layoutChanged();
  15.  
  16. return subnode;
  17. }
  18.  
  19. bool lessThan(Node* node1, Node* node2)
  20. {
  21. return node1->getValue() < node2->getValue();
  22. }
  23.  
  24. void Node::sortSubNodes()
  25. {
  26. qSort(children.begin(), children.end(), lessThan);
  27. }
To copy to clipboard, switch view to plain text mode 

Adding nodes and sub-nodes works fine, but when i start to remove them things start breaking down. A segfault tends to appear in beginRemoveRows with a QModelIndex with an invalid internalPointer. I'm fairly confident however that i only create nodes with pointers to valid parents. If i don't do the sorting the crash dissapears and things seem stable. Is it possible to do the sorting in this way or must i add a QSortFilterProxyModel?

Thank you for your time,
/TR