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.



  • Hi,
    Do you figure out that? I have the same question. Can you help me with that?


  • Moderators

    @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



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


Log in to reply
 

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