Attitude12136
Attitude12136

Reputation: 47

How to open a second QMainWindow from my first/original MainWindow?

I am creating a desktop app with Qt6 and C++ and I have my original MainWindow class. Using Qt Creator I generated ui,h,cpp for a new SummaryClass (QMainWindow). I want to be able to click a button located in MainWindow so that I can open the SummaryWindow.

  void MainWindow::openSummary()
    {
    SummaryWindow window;
    window.show();
    }

I understand that at the end of the function the window instance falls out of scope and gets destroyed. (the destructor generated by Qt Creator gets automatically called) since the window appears then disappears quickly. If I were to simply execute

SummaryWindow window = new SummaryWindow();
window.show();

The window would show successfully but then that creates a memory leak.

Are there workarounds/solutions for what I want to achieve?

To be clear, I want to open the window and keep both windows visible.

Upvotes: 0

Views: 1569

Answers (2)

Nikolay
Nikolay

Reputation: 198

In the constructor of the SummaryWindow write:

SummaryWindow::SummaryWindow() {
   this->setAttribute(::Qt::WA_DeleteOnClose);
   ...
}

That makes the trick. Now

auto window = new SummaryWindow();
window->show();

does not cause a memory leak. (To ensure, you can add some debug printing into ~SummaryWindows()).

Upvotes: 0

one alternative is that you define a list of pointers to the summaryClass and you create and show as many instances of the summary as you need in the slot for the button in the mainWindow

your mainwindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    QList<SummaryClass*> l;
};

and the slot of the button

void MainWindow::on_pushButton_clicked()
{
    SummaryClass* sm = new SummaryClass(this);
    l.push_back(sm);
    sm->show();
}

as soon as you do this:

new SummaryClass(this);

every summary class will be destroyed when the mainWin is destroyed....


enter image description here

Upvotes: 1

Related Questions