I need to delete objects in mainwindow?



  • @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.


  • Lifetime Qt Champion

    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.



  • 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?



  • All objects that you allocated on the heap and which don't have a QObject parent set have to be deleted by you.



  • 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]



  • 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;
    }
    @



  • Hi,
    If this answered your question, set [SOLVED] in front of your first post! Saves other guys reading it.


Log in to reply
 

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