Archived:How to create a 2-state button using the Qt State Machine Framework
Archived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (using C++ for the Qt app UI) is deprecated.
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (using C++ for the Qt app UI) is deprecated.
This example shows how to use the Qt State Machine Framework to implement a simple state machine that toggles the current state when a button is clicked.
Article Metadata
Implementation
- construct a button and a state machine
QPushButton button;
QStateMachine machine;
- Create two states: on and off. assign Property and ObjectName of the each state
QState *off = new QState();
off->assignProperty(&button, "text", "Off");
off->setObjectName("off");
QState *on = new QState();
on->setObjectName("on");
on->assignProperty(&button, "text", "On");
- When the state machine is in the off state and the button is clicked, it will transition to the on state; when the state machine is in the on state and the button is clicked, it will transition to the off state.
-
off->addTransition(&button, SIGNAL(clicked()), on);
on->addTransition(&button, SIGNAL(clicked()), off);
-
- add states to the state machine
-
machine.addState(off);
machine.addState(on);
-
- set the Initial State
-
machine.setInitialState(off);
machine.start();
-
- show the button
button.resize(100, 50);
button.show();

