You're explicitly invoking the destructor on this
. There are very few times you'd need to do this, and they always should be abstracted out. Such calls only belong in low-level resource management classes. If you think of doing this in a subclass of QObject
or QWidget
, you most likely shouldn't be!
If all you want is to close a window, use QWidget::close()
. But perhaps you wish to destroy the widget instance, too, to release any resources used by it. Then read on.
Let's assume that Authentication
is a proper dialog that emits accepted()
and rejected()
signals as appropriate when authentication succeeds or fails, respectively:
class Authentication : public QDialog {
...
};
Some ways of proceeding from such a dialog might be:
Define the dialog as a variable local to a scope, run an event loop as long as the dialog is active, then leave the scope:
int main(int argc, char ** argv) {
QApplication app{argc, argv};
{
Authentication auth;
auto result = auth.exec();
if (result == QDialog::Rejected) return 1;
} // here auth has been destructed
MainWindow window;
window.show();
return app.exec();
}
Allocate the dialog dynamically, and have it auto-delete when closed.
int main(int argc, char ** argv) {
QApplication app{argc, argv};
auto auth = new Authentication;
auth->setAttribute(Qt::WA_DeleteOnClose);
QObject::connect(auth, &QDialog::accepted, []{
auto win = new MainWindow;
win->setAttribute(Qt::WA_DeleteOnClose);
win->show();
});
auth->show();
return app.exec();
}