Search code examples
qtsleep

How to sleep within the same function in QT?


I'm student for studying QT. I want to sleep(delay) within the same function, but I can't to sleep function as I thought.

void test(){
        cardTurning(i, 0);
        // I want to sleep for 3 seconds at here
        cardTurning(i, 1);
}

What shoud I do for sleep there?

I already used QThread::sleep(3);, but it makes sleep there two functions together.

I want to sleep three seconds after cardTurning(i, 0) and then work cardTurning(i, 1).

Thank you.


Solution

  • If you going to use the sleep function you will sleep the whole program. at this type of delay, you can use the QTimer::singleShot function it calls only one time after your interval and not sleep the whole system. it takes interval as an ms.

    you can see a basic example below ;

    #include <QCoreApplication>
    #include <QDebug>
    #include <QTimer>
    void print1(int x,int y){
        qDebug()<<"value = "<<x<<" "<<y;
    }
    
    void Test(){
        print1(3,2);
        QTimer::singleShot(3000,[](){
           print1(4,5);
    
        });
    
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        Test();
        print1(10,10);
        return a.exec();
    }
    

    expected outputs are ;
    value = 3 2
    value = 10 10
    value = 4 5