Important: Please read the Qt Code of Conduct -

Creating a QDialog per new as a pointer vs. initializing it directly

  • Hi all,

    I'd be very grateful for some advice/clarification on how to use a QDialog derived class correctly. I can show such a class in two ways: either, I do

    SomeDialog *dialog = new SomeDialog(whatever);

    or I can do

    SomeDialog dialog(whatever);;

    Is it correct that, if I do setAttribute(Qt::WA_DeleteOnClose); for the first variant, the result will be the very same, as the pointer will be deleted when the dialog exists, and the variable of the second one will also be deleted as soon as it goes out of scope (the function creating the dialog exits)?

    If so, can one say that one sould always use the second, pointer-less solution if no connect() statement is used and the dialog won't be used later (as it's deleted anyway on exiting)?

    And: Is it possible to know if such a dialog is created via new or directly, so that if I need both variants, setAttribute(Qt::WA_DeleteOnClose); can be set automatically, and only for the new variant, so that I don't get a double free or corruption error if it's used directly?

    Thanks a lot for all clarification/help!

  • Lifetime Qt Champion

    SomeDialog dialog(whatever);;
    would only work in main.cpp as exec() blocks it from running out of scope

    if you do it in a function like

    void some func()  {
    SomeDialog dialog(whatever);; // not blocking
    } // SomeDialog would be deleted  here 

    for this to work u have to use exec() which is blocking.

    and yes, setAttribute(Qt::WA_DeleteOnClose); will delete the dialog when it is closed.
    for the pointer version.

    so if you use show() use pointer and WA_DeleteOnClose for auto clean up.
    if you use exec()
    no need to use new.

  • @mrjj Oh, that's another aspect of this I didn't think of yet … thanks for the help :-)

Log in to reply