Qt C++每秒运行一次代码

Qt C++ Run code every second

本文关键字:一次 代码 C++ 运行 Qt      更新时间:2023-10-16

我需要每秒检查一次条件,然后运行函数。执行是异步的,因此不会产生任何问题。我可以在循环中的某个地方调用函数吗?我会在程序启动后获得时间并检查秒是否通过。我在哪里可以找到主循环?谢谢

使用 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);

请注意,此方法不应有参数,因为超时信号也是在没有参数的情况下定义的。