本页面内容

SCXML 计算器

一个实现 SCXML 规范中“计算器”示例的应用程序。

带数字显示屏、运算符按键和数字按键的计算器

该计算器使用Qt SCXML 类来实现SCXML规范中提出的“计算器”示例。

状态机在statemachine.scxml文件中进行定义,并编译为CalculatorStateMachine 类。用户界面使用Qt Quick 创建。

运行示例

您可以通过以下方式运行该示例:

实例化状态机

我们通过在calculator-qml.h文件中将其声明为 QML 类型,使生成的CalculatorStateMachine 类可在 QML 中使用:

struct CalculatorStateMachineRegistration
{
    Q_GADGET
    QML_FOREIGN(CalculatorStateMachine)
    QML_NAMED_ELEMENT(CalculatorStateMachine)
    QML_ADDED_IN_VERSION(1, 0)
};

我们实例化一个 CalculatorStateMachine,并监听updateDisplay 事件。当该事件发生时,我们会更改计算器显示屏上的文本:

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

当用户按下计算器按键时,按键会向状态机提交事件:

        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

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