Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.
How to use QStateMachine in Qt
This article demonstrates how to use Qt's QStateMachine class.
The QStateMachine class provides a hierarchical finite state machine which is normally used in a complex task of programming or designing a circuit. If your task can be divided in a finite number of state then in such a case you can use this concept. At each state you just perform some task and then change the state. This will continue until you reach the final state.
Working of the code
In this example the state-machine has two finite states out of which one has been set as an initial state. When you click on the button a state transition been made converting the state to state s2.
Now using a simple switch-case statement depending on the current state you perform certain tasks and at the end make a state transition.
int main(int argc, char *argv)
QApplication app(argc, argv);
QWidget *win = new QWidget();
QLabel* label = new QLabel("state 1");
QVBoxLayout *layout = new QVBoxLayout;
QState *s1 = new QState();
s1->assignProperty(&button, "text", "Click me"); //Property is assign only when state-machine is started.
QLabel *label1 = new QLabel("state 2");
QFinalState *s2 = new QFinalState();
s1->addTransition(&button, SIGNAL(clicked()), s2);
Initially both the labels are shown. Click on the button to make a state transition.
Label "state-1" is hidden when a button is clicked.