SCXML 交通灯(简单、QML)
这是一个Qt Quick 应用程序,它使用编译后的状态机来实现一个简化的交通灯。
交通灯演示了如何连接编译为类的状态机中状态的活动属性。
用户界面使用Qt Quick 创建。
运行示例
运行示例 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行。
编译状态机
我们通过在示例的编译文件中添加以下几行来链接Qt SCXML 模块。
在使用 qmake 时,我们在编译文件中添加.pro行:
QT += qml scxml
然后指定要编译的状态机:
STATECHARTS = ../trafficlight-common/statemachine.scxml
CMakeLists.txt当使用 cmake 时:
find_package(Qt6 REQUIRED COMPONENTS Core Gui Qml Scxml) target_link_libraries(trafficlight-qml-static PRIVATE Qt6::Core Qt6::Gui Qt6::Qml Qt6::Scxml )
然后指定要编译的状态机:
qt6_add_statecharts(trafficlight-qml-static ../trafficlight-common/statemachine.scxml )
状态图指令STATECHARTS或qt6_add_statecharts会调用Qt SCXML 编译器qscxmlc
,该编译器会自动运行以生成statemachine.h和statemachine.cpp,然后适当添加这两个文件作为编译时的头文件和源文件。
实例化状态机
我们按如下方式实例化状态机:
TrafficLightStateMachine { id: stateMachine running: true }
连接状态
在 SCXML 文件中,我们为每盏灯指定了状态:红灯、黄灯和绿灯。在<onentry>
元素中,我们指定了进入状态时要发送的事件以及发送事件前的延迟(以秒为单位)。在<transition>
元素中,我们指定了触发向target
属性指定的状态过渡的事件:
<state id="red"> <onentry> <send event="startGoingGreen" delay="3s"/> </onentry> <transition event="startGoingGreen" target="redGoingGreen"/> </state> <state id="yellow" initial="greenGoingRed"> <state id="redGoingGreen"> <onentry> <send event="goGreen" delay="1s"/> </onentry> <transition event="goGreen" target="green"/> </state> <state id="greenGoingRed"> <onentry> <send event="goRed" delay="1s"/> </onentry> <transition event="goRed" target="red"/> </state> </state> <state id="green"> <onentry> <send event="startGoingRed" delay="3s"/> </onentry> <transition event="startGoingRed" target="greenGoingRed"/> </state>
我们连接状态的方式如下:
Light { anchors.top: parent.top anchors.horizontalCenter: parent.horizontalCenter color: "red" visible: stateMachine.red || stateMachine.redGoingGreen } Light { anchors.centerIn: parent color: "yellow" visible: stateMachine.yellow || stateMachine.blinking } Light { anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter color: "green" visible: stateMachine.green } }
© 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.