QT 延时

来源:互联网 发布:淘宝店改区域 编辑:程序博客网 时间:2024/06/03 21:30

  编写上位机软件时,需要发送一个指令要求:延时30s,收到回复,延时立马中断。


void Dialog::sleep(int sec)
{
    QEventLoop loop;
    connect(this, SIGNAL(netTestSignal()), &loop, SLOT(quit()));
    QTimer::singleShot(sec*1000, &loop, SLOT(quit()));
    loop.exec();
}

Detailed Description

The QEventLoop class provides a means of entering and leaving an event loop.

At any time, you can create a QEventLoop object and call exec() on it to start a local event loop. From within the event loop, calling exit() will force exec() to return.


翻译:
QEventLoop类为我们提供了一种进入和退出事件循环的方法。
在任何时候,你都可以创建一个QEventLoop实例,并通过调用exec()来启动一个事件循环。在循环期间,主动调用exit()可以使exec()强制返回。

 从以上说明可以略知QEventLoop的使用方法,陈列如下:
(1)创建QEventLoop实例;
(2)调用exec()来启动;
(3)通过exit()来使exec()退出并返回退出码。

    看起来挺简单的,不是吗?但是问题在于,如何掌握退出的时机呢?对了,就是“信号与槽”!!!

    本文的目的在于,接收完数据之后就返回,不是吗?那只要判断数据何时读取完毕就可以解决问题了。因此,采用信号与槽机制来判断数据是否接收完毕恰如其境。



文章开头的例子就是很好的应用。


参考资料:
QEventLoop类说明:http://qt-project.org/doc/qt-5/QEventLoop.html
QEventLoop使用两例:http://blog.csdn.net/dbzhang800/article/details/6300519

QEventLoop介绍的使用解析:https://www.qtdeveloperdays.com/2013/sites/default/files/presentation_pdf/Qt_Event_Loop.pdf