Search code examples
c++qtqt5qtimer

QTimer, Parametrized slot


I am writing an app for relay controller. I have a function that opens/closes relay:

void setRelay(unsigned int relay_number, bool state);

Now I want to make some button to open an relay for lets say 1sek.

I want to do th sth like this:

void on_button_clicked()
{
    setRelay(1, true);
    QTimer::singleShot(1000,this,SLOT(setRelay(1,false)))
}

Yes, I know that the signals dont work that way. Is there any way to change the signal emitted from timer, so it will close up an relay. Closest thing I came up is this:

QTimer::singleShot(1000,this,SLOT(relay_1_off()));

and then I have to make a slot per relay to close it:

void relay_1_off(){
    setRelay(1,false);
}

Could it be done without making so many slots, anyone have some more clever way? Greetings


Solution

  • If you are using Qt5 you can use the lambda functions:

    void QTimer::singleShot(int msec, Functor functor)

    QTimer::singleShot(1000, [&](){
        setRelay(1,false);
    });