我需要每秒检查一次条件,然后运行函数。执行是异步的,所以不会有任何问题。我可以在循环中的某处调用函数吗?自程序启动以来我会得到时间并检查是否第二次过去了。我在哪里可以找到主循环?谢谢
最佳答案
使用 QTimer 可以解决这个问题:
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
此外(并且由于存在关于 lambda 函数在目标对象生命周期上的不安全性的争论)当然可以将其连接到另一个对象中的插槽:
connect(timer, &QTimer::timeout, anotherObjectPtr, &AnotherObject::method);
请注意,此方法不应有参数,因为超时信号也是在没有参数的情况下定义的。
关于c++ - Qt C++ 每秒运行一次代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42850485/