Important: Please read the Qt Code of Conduct -

QGraphicsScene clear() problems

  • I have this custom class which inherits from QGraphicsRectItem.

    class CellGraphic : public QGraphicsRectItem
    static QColor active, inactive, noConnection;

    Cell *cell;
    bool isBorderCell;

    // Various functions

    I create a number of these on the heap and add them to a QGraphicsScene object. Every once in a while I need to dump them and create the scene from scratch, so I empty the scene by calling clear() and then create new ones which I add to the scene.

    This works as expected, but only until they've received a manual call to the update() function. Here is the paint function:
    [code]void CellGraphic::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget){

    if(cell == nullptr || isBorderCell)
        painter->fillRect(rect(), noConnection);
    else if(!cell->currentState)
        painter->fillRect(rect(), inactive);
        painter->fillRect(rect(), active);


    When I clear the scene after the object has been drawn with the last 'else' condition, the debugger immediately takes me to a heap breakpoint.

    If I'm in release mode the program works as expected, though I may be seeing a slight memory leak. It's a bit difficult to determine without more extensive testing.

    Anyway, being new at Qt and not very experienced in C++ I guess I'm just wondering what I'm doing wrong here. I was under the impression that the scene would handle the objects once added, and that clear() would delete them properly.

    Nevermind, just me being an idiot. I fixed a tricky invalid pointer problem elsewhere in the code that must have been corrupting the CellGraphic objects, because clearing the container works flawlessly now.

Log in to reply