End Game Function

133 Views Asked by At

I'm trying to display "Game Over" once the player runs out of lives. However, it's never displayed after the game ends. Here is some example code.

void Game::end()
{
  QGraphicsTextItem *text = new QGraphicsTextItem("GameOver");

  text->setPos(400, 500);

  scene->addItem(text);

  sleep(2);
  QApplication::quit();
}
1

There are 1 best solutions below

3
George On BEST ANSWER

You dont get the desired result because the drawing occurs after the function it's been called inside returns, and it never returns since you are quiting the application before. As drescherjm pointed out, try to delay the quit by using QTimer::SingleShot. Like this:

QTimer::singleShot(1000, [](){
    QApplication::exit();
});

Thus QApplication::exit() is called in given interval, by which time Game::end() should return.