×
Namespaces

Variants
Actions

How to use QStateMachine in Qt

From Nokia Developer Wiki
Jump to: navigation, search

This article demonstrates how to use Qt's QStateMachine class.

Article Metadata
Tested withCompatibility
Platform(s):
Symbian
Article
Created: james1980 (01 Apr 2010)
Last edited: hamishwillee (11 Oct 2012)

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.

State1.jpg

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

State2.jpg

This page was last modified on 11 October 2012, at 04:17.
127 page views in the last 30 days.
×