读书人

关于线程中的定时器的有关问题

发布时间: 2012-04-10 21:03:56 作者: rapoo

关于线程中的定时器的问题
想在新创建的线程中定义一个100ms的定时器,一旦timeout就调用槽函数发送网络数据
但成功启动线程后从未跳入槽函数,为什么鸟?
代码大致如下:

// .h文件
#include<QThread>
#include<QTimer>

class NewThread : public QThread
{
public:
NewThread();
QTimer *m_timer;

private slots:
void sSend();
}

// .cpp文件
#include ".h"

NewThread::NewThread()
{
m_timer = new QTimer(this);
}

NewThread::run()
{
m_timer->start(100);
connect(m_timer, SIGNAL(timeout()), this, SLOT(sSend()));

while(1)
{
Sleep(1);
}
}

NewThread::sSend()
{
...
}


[解决办法]
线程中是用定时器好像是有一些问题,楼主不妨换个角度,定时器实际上就类似于新的线程,你要是需要完成定时器的工作,不用去继承QThread,直接继承QTimer就可以
我写过类似的

C/C++ code
class ReadHeart : public QTimer{    Q_OBJECTpublic:    ReadHeart();    ~ReadHeart();private slots:    void readHeartTime();};
[解决办法]
Here...
C/C++ code
NewThread::run(){  m_timer->start(100);  connect(m_timer, SIGNAL(timeout()), this, SLOT(sSend()));  while(1)  {  Sleep(1);  }}
[解决办法]
m_timer = new QTimer(this)放到run()里,然后把while循环换成exec()

读书人网 >QT开发

热点推荐