Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qtimer

I am having a hard time wording this question even though I don't think its that complicated.

I want to do something simalar to QTimer::singleshot() but I want it to still only call the SLOT once even if QTimer::singleshot() is called multiple times before it fires.

like image 399
sm11963 Avatar asked Jan 11 '13 00:01

sm11963


3 Answers

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.

like image 138
simotek Avatar answered Oct 22 '22 03:10

simotek


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);
}
like image 21
Timmmm Avatar answered Oct 22 '22 01:10

Timmmm


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

QTimer::singleShot(2000, [=](){
    qDebug()<<"do something after 2000 msec...";
});
like image 3
S.M.Mousavi Avatar answered Oct 22 '22 02:10

S.M.Mousavi