I have a simple node graph editor in c++/Qt that uses QGraphicsView/QGraphicsScene to draw the graph and I'm experiencing a weird issue where QGraphicsItems sometimes remain on the scene for a split second after calling scene.removeItem(Item). I'm deleting the the items right after removing them from the scene so it's causing segfaults. When I comment the deletion out I can see a part of the item being drawn (not the whole thing) for a literal second before it disappears completely.
Here's my code. It's a slot that gets called by a when a connection gets removed.
void GraphScene::connectionRemoved(QUuid uuid)
{
//Connections and nodes are stored in QMaps to retrieve them by uuid
ConnectionGraphicsItem *connectionItem = connections.value(uuid);
if (connectionItem == nullptr) return;
removeItem(connectionItem); //Delayed
//delete connectionItem;
qDebug() << "con removed" << uuid;
}
I tried calling prepareGeometryChange() before removing the item from the scene and it didn't fix it. Setting QGraphicsView update mode to FullViewportUpdate didn't help either.
I've solved the problem. Qt Docs for
void QGraphicsItem::prepareGeometryChange()
state that you need to call this method before changing the bounding rectangle of the item so that the graphics scene updates its index. I didn't do this. So when I added this before the code that adjusts the connections to match node ports the problem disappeared.
Edit: Also, I've realized that I don't remove the item from the QMap.