Reputation: 673
In my main window i used this code to open my game application
void MainWindow::on_playButton_clicked(){
CSpaceInwaders* pGame = new CSpaceInwaders(qApp->screens()[0]->size());
pGame->showFullScreen();
pGame->Run();
}
Then in there this is the run function that I called
void CSpaceInwaders::Run(){
scene()->clear();
setCursor(Qt::BlankCursor);
m_pCannon =new CCannon(EColor::Red);
m_pCannon->setPos(m_onScreenSize.width()/2,m_onScreenSize.height()-gCannonSize.height());
m_pCannon->setFlag(QGraphicsItem::ItemIsFocusable);
m_pCannon->setFocus();
scene()->addItem(m_pCannon);
connect(m_pCannon, &CCannon::sigIncreaseScore,this,&CSpaceInwaders::onIncreaseScore);
connect(m_pCannon, &CCannon::sigDecreseScore,this,&CSpaceInwaders::onDecreseScore);
m_pPoints = new CPoints();
scene()->addItem(m_pPoints);
QTimer* pTimer = new QTimer(this);
connect(pTimer, &QTimer::timeout,this,&CSpaceInwaders::onCreateEnemy);
pTimer->start(2000);}
after the game over I want to go back to my main window. So I used this function
void CSpaceInwaders::onGameOver(){
scene()->clear();
QMessageBox msgBox;
msgBox.setText("Game.");
msgBox.setInformativeText("You got hit ! Game Over");
msgBox.setStandardButtons(QMessageBox::Ok);
int ret = msgBox.exec();
switch (ret) {
case QMessageBox::Ok:
close();
MainWindow w;
w.show();
}}
This takes me back to the main window but after few seconds it closes.
I want to know how to fix this
Note : Created using QT
Upvotes: 1
Views: 86
Reputation: 673
Using this I solved my problem
void CSpaceInwaders::onGameOver(){
this->close();
}
Upvotes: 0
Reputation: 409442
The problem is with the code in the case:
case QMessageBox::Ok:
close();
MainWindow w;
w.show();
The problem is two-fold: First of all you can't actually define variables inside a case
like that. You need to add a scope. I'm surprised the compiler doesn't yell at you for that.
The second problem (and that's causing your problem) is that the variable w
is a local variable inside the switch
statement. Once the statement ends so does the life-time and w
and it's destructed and ceases to exist.
The solution (as far as I know) seems to be simple: Don't create and open a new main window! When you start the "space invaders" game you never close the original main window, it's should still be running in the background.
However this is a very bad way to "run" what should essentially be either a separate program or at the very least part of your normal program flow and event loop. Either extract the mini-game into its own program that you then load and execute, or don't create a separate application object and just open a normal window and let the main application event loop handle it.
Upvotes: 4