The State Machine Framework¶
An overview of the State Machine framework for constructing and executing state graphs.
The State Machine framework provides classes for creating and executing state graphs. The concepts and notation are based on those from Harel’s Statecharts: A visual formalism for complex systems , which is also the basis of UML state diagrams. The semantics of state machine execution are based on State Chart XML (SCXML).
Statecharts provide a graphical way of modeling how a system reacts to stimuli. This is done by defining the possible states that the system can be in, and how the system can move from one state to another (transitions between states). A key characteristic of event-driven systems (such as Qt applications) is that behavior often depends not only on the last or current event, but also the events that preceded it. With statecharts, this information is easy to express.
The State Machine framework provides an API and execution model that can be used to effectively embed the elements and semantics of statecharts in Qt applications. The framework integrates tightly with Qt’s meta-object system; for example, transitions between states can be triggered by signals, and states can be configured to set properties and invoke methods on {
QObject
}s. Qt’s event system is used to drive the state machines.The state graph in the State Machine framework is hierarchical. States can be nested inside of other states, and the current configuration of the state machine consists of the set of states which are currently active. All the states in a valid configuration of the state machine will have a common ancestor.
Classes in the State Machine Framework¶
These classes are provided by qt for creating event-driven state machines.
PySide2.QtCore.QAbstractState
The QAbstractState class is the base class of states of a QStateMachine.
PySide2.QtCore.QAbstractTransition
The QAbstractTransition class is the base class of transitions between QAbstractState objects.
PySide2.QtCore.QEventTransition
The QEventTransition class provides a QObject-specific transition for Qt events.
PySide2.QtCore.QFinalState
The QFinalState class provides a final state.
PySide2.QtCore.QHistoryState
The QHistoryState class provides a means of returning to a previously active substate.
PySide2.QtCore.QSignalTransition
The QSignalTransition class provides a transition based on a Qt signal.
PySide2.QtCore.QState
The QState class provides a general-purpose state for QStateMachine.
PySide2.QtCore.QStateMachine
The QStateMachine class provides a hierarchical finite state machine.
QStateMachine.SignalEvent
The SignalEvent class represents a Qt signal event.
QStateMachine.WrappedEvent
The WrappedEvent class inherits QEvent and holds a clone of an event associated with a QObject.
The QBasicKeyEventTransition class provides a transition for Qt key events.
The QBasicMouseEventTransition class provides a transition for Qt mouse events.
PySide2.QtWidgets.QKeyEventTransition
The QKeyEventTransition class provides a transition for key events.
PySide2.QtWidgets.QMouseEventTransition
The QMouseEventTransition class provides a transition for mouse events.
A Simple State Machine¶
To demonstrate the core functionality of the State Machine API, let’s look at a small example: A state machine with three states,
s1
,s2
ands3
. The state machine is controlled by a singleQPushButton
; when the button is clicked, the machine transitions to another state. Initially, the state machine is in states1
. The statechart for this machine is as follows:The following snippet shows the code needed to create such a state machine. First, we create the state machine and states:
QStateMachine machine; QState *s1 = new QState(); QState *s2 = new QState(); QState *s3 = new QState();Then, we create the transitions by using the
addTransition()
function:s1->addTransition(button, &QPushButton::clicked, s2); s2->addTransition(button, &QPushButton::clicked, s3); s3->addTransition(button, &QPushButton::clicked, s1);Next, we add the states to the machine and set the machine’s initial state:
machine.addState(s1); machine.addState(s2); machine.addState(s3); machine.setInitialState(s1);Finally, we start the state machine:
machine.start();The state machine executes asynchronously, i.e. it becomes part of your application’s event loop.
Doing Useful Work on State Entry and Exit¶
The above state machine merely transitions from one state to another, it doesn’t perform any operations. The
assignProperty()
function can be used to have a state set a property of aQObject
when the state is entered. In the following snippet, the value that should be assigned to aQLabel
‘s text property is specified for each state:s1->assignProperty(label, "text", "In state s1"); s2->assignProperty(label, "text", "In state s2"); s3->assignProperty(label, "text", "In state s3");When any of the states is entered, the label’s text will be changed accordingly.
The
entered()
signal is emitted when the state is entered, and theexited()
signal is emitted when the state is exited. In the following snippet, the button’sshowMaximized()
slot will be called when states3
is entered, and the button’sshowMinimized()
slot will be called whens3
is exited:QObject::connect(s3, &QState::entered, button, &QPushButton::showMaximized); QObject::connect(s3, &QState::exited, button, &QPushButton::showMinimized);Custom states can reimplement
onEntry()
andonExit()
.
State Machines That Finish¶
The state machine defined in the previous section never finishes. In order for a state machine to be able to finish, it needs to have a top-level final state (
QFinalState
object). When the state machine enters a top-level final state, the machine will emit thefinished()
signal and halt.All you need to do to introduce a final state in the graph is create a
QFinalState
object and use it as the target of one or more transitions.
Using History States to Save and Restore the Current State¶
Imagine that we wanted to add an “interrupt” mechanism to the example discussed in the previous section; the user should be able to click a button to have the state machine perform some non-related task, after which the state machine should resume whatever it was doing before (i.e. return to the old state, which is one of
s11
,s12
ands13
in this case).Such behavior can easily be modeled using history states . A history state (
QHistoryState
object) is a pseudo-state that represents the child state that the parent state was in the last time the parent state was exited.A history state is created as a child of the state for which we wish to record the current child state; when the state machine detects the presence of such a state at runtime, it automatically records the current (real) child state when the parent state is exited. A transition to the history state is in fact a transition to the child state that the state machine had previously saved; the state machine automatically “forwards” the transition to the real child state.
The following diagram shows the state machine after the interrupt mechanism has been added.
The following code shows how it can be implemented; in this example we simply display a message box when
s3
is entered, then immediately return to the previous child state ofs1
via the history state.QHistoryState *s1h = new QHistoryState(s1); QState *s3 = new QState(); s3->assignProperty(label, "text", "In s3"); QMessageBox *mbox = new QMessageBox(mainWindow); mbox->addButton(QMessageBox::Ok); mbox->setText("Interrupted!"); mbox->setIcon(QMessageBox::Information); QObject::connect(s3, &QState::entered, mbox, &QMessageBox::exec); s3->addTransition(s1h); machine.addState(s3); s1->addTransition(interruptButton, &QPushButton::clicked, s3);
Using Parallel States to Avoid a Combinatorial Explosion of States¶
Assume that you wanted to model a set of mutually exclusive properties of a car in a single state machine. Let’s say the properties we are interested in are Clean vs Dirty, and Moving vs Not moving. It would take four mutually exclusive states and eight transitions to be able to represent and freely move between all possible combinations.
If we added a third property (say, Red vs Blue), the total number of states would double, to eight; and if we added a fourth property (say, Enclosed vs Convertible), the total number of states would double again, to 16.
Using parallel states, the total number of states and transitions grows linearly as we add more properties, instead of exponentially. Furthermore, states can be added to or removed from the parallel state without affecting any of their sibling states.
To create a parallel state group, pass
ParallelStates
to theQState
constructor.QState *s1 = new QState(QState::ParallelStates); // s11 and s12 will be entered in parallel QState *s11 = new QState(s1); QState *s12 = new QState(s1);When a parallel state group is entered, all its child states will be simultaneously entered. Transitions within the individual child states operate normally. However, any of the child states may take a transition which exits the parent state. When this happens, the parent state and all of its child states are exited.
The parallelism in the State Machine framework follows an interleaved semantics. All parallel operations will be executed in a single, atomic step of the event processing, so no event can interrupt the parallel operations. However, events will still be processed sequentially, since the machine itself is single threaded. As an example: Consider the situation where there are two transitions that exit the same parallel state group, and their conditions become true simultaneously. In this case, the event that is processed last of the two will not have any effect, since the first event will already have caused the machine to exit from the parallel state.
Detecting that a Composite State has Finished¶
A child state can be final (a
QFinalState
object); when a final child state is entered, the parent state emits thefinished()
signal. The following diagram shows a composite states1
which does some processing before entering a final state:When
s1
‘s final state is entered,s1
will automatically emitfinished()
. We use a signal transition to cause this event to trigger a state change:s1->addTransition(s1, &QState::finished, s2);Using final states in composite states is useful when you want to hide the internal details of a composite state; i.e. the only thing the outside world should be able to do is enter the state, and get a notification when the state has completed its work. This is a very powerful abstraction and encapsulation mechanism when building complex (deeply nested) state machines. (In the above example, you could of course create a transition directly from
s1
‘sdone
state rather than relying ons1
‘sfinished()
signal, but with the consequence that implementation details ofs1
are exposed and depended on).For parallel state groups, the
finished()
signal is emitted when all the child states have entered final states.
Targetless Transitions¶
A transition need not have a target state. A transition without a target can be triggered the same way as any other transition; the difference is that when a targetless transition is triggered, it doesn’t cause any state changes. This allows you to react to a signal or event when your machine is in a certain state, without having to leave that state. Example:
QStateMachine machine; QState *s1 = new QState(&machine); QPushButton button; QSignalTransition *trans = new QSignalTransition(&button, &QPushButton::clicked); s1->addTransition(trans); QMessageBox msgBox; msgBox.setText("The button was clicked; carry on."); QObject::connect(trans, QSignalTransition::triggered, &msgBox, &QMessageBox::exec); machine.setInitialState(s1);The message box will be displayed each time the button is clicked, but the state machine will remain in its current state (s1). If the target state were explicitly set to s1, however, s1 would be exited and re-entered each time (e.g. the
entered()
andexited()
signals would be emitted).
Events, Transitions and Guards¶
A
QStateMachine
runs its own event loop. For signal transitions (QSignalTransition
objects),QStateMachine
automatically posts aSignalEvent
to itself when it intercepts the corresponding signal; similarly, forQObject
event transitions (QEventTransition
objects) aWrappedEvent
is posted.You can post your own events to the state machine using
postEvent()
.When posting a custom event to the state machine, you typically also have one or more custom transitions that can be triggered from events of that type. To create such a transition, you subclass
QAbstractTransition
and reimplementeventTest()
, where you check if an event matches your event type (and optionally other criteria, e.g. attributes of the event object).Here we define our own custom event type,
StringEvent
, for posting strings to the state machine:struct StringEvent : public QEvent { StringEvent(const QString &val) : QEvent(QEvent::Type(QEvent::User+1)), value(val) {} QString value; };Next, we define a transition that only triggers when the event’s string matches a particular string (a guarded transition):
class StringTransition : public QAbstractTransition { Q_OBJECT public: StringTransition(const QString &value) : m_value(value) {} protected: bool eventTest(QEvent *e) override { if (e->type() != QEvent::Type(QEvent::User+1)) // StringEvent return false; StringEvent *se = static_cast<StringEvent*>(e); return (m_value == se->value); } void onTransition(QEvent *) override {} private: QString m_value; };In the
eventTest()
reimplementation, we first check if the event type is the desired one; if so, we cast the event to aStringEvent
and perform the string comparison.The following is a statechart that uses the custom event and transition:
Here’s what the implementation of the statechart looks like:
QStateMachine machine; QState *s1 = new QState(); QState *s2 = new QState(); QFinalState *done = new QFinalState(); StringTransition *t1 = new StringTransition("Hello"); t1->setTargetState(s2); s1->addTransition(t1); StringTransition *t2 = new StringTransition("world"); t2->setTargetState(done); s2->addTransition(t2); machine.addState(s1); machine.addState(s2); machine.addState(done); machine.setInitialState(s1);Once the machine is started, we can post events to it.
machine.postEvent(new StringEvent("Hello")); machine.postEvent(new StringEvent("world"));An event that is not handled by any relevant transition will be silently consumed by the state machine. It can be useful to group states and provide a default handling of such events; for example, as illustrated in the following statechart:
For deeply nested statecharts, you can add such “fallback” transitions at the level of granularity that’s most appropriate.
Using Restore Policy To Automatically Restore Properties¶
In some state machines it can be useful to focus the attention on assigning properties in states, not on restoring them when the state is no longer active. If you know that a property should always be restored to its initial value when the machine enters a state that does not explicitly give the property a value, you can set the global restore policy to
RestoreProperties
.QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties);When this restore policy is set, the machine will automatically restore all properties. If it enters a state where a given property is not set, it will first search the hierarchy of ancestors to see if the property is defined there. If it is, the property will be restored to the value defined by the closest ancestor. If not, it will be restored to its initial value (i.e. the value of the property before any property assignments in states were executed.)
Take the following code:
QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); QState *s1 = new QState(); s1->assignProperty(object, "fooBar", 1.0); machine.addState(s1); machine.setInitialState(s1); QState *s2 = new QState(); machine.addState(s2);Lets say the property
fooBar
is 0.0 when the machine starts. When the machine is in states1
, the property will be 1.0, since the state explicitly assigns this value to it. When the machine is in states2
, no value is explicitly defined for the property, so it will implicitly be restored to 0.0.If we are using nested states, the parent defines a value for the property which is inherited by all descendants that do not explicitly assign a value to the property.
QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); QState *s1 = new QState(); s1->assignProperty(object, "fooBar", 1.0); machine.addState(s1); machine.setInitialState(s1); QState *s2 = new QState(s1); s2->assignProperty(object, "fooBar", 2.0); s1->setInitialState(s2); QState *s3 = new QState(s1);Here
s1
has two children:s2
ands3
. Whens2
is entered, the propertyfooBar
will have the value 2.0, since this is explicitly defined for the state. When the machine is in states3
, no value is defined for the state, buts1
defines the property to be 1.0, so this is the value that will be assigned tofooBar
.
Animating Property Assignments¶
The State Machine API connects with the Animation API in Qt to allow automatically animating properties as they are assigned in states.
Say we have the following code:
QState *s1 = new QState(); QState *s2 = new QState(); s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); s1->addTransition(button, &QPushButton::clicked, s2);Here we define two states of a user interface. In
s1
thebutton
is small, and ins2
it is bigger. If we click the button to transition froms1
tos2
, the geometry of the button will be set immediately when a given state has been entered. If we want the transition to be smooth, however, all we need to do is make aQPropertyAnimation
and add this to the transition object.QState *s1 = new QState(); QState *s2 = new QState(); s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); QSignalTransition *transition = s1->addTransition(button, &QPushButton::clicked, s2); transition->addAnimation(new QPropertyAnimation(button, "geometry"));Adding an animation for the property in question means that the property assignment will no longer take immediate effect when the state has been entered. Instead, the animation will start playing when the state has been entered and smoothly animate the property assignment. Since we do not set the start value or end value of the animation, these will be set implicitly. The start value of the animation will be the property’s current value when the animation starts, and the end value will be set based on the property assignments defined for the state.
If the global restore policy of the state machine is set to
RestoreProperties
, it is possible to also add animations for the property restorations.
Detecting That All Properties Have Been Set In A State¶
When animations are used to assign properties, a state no longer defines the exact values that a property will have when the machine is in the given state. While the animation is running, the property can potentially have any value, depending on the animation.
In some cases, it can be useful to be able to detect when the property has actually been assigned the value defined by a state.
Say we have the following code:
QMessageBox *messageBox = new QMessageBox(mainWindow); messageBox->addButton(QMessageBox::Ok); messageBox->setText("Button geometry has been set!"); messageBox->setIcon(QMessageBox::Information); QState *s1 = new QState(); QState *s2 = new QState(); s2->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); connect(s2, &QState::entered, messageBox, SLOT(exec())); s1->addTransition(button, &QPushButton::clicked, s2);When
button
is clicked, the machine will transition into states2
, which will set the geometry of the button, and then pop up a message box to alert the user that the geometry has been changed.In the normal case, where animations are not used, this will operate as expected. However, if an animation for the
geometry
ofbutton
is set on the transition betweens1
ands2
, the animation will be started whens2
is entered, but thegeometry
property will not actually reach its defined value before the animation is finished running. In this case, the message box will pop up before the geometry of the button has actually been set.To ensure that the message box does not pop up until the geometry actually reaches its final value, we can use the state’s
propertiesAssigned()
signal. ThepropertiesAssigned()
signal will be emitted when the property is assigned its final value, whether this is done immediately or after the animation has finished playing.QMessageBox *messageBox = new QMessageBox(mainWindow); messageBox->addButton(QMessageBox::Ok); messageBox->setText("Button geometry has been set!"); messageBox->setIcon(QMessageBox::Information); QState *s1 = new QState(); QState *s2 = new QState(); s2->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); QState *s3 = new QState(); connect(s3, &QState::entered, messageBox, SLOT(exec())); s1->addTransition(button, &QPushButton::clicked, s2); s2->addTransition(s2, &QState::propertiesAssigned, s3);In this example, when
button
is clicked, the machine will enters2
. It will remain in states2
until thegeometry
property has been set toQRect(0, 0, 50, 50)
. Then it will transition intos3
. Whens3
is entered, the message box will pop up. If the transition intos2
has an animation for thegeometry
property, then the machine will stay ins2
until the animation has finished playing. If there is no such animation, it will simply set the property and immediately enter states3
.Either way, when the machine is in state
s3
, you are guaranteed that the propertygeometry
has been assigned the defined value.If the global restore policy is set to
RestoreProperties
, the state will not emit thepropertiesAssigned()
signal until these have been executed as well.
What Happens If A State Is Exited Before The Animation Has Finished¶
If a state has property assignments, and the transition into the state has animations for the properties, the state can potentially be exited before the properties have been assigned to the values defines by the state. This is true in particular when there are transitions out from the state that do not depend on the
propertiesAssigned()
signal, as described in the previous section.The State Machine API guarantees that a property assigned by the state machine either:
Has a value explicitly assigned to the property.
Is currently being animated into a value explicitly assigned to the property.
When a state is exited prior to the animation finishing, the behavior of the state machine depends on the target state of the transition. If the target state explicitly assigns a value to the property, no additional action will be taken. The property will be assigned the value defined by the target state.
If the target state does not assign any value to the property, there are two options: By default, the property will be assigned the value defined by the state it is leaving (the value it would have been assigned if the animation had been permitted to finish playing). If a global restore policy is set, however, this will take precedence, and the property will be restored as usual.
Default Animations¶
As described earlier, you can add animations to transitions to make sure property assignments in the target state are animated. If you want a specific animation to be used for a given property regardless of which transition is taken, you can add it as a default animation to the state machine. This is in particular useful when the properties assigned (or restored) by specific states is not known when the machine is constructed.
QState *s1 = new QState(); QState *s2 = new QState(); s2->assignProperty(object, "fooBar", 2.0); s1->addTransition(s2); QStateMachine machine; machine.setInitialState(s1); machine.addDefaultAnimation(new QPropertyAnimation(object, "fooBar"));When the machine is in state
s2
, the machine will play the default animation for the propertyfooBar
since this property is assigned bys2
.Note that animations explicitly set on transitions will take precedence over any default animation for the given property.
Nesting State Machines¶
QStateMachine
is a subclass ofQState
. This allows for a state machine to be a child state of another machine.QStateMachine
reimplementsonEntry()
and callsstart()
, so that when the child state machine is entered, it will automatically start running.The parent state machine treats the child machine as an atomic state in the state machine algorithm. The child state machine is self-contained; it maintains its own event queue and configuration. In particular, note that the
configuration()
of the child machine is not part of the parent machine’s configuration (only the child machine itself is).States of the child state machine cannot be specified as targets of transitions in the parent state machine; only the child state machine itself can. Conversely, states of the parent state machine cannot be specified as targets of transitions in the child state machine. The child state machine’s
finished
() signal can be used to trigger a transition in the parent machine.See also
The Declarative State Machine Framework
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.