QTimer与QThread
报错
1.调用QTimer时,报错:定时器不能在非线程中使用。
解决
1.在继承了QObject类中定义一个私有的QThread对象。
2.类中需要初始化定时器的地方进行一下初始化
QTimer *heartbeat = new QTimer();
heartbeat->moveToThread(&heartThread);
heartbeat->setInterval(5000);
connect(&heartThread,SIGNAL(started()),heartbeat,SLOT(start()));
connect(&heartThread,&QThread::finished,heartbeat,&QObject::deleteLater);
connect(heartbeat,&QTimer::timeout,this,&sqlSpecMod::sendHeartbeat,Qt::DirectConnection);
heartThread.start();//5s发送心跳
注意事项
1.QTimer是一个初始化函数中的局部变量。
2.信号和槽定义时,要加SIGNAL,SLOT,程序会报错,started()是一个私有信号。
3.需要加Qt::DirectConnection,不然启动定时器会失败