Two-way Button Example

The Two-way button example shows how to use The State Machine Framework to implement a simple state machine that toggles the current state when a button is clicked.

int main(int argc, char **argv)
    QApplication app(argc, argv);
    QPushButton button;
    QStateMachine machine;

The application's main() function begins by constructing the application object, a button and a state machine.

    QState *off = new QState();
    off->assignProperty(&button, "text", "Off");

    QState *on = new QState();
    on->assignProperty(&button, "text", "On");

The state machine has two states; on and off. When either state is entered, the text of the button will be set accordingly.

    off->addTransition(&button, &QAbstractButton::clicked, on);
    on->addTransition(&button, &QAbstractButton::clicked, off);

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.


The states are added to the state machine; they become top-level (sibling) states.


The initial state is off; this is the state the state machine will immediately transition to once the state machine is started.

    button.resize(100, 50);;
    return app.exec();

Finally, the button is resized and made visible, and the application event loop is entered.

Example project @

© 2024 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.