简体   繁体   中英

How To Use Timer For A Set Period Of Time

I have used a timer several different times using signals and slots, I launch it and it keep going and calls an event every few seconds.

QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(move()));
timer->start(50);

I would like to know how to go about using a timer for a certain period of time eg

If something happens in my program ->

//Start CountdownTimer(3 seconds)
setImage("3secondImage.jpg");
//when time allocated is up
resetOrginalImage("orig.jpg");

I have no idea how to go about doing this any help or a point in the right direction would be much appreciated.

QTimer has singleShot() . But you need to create a separate slot with no arguments:

private slots:
    void resetImage() {resetOrginalImage("orig.jpg");}

...
setImage("3secondImage.jpg");
QTimer::singleShot(3000, this, SLOT(resetImage()));

If you're using C++ 11, the use of lambda expressions with QTimer makes it easier to read, especially if the timer only executes a small number of lines of code: -

QTimer * timer = new QTimer();
timer->setSingleShot(true); // only once

connect(timer, &QTimer::timeout, [=]{
    // do work here
    resetOrginalImage("orig.jpg");
};

timer->start(3 * 1000); // start in 3 seconds

In my opinion, it's a little more elegant than having to declare a separate function to be called when the timer times out.

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