Using QT, how to call function once after a certain interval, even if more calls may occur?

时光毁灭记忆、已成空白 提交于 2019-12-05 06:46:01
Timmmm

This should work. 

class MyObject
{

// ...
    QTimer* mTimer;
}

MyObject::MyObject()
{
    mTimer = new QTimer(this);
    mTimer->setSingleShot(true);
    connect(mTimer, SIGNAL(timeout()), SLOT(doStuff()));
}

MyObject::startOrResetTimer()
{
   mTimer->start(1000);
}

If you only want to call a slot once off a timer you could look at something like

QTimer::singleShot(500, this, SLOT(MySlot()));

Then your guaranteed it will only happen once.

To clarify, by calling the static version of this rather then calling it from a existing timer it will only happen once.

You can use singleShot() static member function with lambda for this purpose easily:

QTimer::singleShot(2000, [=](){
    qDebug()<<"do something after 2000 msec...";
});

Quick-and-dirty: use a boolean in your class and set it to true in the slot; ignore subsequent calls until the boolean is reset.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!