PDA

View Full Version : Memory leaks!



karlkar
28th June 2013, 19:57
I have such a code and I wonder how should I clean up after it? Should I delete all elements one by one? Should I delete also layouts? Or can I delete just the main element - parent of every other and hope that he will clean up the rest of them?


TableTab::TableTab(QWidget *parent) :
QWidget(parent)
{
objectNameLabel_ = new QLabel;
personLabel_ = new QLabel;
tableWidget_ = new RequestTable(parent);
summaryBox_ = new QGroupBox;
commentaryTextEdit_ = new QPlainTextEdit;
normatywLabel_ = new QLabel;
sumLabel_ = new QLabel;
reInvoiceLabel_ = new QLabel;
QGroupBox *calculationsBox = new QGroupBox;

objectNameLabel_->setText("OBIEKT 1");
personLabel_->setText("JOLA");
normatywLabel_->setText("666");
sumLabel_->setText("667");
reInvoiceLabel_->setText("668");

QBoxLayout *layout = new QVBoxLayout;
layout->addWidget(normatywLabel_);
layout->addWidget(sumLabel_);
layout->addWidget(reInvoiceLabel_);
calculationsBox->setLayout(layout);

layout = new QHBoxLayout;
layout->addWidget(commentaryTextEdit_);
layout->addWidget(calculationsBox);
summaryBox_->setLayout(layout);

layout = new QVBoxLayout;
layout->addWidget(objectNameLabel_);
layout->addWidget(personLabel_);
layout->addWidget(tableWidget_);
layout->addWidget(summaryBox_);
setLayout(layout);
}

Zlatomir
28th June 2013, 22:37
You don't need to delete any of those, you just need to make sure that the class instance (that's the parent of everything in there) is deleted (either by allocating on stack or by setting a mainwindow parent that is allocated on stack or explicitly deleted if allocated on heap and it doesn't have another parent), so basically you need to delete only the QObjects that don't have a parent - those objects when deleted will delete their children. //of course for the classes that doesn't take part in QObject's parent-child relation-ship the standard C++ rules apply.

Anyway you can read more about parent-children in the documentation here (https://qt-project.org/doc/qt-4.8/objecttrees.html)