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

前端 未结 4 1307
后悔当初
后悔当初 2020-12-11 05:04

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() b

相关标签:
4条回答
  • 2020-12-11 05:13

    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);
    }
    
    0 讨论(0)
  • 2020-12-11 05:15

    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.

    0 讨论(0)
  • 2020-12-11 05:20

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

    QTimer::singleShot(2000, [=](){
        qDebug()<<"do something after 2000 msec...";
    });
    
    0 讨论(0)
  • 2020-12-11 05:25

    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.

    0 讨论(0)
提交回复
热议问题