I need to delete objects in mainwindow?
-
wrote on 11 Sept 2013, 21:31 last edited by
@MainWindow::~MainWindow()
{
delete ui;
}@This is default code when I create a project in Qt Creator. It's necessary? I think after close program OS will delete it automatically.
-
Hi,
Yes it's necessary, ui is allocated on the heap, so it must be deleted when not used anymore. Otherwise you would have a memory leak.
-
wrote on 11 Sept 2013, 21:57 last edited by
OK ui is necessary. How about QWidget object? Let's say it's created in MainWindow. Do I need to delete it on MainWindow's destructor?
@MainWindow::~MainWindow()
{
delete QWidget1; // Need?
delete QWidget2;// Need?
delete QWidget3;// Need?
delete ui;// OK
}@OK ui is needed to be delete but how I know which object need to be delete?
-
wrote on 12 Sept 2013, 06:30 last edited by
All objects that you allocated on the heap and which don't have a QObject parent set have to be deleted by you.
-
wrote on 12 Sept 2013, 10:28 last edited by
Hmm, OK.
Thanks
[quote author="KA51O" date="1378967418"]All objects that you allocated on the heap and which don't have a QObject parent set have to be deleted by you.[/quote] -
wrote on 12 Sept 2013, 11:37 last edited by
Just to clarify.
@
MainWindow: public QMainWindow
{
MainWindow(QObject* a_parent);
~MainWindow();QWidget m_StackWidget;
QWidget* m_HeapWidgetWithParent;
QWidget* m_HeapWidgetWithoutParent;
NoQObjectDerivedClass m_StackNoQObj;
NoQObjectDerivedClass* m_HeapNoQObj;
};MainWindow::MainWindow(QObject* a_parent)
{
// needs to be deleted by you
m_HeapWidgetWithoutParent = new QWidget();
//doesn't need to be deleted by you
m_HeapWidgetWithParent = new QWidget(this);
// needs to be deleted by you
m_HeapNoQObj = new NoQObjectDerivedClass();
}MainWindow::~MainWindow()
{
delete m_HeapWidgetWithoutParent;
delete m_HeapNoQObj;
}
@ -
wrote on 13 Sept 2013, 06:21 last edited by
Hi,
If this answered your question, set [SOLVED] in front of your first post! Saves other guys reading it. -
wrote on 18 Dec 2017, 00:10 last edited by
Hi,
Do you figure out that? I have the same question. Can you help me with that? -
Hi,
Do you figure out that? I have the same question. Can you help me with that?@Blizzard365 What question?
In C++ you have to free unused memory by yourself.
In Qt you don't have to delete children (widgets for example) which have parents - when parent is deleted the children are deleted automatically. See http://doc.qt.io/qt-5/objecttrees.html -
@Blizzard365 What question?
In C++ you have to free unused memory by yourself.
In Qt you don't have to delete children (widgets for example) which have parents - when parent is deleted the children are deleted automatically. See http://doc.qt.io/qt-5/objecttrees.htmlwrote on 19 Dec 2017, 08:40 last edited by@jsulm thx
I got it, ui is not a QObject. I have mistaken 'ui' as a QObject, and setUpUi(MainWindow) is setting parent for 'ui', which is unappropriate.