How to use QStateMachine in Qt
This article demonstrates how to use Qt's QStateMachine class.
Article Metadata
Tested with
Article
Contents |
Overview
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.
Source file
#include <QApplication>
#include <QState>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QStateMachine>
#include <QFinalState>
#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
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.




(no comments yet)