Qt QTimer::singleShot simple usage


Example

The QTimer::singleShot is used to call a slot/lambda asynchronously after n ms.

The basic syntax is :

QTimer::singleShot(myTime, myObject, SLOT(myMethodInMyObject()));

with myTime the time in ms, myObject the object which contain the method and myMethodInMyObject the slot to call

So for example if you want to have a timer who write a debug line "hello !" every 5 seconds:

.cpp

void MyObject::startHelloWave()
{
    QTimer::singleShot(5 * 1000, this, SLOT(helloWave()));
}

void MyObject::helloWave()
{
    qDebug() << "hello !";
    QTimer::singleShot(5 * 1000, this, SLOT(helloWave()));
}

.hh

class MyObject : public QObject {
    Q_OBJECT
    ...
    void startHelloWave();

private slots:
    void helloWave();
    ...
};