SCXML交通安全灯(简单,QML)
一个使用编译状态机实现简化交通灯的Qt Quick应用程序。

交通安全灯展示了如何在编译为类的状态机中连接到活动的状态属性。
UI使用Qt Quick创建。
运行示例
要从Qt Creator运行此示例,请打开欢迎模式并从示例中选择示例。有关更多信息,请访问构建和运行示例。
编译状态机
我们通过在示例的构建文件中添加以下行来链接到Qt SCXML模块。
.pro 当使用qmake时:
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 } }
© 2024 Qt公司有限公司。此处包含的文档贡献是相应所有者的版权。此处提供的文档是根据由自由软件基金会发布的GNU自由文档许可版1.3的条款提供的。Qt及其相关标志是芬兰及其它国家Qt公司有限公司的商标。所有其他商标均属于其各自所有者。