如何在设定的时间段内使用计时器

How To Use Timer For A Set Period Of Time

我使用信号和插槽多次使用定时器,我启动它,它继续运行并每隔几秒调用一个事件。

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

我想知道如何在特定时间段内使用计时器,例如

如果我的程序出现问题 ->

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

我不知道如何着手做这件事任何帮助或正确方向的观点将不胜感激。

QTimer 有 singleShot()。但是你需要创建一个没有参数的单独插槽:

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

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

如果您使用的是 C++ 11,则将 lambda 表达式与 QTimer 结合使用会使其更易于阅读,尤其是当计时器仅执行少量代码行时:-

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

在我看来,这比必须声明一个单独的函数在计时器超时时调用要优雅一些。