samprat
samprat

Reputation: 2214

Avoid QTimer to emit timeout signal

I have started Timer to wait for certain condition to be true. IF condition is true then I stop timer and dont want timeout signal to emit or execute connnected slot. But if condition is false within specified time then its allright to emit signal timeout(). But whatever is the case it always emit timeout signal. I have used blockSignals ( true ) as well and it doesnt work. Can some one please advice me.

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;
    }
}

Also in timerStop function I have tried to emit destroyed signal but I got response that it fails to connect. pLease advice me.

Upvotes: 0

Views: 1100

Answers (1)

ratchet freak
ratchet freak

Reputation: 48186

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();
}

This doesn't actually return the timer you just created. You want something like:

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;
}

Then you can pass the returned timer into the stop function though I suggest you use deleteLater instead of straight up deleting it:

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();
    }
}

Upvotes: 2

Related Questions