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

标签 c++ qt

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

最佳答案

使用 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/

相关文章:

c++ - 写网络使用程序应该用什么API?

c++ - 有哪些用于非 MFC、Win32 C++ 应用程序的 *slick* UI 库/框架/工具?

c++ - 隐藏 QListView 项目的复选框

c++ - QDeclarativeView 目录中没有这样的文件。在 qtCreator 中运行 QML 和 c++ 应用程序

c++ - _p.h 文件的用途是什么?

c++ - ifstream 没有匹配的初始化构造函数

C++ 结构指针指向对象类型错误

c++ - 结构上未声明的标识符

c++ - 编译opengl的 undefined reference

python-2.7 - PyQt 4 : Get Position of Toolbar