简体   繁体   中英

How to make time gap or delay between two parts of code meanwhile program continue? C++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM