Important: Please read the Qt Code of Conduct -

How to properly create new QWidget "window" - as pointer or not?

  • Hi,
    I have main GUI class (QMainWindow). It contains pushbutton that can create MyWidget class (subclass QWidget). MyWidget it is widget that should be showed as a window.
    My question is that:
    If I create MyWidget as:

    class BaseWindow :  public QMainWindow
        BaseWindow(QWidget *parent = 0);
        //Other stuff
    public slots:
        void createMyWidget();
        //Other stuff
        MyWidget* widgetPtr;

    and in createMyWidget() method I have:

    void BaseWindow::createMyWidget()
        widgetPtr = new MyWidget(0);

    How to properly use "new" if can't destroy that widget (it can be closed by clicking exit button). I mean that if the pointer is created by new it should be also deleted.
    The proper way (in C++) is to create MyWidget by new and after closing it should be deleted. But window is deleted after using exit button, so I cannot delete it on my own.
    If I should leave it in above form or there is better way to do this?

    I hope I wrote it clearly.

  • Lifetime Qt Champion

    @never_ever said:

    well one way is to let the mainwindow create other windows in constructor (hidden)
    and then delete them in the destructor.

    So you createMyWidget would only show it.

    there is also the
    flag to make dialogs delete them self when closed.

    also you dont have to new them. you can have
    //Other stuff
    MyWidget widget; // no pointer

    and it dies with parent.

  • @mrjj thanks

Log in to reply