Reputation: 291
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 e.g
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.
Upvotes: 0
Views: 646
Reputation: 27611
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.
Upvotes: 0
Reputation: 10456
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()));
Upvotes: 3