3

I have the following code:

if(collision == 1)
{
    painter->setBrush(QColor(Qt::red));
    painter->setPen(QColor(Qt::black));
    painter->drawEllipse(QPoint(boundingRect().x() + (boundingRect().width() / 1.7),
                             boundingRect().y() + (boundingRect().width() / 2.1)),
                             boundingRect().width() / 5,
                             boundingRect().height() / 10);

    /*THERE SHOUD BE THE TIME GAP AND THEN DO*/
    collision = 0;
}

I want to use this code to paint red ellipse, but only for few seconds (after collision). Therefore I have to make time gap or delay between two parts of this code. The problem here is that I do not know how to do it.

I tried sleep() or wait() or:

QTime dieTime= QTime::currentTime().addSecs(1);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);   

but these STOP or PAUSE whole PROGRAM I just want to delay execution of "collision = 0" Any ideas?

Ondřej Král
  • 89
  • 1
  • 6
  • 1
    look into [threading](http://stackoverflow.com/questions/266168/simple-example-of-threading-in-c) –  Oct 27 '14 at 13:11
  • 1
    If you just want a piece of code to run after a certain amount of time has passed, [look into QTimer](http://qt-project.org/doc/qt-5/qtimer.html). For more complex concurrency, see [Qt's Threading Model](http://qt-project.org/doc/qt-5/examples-threadandconcurrent.html) *(though note that C++11 now has threads as part of the standard, so depending on your needs it may be better to start learning that way vs. the Qt way)* – HostileFork says dont trust SE Oct 27 '14 at 13:17

1 Answers1

3

sleep() or wait() stop all your GUI thread, so it freezes. Try to use singleShot from QTimer. For example:

QTimer::singleShot(4000,this,SLOT(mySlot()));

In mySlot you can do all needed stuff. In this case singleShot will not freeze your GUI. For example set collision to zero and call update, it will call paintEvent and in this paintEvent with zero collision your ellipse will not be drawn again.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • `QTimer::singleShot(4000,this,SLOT(collisionSet())); void OtesanekItem::collisionSet() { collision = 0; }` This code gives me error: no matching function for call to 'QTimer::singleShot(int, OtesanekItem* const, const char*)' – Ondřej Král Oct 27 '14 at 13:44
  • @OndřejKrál See this answer: http://stackoverflow.com/questions/17212909/error-no-matching-function-for-call-to-qtimersingleshot there are solutions for QGraphicsItem subclass or just including QTimer – Jablonski Oct 27 '14 at 13:50