简体   繁体   中英

How to completely stop QTimer

How could i completely stop a QTimer ? when i call QTimer::stop() it doesn't correctly stopped.

For example i create a QTimer :

QTimer timer;
timer.singleShot(10000, this, [] { emit work_is_down(); });

and when i stopped:

timer.stop();

the lambda [] { emit work_is_down(); } [] { emit work_is_down(); } is still run after 10000ms. how to completely stop it?

QTimer::singleShot is a static method of the QTimer class. You can call it on an instance but it will be fundamentally disconnected from that instance.

You need to do the full QTimer dance, as said in the comments above:

QTimer *timer = new QTimer();
QObject::connect(timer, &QTimer::timeout, this, [](){ emit work_is_down(); });
timer->setSingleShot(true);
timer->start(10000);

Don't forget to call delete timer or timer->deleteLater() when you're done with it, or better yet, use a std::unique_ptr or QSharedPointer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM