简体   繁体   中英

Qt C++ Run code every second

I need to check a conditional every second and then run function. Executing is asynchronous so it won't make any problems. Can I call function somewhere in loop? I would get time since program started and check if second passed. Where can i find main loop? Thanks

Using a QTimer can solve this:

QTimer* timer = new QTimer();
timer->setInterval(1000); //Time in milliseconds
//timer->setSingleShot(false); //Setting this to true makes the timer run only once
connect(timer, &QTimer::timeout, this, [=](){
    //Do your stuff in here, gets called every interval time
});
timer->start(); //Call start() AFTER connect
//Do not call start(0) since this will change interval

In addition (and since there has been an argument about the insecurity of lambda functions on target object lifetime) one can of course connect this to a slot in another object:

connect(timer, &QTimer::timeout, anotherObjectPtr, &AnotherObject::method);

Please be aware that this method should not have parameters, since the timeout signal is also defined without parameters.

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