Planned maintenance has been done but it did not solve the problem. So work will continue on this and a new time for trying updates will be announced asap.

My QStateMachine API example won't transition



  • Given the following code (headers omitted).

    //threadedobject.cpp
    #include "threadedobject.h"

    ThreadedObject::ThreadedObject(QObject *parent) : QObject(parent)
    {
    }

    void ThreadedObject::callSignalOne()
    {
    emit signal1();
    }

    void ThreadedObject::callSignalTwo()
    {
    emit signal2();
    }

    //statemachinemain.cpp
    #include "statemachinemain.h"
    #include <QDebug>
    #include <QSignalTransition>
    #include <QState>

    StateMachineMain::StateMachineMain(ThreadedObject *threadedObject, QObject *parent)
    : QObject(parent)
    , m_threadedObject(threadedObject)

    {
    initStateMachine();
    }

    void StateMachineMain::onStateOneEntered()
    {
    qDebug() << "onStateOneEntered()";
    }

    void StateMachineMain::onStateTwoEntered()
    {
    qDebug() << "onStateTwoEntered()";
    }

    void StateMachineMain::onStateThreeEntered()
    {
    qDebug() << "onStateThreeEntered()";
    }

    void StateMachineMain::initStateMachine()
    {
    QState *state1 = new QState;
    QState *state2 = new QState;
    QState *state3 = new QState;

    m_stateMachine.addState(state1);
    m_stateMachine.addState(state2);
    m_stateMachine.addState(state3);
    
    state1->addTransition(m_threadedObject, SIGNAL(signal1()), state2);
    QObject::connect(state2, SIGNAL(entered()), this, SLOT(onStateTwoEntered()));
    state2->addTransition(m_threadedObject, SIGNAL(signal2()), state3);
    QObject::connect(state3, SIGNAL(entered()), this, SLOT(onStateThreeEntered()));
    QObject::connect(state1, SIGNAL(entered()), this, SLOT(onStateOneEntered()));
    
    m_stateMachine.setInitialState(state1);
    m_stateMachine.start();
    

    }

    //main.cpp
    #include <QCoreApplication>
    #include <QThread>

    #include "statemachinemain.h"
    #include "threadedobject.h"

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    ThreadedObject *obj = new ThreadedObject;
    QThread t1;
    QThread t2;
    obj->moveToThread(&t2);
    StateMachineMain *main = new StateMachineMain(obj);
    main->moveToThread(&t1);
    t1.start();
    t2.start();
    obj->callSignalOne();
    obj->callSignalTwo();
    return a.exec();
    

    }

    Output from running the application:
    onStateOneEntered()

    Expected:
    onStateOneEntered()
    onStateTwoEntered()
    onStateThreeEntered()

    Would appreciate any help.


  • Lifetime Qt Champion

    Hi,

    You are emitting the signals before all the event loops have started.


Log in to reply