2015-08-27 37 views
0

我已經啓動Timer來等待某個條件爲真。如果條件是真的,那麼我停止定時器,並且不希望超時信號發出或執行連接的插槽。但是如果在指定的時間內條件是錯誤的,那麼它就會發出信號timeout()。但無論如何,它總是會發出超時信號。我也使用了blockSignals(true),它不起作用。有人可以請教我。避免QTimer發出超時信號

void timerStart(QTimer* timer, int timeMillisecond) 
{ 
    timer = new QTimer(this); 
    timer->setInterval(timeMillisecond); 
    timer->setSingleShot(true); 
    connect(timer, SIGNAL(timeout()), this, SLOT(noRespFrmServer())) ; 
    //timer->start(timeMillisecond); 
    timer->start(); 
} 
void timerStop(QTimer* timer) 
{ 
    connect(timer, SIGNAL(destroyed(timer)), this, SLOT(stopTimerbeforeTimeout())); 
    qDebug() << " we are in timer stop"; 
    if(timer) 
    { 
     timer->stop(); 
     timer->blockSignals(true); 
     delete timer; 
    } 
} 

也在timerStop函數我試圖發出摧毀的信號,但我得到了它無法連接的響應。 請教我。

+0

幾件事情看起來嫌疑人 - 中'timerStart()'你忽略傳遞的參數'timer',並且不存儲你新創建的定時器,所以你無法阻止它。你在哪裏得到你傳遞給'timerStop()'的計時器?你可能意味着將'QTimer *&'傳遞給'timerStart()',或者將該定時器存儲在成員或(ugh)全局中? –

回答

2
void timerStart(QTimer* timer, int timeMillisecond) 
{ 
    timer = new QTimer(this); 
    timer->setInterval(timeMillisecond); 
    timer->setSingleShot(true); 
    connect(timer, SIGNAL(timeout()), this, SLOT(noRespFrmServer())) ; 
    //timer->start(timeMillisecond); 
    timer->start(); 
} 

這實際上並沒有返回剛創建的計時器。你想要的東西,如:

QTimer *timerStart(int timeMillisecond) 
{ 
    QTimer* timer = new QTimer(this); 
    timer->setInterval(timeMillisecond); 
    timer->setSingleShot(true); 
    connect(timer, SIGNAL(timeout()), this, SLOT(noRespFrmServer())) ; 
    //timer->start(timeMillisecond); 
    timer->start(); 
    return timer; 
} 

然後你就可以通過返回的計時器進入停止功能,雖然我建議你使用deleteLater,而不是直上刪除它:

void timerStop(QTimer* timer) 
{ 
    qDebug() << " we are in timer stop"; 
    if(timer) 
    { 
     qDebug() << " we are stopping the timer"; 
     timer->stop(); 
     timer->blockSignals(true); 
     timer->deleteLater(); 
    } 
} 
+0

非常感謝你的伴侶。但它仍然執行超時。我改變了我的代碼,但沒有喜悅。 – samprat

+0

actualluy在調試我注意到它不執行「我們正在停止計時器」。我只是在調查爲什麼。 – samprat

+0

確保你實際存儲並傳遞從'timerStart'返回的計時器。 –