当前位置: 代码迷 >> QT开发 >> 关于线程中的定时器的有关问题
  详细解决方案

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

热度:123   发布时间:2016-04-25 04:55:07.0
关于线程中的定时器的问题
想在新创建的线程中定义一个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()
  相关解决方案