当前位置:编程学习 > wap >>

Qt线程中如何创建定时器?

如何在qt的线程中创建一个定时器? --------------------编程问答-------------------- 1、QTimer 类
2、QObject的类的定时器 --------------------编程问答-------------------- run 里面一定要有exec().... --------------------编程问答-------------------- 在多数情况下,直接让线程sleep会更方便。 --------------------编程问答-------------------- 用这个 QEventloop 可以在线程里面 监听事件

相当于主线程的 事件监听。

不过有个条件:timer的new和 connect必须放在run里面 ,并且connect的第五个参数要指定成Qt::DirectConnection --------------------编程问答-------------------- 这个方法 ,即使是主线程阻塞了,你的定时器照样执行。  感觉不错。 --------------------编程问答-------------------- 定时器依赖事件循环,还是用sleep方便。 --------------------编程问答-------------------- 1.QTimer
//创建定时器
QTimer *testTimer = new QTimer(this);
//将定时器超时信号与槽(功能函数)联系起来
connect( testTimer, SIGNAL(test()), this, SLOT(testFunction()) );
//开始运行定时器,定时时间间隔为1000ms
testTimer->start(1000);

2.通过QObject::startTimer(),可以把一个一毫秒为单位的时间间隔作为参数来开始定时器 --------------------编程问答-------------------- .h中
void timerDeal();//槽函数定义
QTimer testTimer;//创建定时器对象

.c中
connect(&testTimer, SIGNAL(timeout()), this, SLOT(timerDeal()) );//将定时器超时信号与槽(功能函数)联系起来

testTimer->start(1000);//开始运行定时器,定时时间间隔为1000ms

void XXX::timerDeal(){//槽函数实现
    ...
}



--------------------编程问答--------------------
引用 8 楼 woshiwuxingcheng 的回复:
.h中
void timerDeal();//槽函数定义
QTimer testTimer;//创建定时器对象

.c中
connect(&testTimer, SIGNAL(timeout()), this, SLOT(timerDeal()) );//将定时器超时信号与槽(功能函数)联系起来

testTimer->start(1000);//开始运行定时器,定时时间间隔……


补充点:自己定义槽函数的时候,要在前面加slots: 
例如:
public:
       int a;
slots:
      void A();
      void B();
补充:移动开发 ,  Qt
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,