最近做項(xiàng)目,需在子線程中生成定時(shí)器,但發(fā)現(xiàn)在構(gòu)造函數(shù)中生成定時(shí)器時(shí),會(huì)報(bào)如下錯(cuò)誤:
QObject: Cannot create children for a parent that is in a different thread.
從網(wǎng)上查資料說,必須將定時(shí)器創(chuàng)建函數(shù)放在線程的run函數(shù)中才行,即按如下那樣:
void CClientThread ::run()
{
timerId = startTimer(5000);
}
但這樣在線程run函數(shù)里創(chuàng)建定時(shí)器,會(huì)導(dǎo)致定時(shí)器有時(shí)失效。經(jīng)測(cè)試發(fā)現(xiàn),10次有2到3次定時(shí)器不響應(yīng)。后查資料得到解決方案如下:
從QTimer派生出一個(gè)子類。如下:
class CCmdTimer :
public QTimer
{
Q_OBJECT
public:
CCmdTimer();
~CCmdTimer(void);
該子類啥都不干,沒有其他成員函數(shù)。
然后在CClientThread中有一個(gè)CCmdTimer的成員指針對(duì)象,并在run中構(gòu)造出該對(duì)象
void CClientThread ::run()
{
m_pCmdTimer = new CCmdTimer;
// 構(gòu)造定時(shí)器超時(shí)信號(hào)槽
connect(m_pCmdTimer, SIGNAL(timeout()), this, SLOT(timeArrived()), Qt::DirectConnection);
}
在 CClientThread類的timeArrived中響應(yīng)定時(shí)器的timeout()信號(hào)
void CClientThread::timeArrived()
{
}
// CClientThread.h
private slots:
void timeArrived();
聯(lián)系客服