简体   繁体   中英

Qt: How to open a new main window on push button click and delete original main window?

I have files main.cpp , MainWindow.h and MainWindow.cpp . I have a push button on this original main window. What I want is when I click on the button, it should take me to a new main window and delete the original main window.

Also I want to follow good programming practices. So I am wondering that should new source and header files like SecondWindow.cpp/.h be created or all this be done in MainWindow.cpp where I have definition of the SLOT on_button_clicked() ?

You need to:

  1. Instantiate the new window and show it.
  2. Delete the current window once the control returns to the event loop.

     void MainWindow::on_button_clicked() { auto win = new MainWindow(); win->setAttribute( Qt::WA_DeleteOnClose ); win->show(); deleteLater(); } 
  3. Make sure that the initial instance of the window is created on the heap:

     int main(int argc, char** argv) { QApplication app(argc, argv); auto win = new MainWindow; win->setAttribute( Qt::WA_DeleteOnClose ); win->show(); return app.exec(); } 

The answer given by Kuba Ober works.However, you can have only 2 main windows at all times no matter how many times you press the button. It seems to crash the program after the second time you run it. I believe my solution would be better since you can open as many main windows.

At your MainWindow Header:

private:
Ui::MainWindow *ui;
MainWindow *nWin; //Add This bit of code here

As for your triggered event function:

void MainWindow::on_actionNew_triggered()
{
   nWin = new MainWindow;
   nWin->show();

}

That should do it.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM