How to show a window in Qt and remove it as soon as it is closed?

As a very simple example, I want to show a dialog in Qt when I click a button. The usual template for this (in the application I'm working on now) is as follows:

class MainWindow { ... private slots: buttonClicked(); ... private: ChildWindow * childWindow; } MainWindow::MainWindow(QWidget * parent) : QWidget(parent) { ... childWindow = new ChildWindow(this); ... } MainWindow::buttonClicked() { childWindow.show(); } 

Starting with .NET and Windows Forms (and because I don’t need access to this object from another place in the class), the following patterns are more familiar to me:

 button1_Clicked(object sender, EventArgs e) { ChildWindow f = new ChildWindow(); f.Show(); } 

A local variable means that I do not have another instance field, and also that the window will not linger in memory much longer than necessary. Direct translation of this into C ++ would be a little ugly, because after that no one cleared up. I have tried the following things:

  • shared_ptr . Unlucky, the delete d window as soon as the method ends, which means that a new window appears within a second of a second and disappears again. Not very good.

  • exec() instead of show() . This will work for modal dialogs, but the documentation seems to imply that it also stops the event loop and that you should call QApplication::processEvents() regularly if it still needs to be updated. I don’t understand much here, but I think this is also not very pleasant.

  • deleteLater() . Unfortunately, just showing the window does not block deleteLater , so it disappears as soon as it appears.

Is there a good way to just clear the window after it closes?

+7
source share
2 answers
 childWindow->setAttribute( Qt::WA_DeleteOnClose ); 

Also note that the call to exec() blocks the execution of the loop of the calling event, but generates its own event loop, so calls to processEvents() not needed.

+12
source

You can connect the finished() signal of this dialog to the deleteLater slot:

 ChildWindow * d = new ChildWindow(this); connect(d, SIGNAL(finished(int)), d, SLOT(deleteLater())); d->show(); 

So it will be delete d as soon as you close the dialog.

+2
source

All Articles