0

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();
}
  • Try switching the order of the `text->setPos(400, 500);` and `scene->addItem(text);` lines. First add the item and then change its position relative to the scene that You have added it to. – sweak Apr 06 '21 at 13:59
  • 2
    What is `sleep(2);`? It may block the GUI thread so you will not see it's updated. – vahancho Apr 06 '21 at 14:23
  • 1
    ***However, it's never displayed after the game ends*** It won't be because of the `QApplication::quit();` remember the drawing happens after your function returns. Use a QTimer::SingleShot to delay the quit – drescherjm Apr 06 '21 at 16:03
  • Add more code about the calling function. This would help contributors understand more about your question. – Ankit Tanna Apr 06 '21 at 17:21
  • drecherjm, that did the trick. I appreciate your help! – Derrick Mullins Apr 07 '21 at 13:47

1 Answers1

1

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.

George
  • 578
  • 4
  • 21
  • George, I really appreciate your help. Can you explain the syntax of your function above? I see the normal syntax for Qtimer::singleShot(myTime, myObject, SLOT(myMethodInMyObject())); but, I've never seen that syntax before. – Derrick Mullins Apr 07 '21 at 13:56
  • @DerrickMullins the `[](){QApplication::exit();}` part of the code above is called a lambda function. It's a part of many modern programming languages, including C++. New syntax for signal slot connection allows you to connect signals to a lambda functions. This is a very convinient way to code "do something when certain signal is emitted" kind of behaviour without adding additional slots to your interface – George Apr 07 '21 at 14:15
  • lambda expressions were an addition to the c++ language in the 2011 standard. c++11. Qt supported them with signals and slots beginning in Qt5. Related: [https://en.cppreference.com/w/cpp/language/lambda](https://en.cppreference.com/w/cpp/language/lambda) – drescherjm Apr 07 '21 at 19:27