Important: Please read the Qt Code of Conduct -

Memory problem with QVector of QGraphicsLineItem objects

  • Hi,

    I am trying to have in my QGraphicsScene a number of lines that update whenever the window is resized, but my problem comes when I want to clear the update the QVector by clearing and appending the updated QGraphicsLineItem objects.
    Basically my problem is that whenever I try to clear the QVector, not all the memory allocated to it is released.

    Simplifying my code as far as I can gives me the following, but my issue persist:

    // declare and initialise QVector
    QVector<QGraphicsLineItem *> *xGrid = new QVector<QGraphicsLineItem *>();

    // fill the QVector with a few QGraphicsLineItem objects
    for (int i = 0; i < 1000000; i++) {
    xGrid->append(new QGraphicsLineItem(10, 10, 10, 10));


    qDebug() << xGrid->size(); // this prints 1000000

    // clear the QVector trying to free the allocated memory
    qDebug() << xGrid->size(); // this prints 0


    Right after that for loop, my application is using about 354 Megabytes of memory (starting from 13.5 Mb).
    After the clear(), my application uses about 350 Megabytes of memory, so I guess something is clearly wrong of I am missing something here, as I would expect my memory usage to back to 13.5 Mb.

    Any advice would be helpful


  • Ok I think i figured it out.
    I need to delete every QGraphicsLineItem object individually like so

    for (int i = 0; i < xGrid->size(); i++) {
    delete xGrid->at(i);


    And then at the end I clear the QVector.

    By looking at the memory usage from Task Manager, for some reason I still feel like I need to do one last step. Can anyone confirm whether this is all I need to do?


  • You can also use


    To really get the memory usage down to your starting point you would have to call


    as well, after the clear(). (Though the actual use of this is rather limited in most cases)

Log in to reply