如何使用 Qt 给出循环执行的延迟
在我的应用程序中,我希望当执行循环时,每次控制权转移到循环时,每次执行都必须延迟特定时间。我该怎么做?
In my application I want that when a loop is being executed, each time the control transfers to the loop, each execution must be delayed by a particular time. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑(删除错误的解决方案)。
编辑(添加此其他选项):
使用它的另一种方法是子类 QThread,因为它具有受保护的 *sleep 方法。
这是创建您自己的 *sleep 方法的代码。
你可以这样调用它:
这会给你相应的 10 微秒、10 毫秒或 10 秒的延迟。如果底层操作系统计时器支持该分辨率。
EDIT (removed wrong solution).
EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
Here's the code to create your own *sleep method.
and you call it by doing this:
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
作为 @Live 的答案的更新,对于 Qt ≥ 5.2,不再需要子类
QThread
,现在睡眠功能是公开的:cf http://qt-project.org/doc/qt-5/qthread.html #静态公共成员
As an update of @Live's answer, for Qt ≥ 5.2 there is no more need to subclass
QThread
, as now the sleep functions are public:cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members
C++11 有一些便携式定时器的东西。查看
sleep_for。
C++11 has some portable timer stuff. Check out
sleep_for.
所以这个问题已经有近 10 年的历史了,但它在我的一次搜索中突然出现,我认为在 Qt 中编程时有更好的解决方案:信号与信号。槽、定时器和有限状态机。所需的延迟可以在不以中断其他功能的方式休眠应用程序的情况下实现,并且无需并发编程且无需旋转处理器 - Qt 应用程序将在没有事件要处理时休眠。
解决这个问题的一个技巧是让一系列计时器的 timeout() 信号连接到事件的槽,然后启动第二个计时器。这很好,因为它很简单。这不太好,因为如果存在逻辑分支,那么很快就会变得难以排除故障和维护,而逻辑分支通常出现在任何玩具示例之外。
QTimer
更好、更灵活的选择是 Qt 中的状态机基础设施。在那里,您可以为具有多个状态和分支的任意事件序列配置框架。随着时间的推移,FSM 更容易定义、扩展和维护。
Qt 状态机
So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.
A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.
QTimer
A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.
Qt State Machine