Search code examples
c++qtqt4

Create a qstate in qt


If I have a simple state machine like that

  switch(state)
    {
    case state_1:
      doSomething();
    state = state_2;
    break;
    case state_2:
    doSomething_2();
state = state_finished;
    break;
    }

how would I convert this simple state machine into qstate with transitions ?


Solution

  • It would be for example something like this:

    TestClass test_class;
    QStateMachine machine;
    
    QState *state_1 = new QState(&machine);
    QObject::connect(state_1, SIGNAL(entered()), &test_class, SLOT(doSomething1()));
    
    QState *state_2 = new QState(&machine);
    QObject::connect(state_2, SIGNAL(entered()), &test_class, SLOT(doSomething2()));
    
    QFinalState *state_finished = new QFinalState(&machine);
    TestClassFinishedTransition *finished_transition = 
                                    new TestClassFinishedTransition(&test_class);
    finished_transition->setTargetState(state_finished);
    state_2->addTransition(finished_transition);
    
    machine.setInitialState(state_1);
    machine.start();
    

    TestClass would be QObject based class.

    I hope this piece of code helps you to get started in understanding the concept. However, you have to read the documentation carefully and go through examples provided by Qt.