Qt SCXML 计算器 QML 范例

A Qt Quick application that implements the Calculator example presented in the SCXML Specification.

计算器 使用 Qt SCXML 去实现 计算器范例 presented in the SCXML Specification.

The state machine is specified in the statemachine.scxml file and compiled into the CalculatorStateMachine class. The user interface is created using Qt Quick.

运行范例

要运行范例从 Qt Creator ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,拜访 构建和运行范例 .

编译状态机

We link against the Qt SCXML module by adding the following line to the .pro 文件:

QT += widgets scxml
					

接着,指定要编译的状态机:

STATECHARTS = ../calculator-common/statemachine.scxml
					

Qt SCXML 编译器 qscxmlc , is run automatically to generate statemachine.h and statemachine.cpp , and to add them to the HEADERS and SOURCES variables for compilation.

实例化状态机

We make the generated CalculatorStateMachine class available to QML by registering it as a QML type in the calculator-qml.cpp 文件:

#include "statemachine.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<CalculatorStateMachine>("CalculatorStateMachine", 1, 0,
                                            "CalculatorStateMachine");
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/calculator-qml.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    return app.exec();
}
					

To use the CalculatorStateMachine type in a QML file, we import it:

import CalculatorStateMachine 1.0
					

We instantiate a CalculatorStateMachine and listen to the updateDisplay event. When it occurs, we change the text on the calculator display:

    CalculatorStateMachine {
        id: statemachine
        running: true
        EventConnection {
            events: ["updateDisplay"]
            onOccurred: resultText.text = event.data.display
        }
    }
					

When users press the calculator buttons, the buttons submit events to the state machine:

        Button {
            id: resultButton
            x: 3 * width
            y: parent.height / 5
            textHeight: y - 2
            fontHeight: 0.4
            width: parent.width / 4
            height: y * 4
            color: pressed ? "#e0b91c" : "#face20"
            text: "="
            onClicked: statemachine.submitEvent("EQUALS")
        }
					

范例工程 @ code.qt.io