QStateMachine: Machine does not start



  • Hello
    I've the problem that the statemachine "machine" does not start to run. The ouput (qDebug) is always "not running". This is a example posted at http://doc.qt.io/qt-5/statemachine-api.html.

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

    qDebug() << "Hallo Welt";
    
    QStateMachine machine;
    QState *s1 = new QState();
    QState *s2 = new QState();
    QFinalState *done = new QFinalState();
    
    StringTransition *t1 = new StringTransition("Hello");
    t1->setTargetState(s2);
    s1->addTransition(t1);
    StringTransition *t2 = new StringTransition("world");
    t2->setTargetState(done);
    s2->addTransition(t2);
    
    machine.addState(s1);
    machine.addState(s2);
    machine.addState(done);
    machine.setInitialState(s1);
    machine.start();
    
    if(true == machine.isRunning())
    {
        qDebug() << "running";
    }
    else if(false == machine.isRunning())
    {
        qDebug() << "not running";
    }
    
    machine.postEvent(new StringEvent("Hello"));
    machine.postEvent(new StringEvent("world"));
    
    return a.exec();
    

    }

    Head "main.h"

    #include <QStateMachine>
    #include <QFinalState>
    #include <QAbstractTransition>

    struct StringEvent : public QEvent
    {
    StringEvent(const QString &val)
    : QEvent(QEvent::Type(QEvent::User+1)),
    value(val) {}

    QString value;
    

    };

    class StringTransition : public QAbstractTransition
    {
    Q_OBJECT

    public:
    StringTransition(const QString &value)
    : m_value(value) {}

    protected:
    virtual bool eventTest(QEvent *e)
    {
    if (e->type() != QEvent::Type(QEvent::User+1)) // StringEvent
    return false;
    StringEvent se = static_cast<StringEvent>(e);
    return (m_value == se->value);
    }

    virtual void onTransition(QEvent *) {}
    

    private:
    QString m_value;
    };

    Any idea?

    Thanks


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You're checking that too early, there's no event loop started. The machine needs one so it will really start once you reach the app.exec() call.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.