Reputation: 717
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()
?
Upvotes: 0
Views: 4869
Reputation: 1
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.
Upvotes: 0
Reputation: 98425
You need to:
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();
}
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();
}
Upvotes: 2