QTimer,QTime的一点应用

来源:互联网 发布:选择lua不选择python 编辑:程序博客网 时间:2024/04/29 19:44

QTime可以及时流逝的时间

QTimer是“时机”;什么时间发生什么时候,发出一个SIGNAL,执行一个SLOT

 

例子1

#include<QtGui>
#include<windows.h>
#include<vector>
int main(int argc,char* argv[])
{
 
 QApplication app(argc,argv);


 std::vector<int> list;

 QTime tim;
 tim.start();
 for(int i=0; i<10; i++)
 {
  Sleep(100);
  list.push_back(tim.elapsed() );
 }
 for(quint32 i=0; i<list.size(); i++)
 {
  printf("%d ", list.at(i));
 }
 printf("/n");

 return app.exec();
}

则输出为,109 203 312 406 516 609 703 812 906 1016

计算一下邻差  94 109 94 110 93 94 109 94 110
差不多, 基本维持在100毫秒的延时,这基本说明Sleep的精度,也说明QTime的用法之一。

 

例子2:

----------------------timeout.h-----------

#include <QtCore>
class TIMEOUT:public QObject
{
 Q_OBJECT
 private:
  QTime t;
 public:
  TIMEOUT()
  {
   t.start();
  }
  public slots:
  void timeout()
  {
   qDebug("%d ", t.elapsed() );
  }
};

---------------------main.cpp-------------

#include "timeout.h"
int main(int argc,char* argv[])
{
 
 QApplication app(argc,argv);


 std::vector<int> list;

 QTimer timer;
 timer.start(100);

 TIMEOUT out;
 QObject::connect(&timer,SIGNAL(timeout()), &out, SLOT(timeout()));

 for (int i=0; i<6;i++)
 {
  Sleep(50);
 // qApp->processEvents();

 }

 

 return app.exec();
}
输出为

3123284375476567658759841094120313121422153116401750185919692078218722972406251526252734

计算一下邻差,

 

16109110109109110109110109109110109109110109110109109110109109110109

可见执行Sleep的时候,QTimer是没有机会fire它的signal的;它眼巴巴的等着cpu有空了,才能释放signal;

那么是不是释放了signal,但是调度处理没有时机调用slot呢?也有可能吧,

但外在的表现是一直的,即来不及处理。

When a timer fires, the application sends a QTimerEvent, and the flow of control leaves the event loop until the timer event is processed. This implies that a timer cannot fire while your application is busy doing something else. In other words: the accuracy of timers depends on

the granularity of your application.

       --------------Qt的assistant

 

上面的例子2中,如果反注释  qApp->processEvents();
则输出为

 

15625032843854765676687598510941203131314221531164117501860196920782188

邻差为

 

9478110109109110109110109109110109109110109110109109110

可见这个qApp->processEvents()的作用了 ,见缝插针,只是第一个sleep和第二个sleep之间没有来得及插针。

 

试图使用QTimer得到固定的,精确的,不依赖于当前任务的时延,是苦难的。