SCXML Invoke
调用一个已编译的嵌套状态机。

“Invoke”演示了如何在生成的嵌套状态机中使用<invoke> 元素,其中SCXML文件被编译为C++类。<invoke> 元素用于创建外部服务的实例。
运行示例
您可以通过以下方式运行示例:
- Qt Creator
打开Welcome 模式,然后从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
调用状态机
在statemachine.scxml 中,我们定义了一个名为DirectionsStateMachine、类型为http://www.w3.org/TR/scxml/的状态机以供调用:
<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使用 cmake 时,在CMakeLists.txt中:
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
)状态图指令STATECHARTS或qt6_add_statecharts会调用Qt SCXML 编译器(qscxmlc ),该编译器会自动运行以生成statemachine.h和statemachine.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
}© 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.