How to use QStateMachine in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:Abstract

Template:ArticleMetaData

Overview[edit | edit source]

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[edit | edit source]

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.

Source file[edit | edit source]

  1. include <QApplication>
  2. include <QState>
  3. include <QPushButton>
  4. include <QLabel>
  5. include <QVBoxLayout>
  6. include <QStateMachine>
  7. include <QFinalState>
  8. include <QWidget>

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

   QApplication app(argc, argv);
   QWidget *win = new QWidget();
   QPushButton button;
   QStateMachine machine;
   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);
   machine.addState(s1);
   machine.addState(s2);
   machine.setInitialState(s1);
   machine.start();
   
   QObject::connect(s1,SIGNAL(exited()),label,SLOT(hide()));
   QObject::connect(&machine,SIGNAL(stopped()),label1,SLOT(hide()));
   layout->addWidget(&button);
   layout->addWidget(label);
   layout->addWidget(label1);
   win->setLayout(layout);
   win->show();
   return app.exec();

}

Output[edit | edit source]

Initially both the labels are shown. Click on the button to make a state transition.

File:State1.jpg

Label "state-1" is hidden when a button is clicked.

File:State2.jpg