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

1 c++ qt

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

Seb*_*nge 5

使用 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
Run Code Online (Sandbox Code Playgroud)

此外(并且由于存在关于 lambda 函数对目标对象生命周期的不安全性的争论)当然可以将其连接到另一个对象中的插槽:

connect(timer, &QTimer::timeout, anotherObjectPtr, &AnotherObject::method);
Run Code Online (Sandbox Code Playgroud)

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

  • 对此要非常小心,不要向新手推荐它!将 lambda 与 `QObject::connect()` 一起使用不是一个没有问题的玩具!目标对象被销毁时不会自动断开连接。参考这个:https://wiki.qt.io/New_Signal_Slot_Syntax (2认同)
  • @TheQuantumPhysicist 由于有“this”作为上下文,因此它可以很好地断开连接。 (2认同)