1
votes

One of our teacher asked us to create a Qt application without any UI file for the main window (a QMainWindow). Usually I always create one, leave it empty and let the uic deal with it.

I know that if a parental relation is defined between a widget (child) and its parent, then there is no need to delete the widget (deleted when the parent is deleted). So, when the UI is deleted, all the children are destroyed.

If we do not use an UI file (not generated), do we have to manually delete all the widget added to the GUI?

A little sample:

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent){
     layout = new QHBoxLayout(this);
     aButton = new QButton(this);
     layout->addWidget(aButton);
     ...
}

MainWindow::~MainWindow(){
    delete ui; // No need to delete more if parental relation.
    // However, what do we do if no ui has been generated?
    // Do we have to delete aButton?
}

The value of parent is 0. It is the main entry of the application.

Thanks

1
Its actually unclear what you're asking, but supposed ui is a nullptr delete ui; is a NOP. So it seems to be fine. - πάντα ῥεῖ
Do we have to manually delete each widget? No. The widgets should be children of the parent widget. QObject will handle them when the parent is deleted. - drescherjm
It should have a parent QObject (or be on the stack or is manually deleted...) otherwise the MainWindow itself would have leaked. - drescherjm
.ui files don't do anything magical, they get converted to C++ code which you could have written yourself (theoretically at least). Please check a generated ui_XXX.h of simple UI for some insight. - hyde
Another thing which will make your life a tiny bit easier: addWidget, setLayout etc reset the parent, so you don't need to give this as constructor parameter when you create widgets, layouts etc. - hyde

1 Answers

3
votes

Please refer to this article

QWidget, the fundamental class of the Qt Widgets module, extends the parent-child relationship. A child normally also becomes a child widget, i.e. it is displayed in its parent's coordinate system and is graphically clipped by its parent's boundaries. For example, when the application deletes a message box after it has been closed, the message box's buttons and label are also deleted, just as we'd want, because the buttons and label are children of the message box.

So, there is no difference do you use ui or not. When you delete window, all its children will be deleted too.