如何使用 Qt 创建暂停/等待功能?

2021-12-09 00:00:00 sleep qt wait c++

我在玩 Qt,我想创建一个两个命令之间的简单暂停.但是它似乎不会让我使用 Sleep(int mili);,而且我找不到任何明显的等待函数.

I'm playing around with Qt, and I want to create a simple pause between two commands. However it won't seem to let me use Sleep(int mili);, and I can't find any obvious wait functions.

我基本上只是制作一个控制台应用程序来测试一些类代码,这些代码稍后将包含在适当的 Qt GUI 中,所以现在我不担心破坏整个事件驱动模型.

I am basically just making a console application to test some class code which will later be included in a proper Qt GUI, so for now I'm not bothered about breaking the whole event-driven model.

推荐答案

这个 上一个问题 提到使用 qSleep() ,它位于 QtTest 模块中.为了避免 QtTest 模块中的开销链接,查看该函数的源代码,您可以制作自己的副本并调用它.它使用定义来调用 Windows Sleep() 或 Linux nanosleep().

This previous question mentions using qSleep() which is in the QtTest module. To avoid the overhead linking in the QtTest module, looking at the source for that function you could just make your own copy and call it. It uses defines to call either Windows Sleep() or Linux nanosleep().

#ifdef Q_OS_WIN
#include <windows.h> // for Sleep
#endif
void QTest::qSleep(int ms)
{
    QTEST_ASSERT(ms > 0);

#ifdef Q_OS_WIN
    Sleep(uint(ms));
#else
    struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
    nanosleep(&ts, NULL);
#endif
}

相关文章