Removing layoutitem and deleting it yet still memory leak



  • Hi,

    for fun i created some sort of dice rolling app.
    It allows you to roll any amount of dices with any amount of pips. The result is shown as simply QLabels with the dices pips on them.
    I do this by having a seperate layout for the "result labels" that is added to my central layout and adding the needed amount of QLabels to it with every roll.
    At the start of the drawing of the result i simply erase the content of the "result layout".
    This apparently creates a memory leak.
    Here is the important part of my code:

    @void Widget::onRoll(void) //this is a slot
    {
    quint32 dicenumber = diceinput.text().toUInt();//how many dices were used
    quint32 dicetype = this->dicetype.text().toUInt(); //amount of pips
    clearLayout(diceresult);

    for(quint32 i = 0; i < dicenumber;i++)
    {
        diceresult.addWidget(QPointer<QLabel>(new QLabel(QString::number((qrand() % dicetype) + 1))));
    }
    
    update();
    

    }
    //this apparently results in a leak
    void Widget::clearLayout(QLayout& layout)
    {
    QLayoutItem* item;
    while(item = layout.takeAt(0))
    {
    item->widget()->setVisible(false);
    layout.removeWidget(item->widget());
    delete item;
    }
    }
    @

    When i click the "roll dice" button of my program it calls the "onRoll" slot.
    Why does the "delete item" call not lead to all dynamic memory being properly deleted?

    Btw i figured this had a leak by looking at the rising amount of memory the program used (provided by windows task manager)

    Any help would be great :)


  • Lifetime Qt Champion

    Hi,

    You also need to delete the widget



  • Hi,

    thank you :) This solved it.
    But i would like to understand why this worked and my first approach didnt.

    what i do now is simply
    @ QLayoutItem* item;
    while((item = layout.takeAt(0)) != 0)
    {
    item->widget()->setVisible(false);
    delete item->widget();
    delete item;
    }@

    why is the dynamic memory not released by calling "delete item"?


  • Moderators

    because the item doesn't take ownership of the widget itself... IIRC this should be mentioned somewhere in the docs.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.