c++qtqt5qtimer

Connect QTimer with a Slot with parameters


I tried the following:

connext(&timer, &QTimer::timeout, this, &myClass::myMethod(_param1, _param2)); // does not work
timer.setSingleShot(true);
timer.start(100);

The timer of type QTimer is a member element of the class.

Is there a way to connect the timeout() signal of a timer to a method with multiple parameters?


Solution

  • The QTimer's timeout signal void timeout() does - on its own - not have enough parameters to call myClass::myMethod(_param1, _param2); (where exactly should timeout take _param1 & _param2 from?)

    You can either use a lambda function:

    //assuming you have _param1 & _param2 as variables before this point
    connect(&timer, &QTimer::timeout, this, [=]() { myMethod(_param1, _param2); });
    timer.setSingleShot(true);
    timer.start(100);
    

    One thing to note is that by using this as the receiver object for connect() you tie the lifetime of the connection to both the lifetime of the timer AND of the currect object (this), which should ensure that the connection is properly destroyed if one of the two objects dies and the lambda (with its implicit call to this->myMethod()) is not executed after this is deallocated.

    Or you could create a void myClass::handleTimeout() function in your class, connect the timeout of the time to it as slot and there call myMethod(_param1, _param2)

    void myClass::handleTimeout()
    {
        //assuming _param1 & _param2 are variables accessible in handleTimeout()
        myMethod(_param1, _param2));
    }
    
    //Your original function...
    void myClass::someFunction()
    {
        //...
        connect(&timer, &QTimer::timeout, this, &myClass::handleTimeout);
        timer.setSingleShot(true);
        timer.start(100);
        //...
    }