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:
Node* TreeModel::addSubNode(Node* parent)
{
Node* subnode = new Node(Node::SubNode, parent->getId());
int position = parent->getChildCount();
beginInsertRows(parentIndex, position, position);
parent->addChild(subnode);
endInsertRows();
emit layoutAboutToBeChanged();
parent->sortSubNodes();
emit layoutChanged();
return subnode;
}
bool lessThan(Node* node1, Node* node2)
{
return node1->getValue() < node2->getValue();
}
void Node::sortSubNodes()
{
qSort(children.begin(), children.end(), lessThan);
}
Node* TreeModel::addSubNode(Node* parent)
{
Node* subnode = new Node(Node::SubNode, parent->getId());
QModelIndex parentIndex = getIndexForNode(parent);
int position = parent->getChildCount();
beginInsertRows(parentIndex, position, position);
parent->addChild(subnode);
endInsertRows();
emit layoutAboutToBeChanged();
parent->sortSubNodes();
emit layoutChanged();
return subnode;
}
bool lessThan(Node* node1, Node* node2)
{
return node1->getValue() < node2->getValue();
}
void Node::sortSubNodes()
{
qSort(children.begin(), children.end(), lessThan);
}
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
Bookmarks