开发者

QTimer doesn't fire on second call

I've implemented the state pattern in qt.

Inside my EnterIdleState function, I'm hooking up a singleshot timer to start t开发者_开发知识库hings off. On the first call this works fine, on the second attempt however the timer doesn't fire, although the connection is made as before:

Codeflow is like this:

SetNewState(newIdleState());
IdleState::doWork();
SetNewState(new WorkState());
WorkdState::doWork();
SetNewState(newIdleState());

The SetNewState looks like this:

void IridiumProcessor::SetNewState(State* pNewState)
{
    if (m_pCurrentState)
    {             
        m_pCurrentState->LeaveState();
        delete m_pCurrentState;
    }    
    m_pCurrentState = pNewState;
    if (m_pCurrentState)
        m_pCurrentState->EnterState();
}

On Entering IdleState, I hook up the single shot timer:

void IdleState::EnterState()
{
    QTimer::singleShot(1000,this,SLOT(OnTimeout())); 
}
void IdleState::OnTimeout()
{
    qDebug() << "IdleState OnTimeout";
}

Same thing happens, when I use a QTimer membervar instead of the static singleShot call.


I see only few possible reasons for this to happen, except for really hardcore bugs like memory corruption and such.

It could be that you call your EnterState() method before the timeout expires. The second call cancels the previous one, and it repeats just again and again. In order to debug this, you should add a debugging output to the EnterState() method, preferably with time, to see if it actually happens. If it doesn't, then it means I'm wrong here.

It could also be that you destroy the receiver before the signal is emitted, as chalup suggested.

Another possibility is that you're blocking the event thread with some lengthy operation. The timer won't fire until the control returns to the Qt event loop of the thread where the timer lives. In case of a single-threaded application it is the main event loop.


I'd add logs to IdleState destructors: maybe you destroy them in IridiumProcessor::SetNewState before the QTimer times out?

Also consider using QStateMachine instead of writing your own solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜