SCXML 调用

调用已编译的嵌套状态机。

Invoke演示了如何将<invoke> 元素与生成的嵌套状态机一起使用,其中 SCXML 文件被编译为 C++ 类。<invoke> 元素用于创建外部服务实例。

运行示例

要从 Qt Creator,打开Welcome 模式,并从Examples 中选择示例。有关详细信息,请参阅Qt Creator: 教程:构建并运行

调用状态机

statemachine.scxml 中,我们指定要调用的状态机类型为http://www.w3.org/TR/scxml/,名称为DirectionsStateMachine

<scxml
    xmlns="http://www.w3.org/2005/07/scxml"
    version="1.0"
    name="DirectionsStateMachine"
    initial="anyplace"
>
    <state id="anyplace">
        <transition event="goNowhere" target="nowhere"/>
        <transition event="goSomewhere" target="somewhere"/>

        <state id="nowhere"/>
        <state id="somewhere">
            <invoke type="http://www.w3.org/TR/scxml/">
                <content>
                    <scxml name="anywhere" version="1.0">
                        <state id="here">
                            <transition event="goThere" target="there"/>
                        </state>
                        <state id="there">
                            <transition event="goHere" target="here"/>
                        </state>
                    </scxml>
                </content>
            </invoke>
        </state>
    </state>
</scxml>

编译状态机

我们通过在示例的构建文件中添加以下行来链接Qt SCXML 模块。

在使用 qmake 时,将invoke.pro添加到编译文件中:
QT += qml scxml

然后指定要编译的状态机:

STATECHARTS = statemachine.scxml
CMakeLists.txt当使用 cmake 时:
find_package(Qt6 REQUIRED COMPONENTS Core Gui Qml Scxml)

target_link_libraries(invoke PRIVATE
    Qt6::Core
    Qt6::Gui
    Qt6::Qml
    Qt6::Scxml
)

然后指定要编译的状态机:

qt6_add_statecharts(invoke
    statemachine.scxml
)

状态图指令STATECHARTSqt6_add_statecharts会调用Qt SCXML 编译器qscxmlc ,该编译器会自动运行以生成statemachine.hstatemachine.cpp,然后适当添加这两个文件作为编译时的头文件和源文件。

将状态机声明为 QML 元素

状态机作为 QML 元素声明如下:

struct DirectionsStateMachineRegistration
{
    Q_GADGET
    QML_FOREIGN(DirectionsStateMachine)
    QML_NAMED_ELEMENT(DirectionsStateMachine)
    QML_ADDED_IN_VERSION(1, 0)
};

实例化状态机

我们在MainView.qml文件中实例化生成的DirectionsStateMachine 元素,如下所示:

    DirectionsStateMachine {
        id: stateMachine
        running: true
    }

示例项目 @ code.qt.io

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