Reputation: 193
I have this (minimal example) code in my mainwindow.cpp
:
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent) {
setWindowTitle("Drawing Window");
setFixedSize(800, 600);
auto *layout = new QVBoxLayout(this);
auto *hlayout = new QHBoxLayout();
// Create the Button
button = new QPushButton("Load Image", this);
button->setGeometry(10, 10, 80, 30);
// Create the drawing area
drawingArea = new QLabel(this);
drawingArea->setFixedSize(512, 512);
layout->addWidget(button);
hlayout->addWidget(drawingArea);
layout->addLayout(hlayout);
}
main.cpp
:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
From what I understand, Qt should handle the memory of my layouts by itself, due to the parent-child relations.
However: CLion shows the warning Allocated memory is leaked
in the lines:
auto *layout = new QVBoxLayout(this);
auto *hlayout = new QHBoxLayout();
Running this code with Valgrind, I get the following warnings:
Leak_DefinetlyLost - 2 Warnings
Leak_PossiblyLost - 136 Warnings
UninitCondition - 209 Warnings
Is there an issue with my code? Should I delete my Layouts in the destructor? Why? Doesn't Qt handle this for me?
Upvotes: 6
Views: 276
Reputation: 85
Following the advice of Sir Nate, we can found that in your example layout
does not have a parent.
The problem here is that
QMainWindow objects come with their own customized layout and setting a layout on a the actual main window, or creating a layout with a main window as a parent, is considered an error. You should always set your own layout on the central widget instead.
as stated at Qt official Menus Example in section called "MainWindow Class Implementation".
As a result, when you create QVBoxLayout
with this
argument it fails to set parent for layout
. Thus, neither the layout
nor its child hlayout
will be deleted.
To achieve proper memory management you should create and set a central widget for main window and then add layout
into it. You can also find code example at the link above.
Upvotes: 1