Search code examples
c++qtqtimer

QTimer dont stop when windows is closed


I am currently starting on QTCreator. I have been asked to use QTimers in a particular context which is this:

We have an open window, One or more QTimers are triggered and make things appear on the screen every x msec. When we press "Escape" the window should close and everything should be reset to 0.

But here is the problem, the timers are defined in a static way:

QTimer::singleShot(500, this, SLOT(foo());

When I call this->close() (which closes my window), the timers do not stop and continue. I tried several solutions: browse all the QTimers contained in my object, obviously there are none since they are defined in static. Instead of declaring them in static I've tried to create each time a new QTimer object like that:

    QTimer *timer= new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(2000);
    timer->setParent(this);
    timer->start();

And then call timer->stop() later, but I think it's very brutal when you have multiple Timers in the same code.

Is there a way to stop the timers when this->close is called, knowing that the timers are defined as a static one ?


Solution

  • Assuming you are using,

    QWindow *qw = new QWindow();
    QTimer *timer= new QTimer(); 
    

    To solve the issue you need to connect destroyed() signal of QWindow to timer's slot stop() So as soon as window is destroyed all registered timers will be stopped without explicit stop call. make sure you connect all timer instances. Code snippet as following,

    QObject::connect(&qw, SIGNAL(destroyed()), timer, SLOT(stop()))
    QObject::connect(&qw, SIGNAL(destroyed()), timer2, SLOT(stop()))
    QObject::connect(&qw, SIGNAL(destroyed()), timer3, SLOT(stop()))
    

    PS:

    QTimer *timer= new QTimer(this); // here you are setting parent as 'this' already
    timer->setSingleShot(true);
    timer->setInterval(2000);
    timer->setParent(this); // remove this, no need to set parent again.
    timer->start();