Qt自定义sleep延时函数(巧妙的使用时间差,但这样似乎CPU满格,而不是沉睡)

Qt不像VC++的win32/MFC编程那样,提供了现成的sleep函数可供调用。Qt把sleep函数封装在QThread类中。子线程可以调用sleep函数。但是如果用户想在主线程实现延时功能,该怎么办呢?方法是自定义sleep延时函数。通过QDateTime来实现时间差。

#include <QDateTime>

void MainWindow::sleep(int msec)//自定义Qt延时函数,单位毫秒
{
    QDateTime last = QDateTime::currentDateTime();
    QDateTime now;
    while (1)
    {
        now = QDateTime::currentDateTime();
        if (last.msecsTo(now) >= msec)
        {
            break;
        }
    }
}

http://blog.csdn.net/libaineu2004/article/details/39161697

原文地址:https://www.cnblogs.com/findumars/p/4886499.html