En esta página

SCXML Semáforo (Dinámico, QML)

Una aplicación Qt Quick que utiliza una máquina de estados cargada dinámicamente para implementar un semáforo.

Semáforo con luz verde encendida

Traffic Light QML demuestra cómo conectarse a las propiedades activas de un estado en una máquina de estados cargada dinámicamente.

La interfaz de usuario se crea utilizando Qt Quick.

Ejecución del ejemplo

Para ejecutar el ejemplo desde Qt Creatorabra el modo Welcome y seleccione el ejemplo de Examples. Para más información, ver Qt Creator: Tutorial: Construir y ejecutar.

Carga dinámica de la máquina de estados

Enlazamos con el módulo Qt SCXML añadiendo las siguientes líneas a los archivos de compilación del ejemplo.

A .pro cuando se utiliza qmake:

QT += qml scxml

A CMakeLists.txt cuando se utiliza cmake:

find_package(Qt6 REQUIRED COMPONENTS Core Gui Qml Scxml)
target_link_libraries(trafficlight-qml-dynamic PRIVATE
    Qt6::Core
    Qt6::Gui
    Qt6::Qml
    Qt6::Scxml
)

Creamos dinámicamente la máquina de estados en el archivo QML principal:

import QtScxml
import TrafficLightApplication

Window {
    width: lights.width
    height: lights.height
    visible: true

    Lights {
        id: lights
        stateMachine: loader.stateMachine
        // Suppress qmllint warning, dynamic statemachine properties not known at compile-time
        // qmllint disable missing-property
        button.source: stateMachine.working ? "pause.png" : "play.png"
        button.onClicked: stateMachine.submitEvent(stateMachine.working ? "smash" : "repair");
        // qmllint enable missing-property
    }

    StateMachineLoader {
        id: loader
        source: Qt.resolvedUrl("statemachine.scxml")
    }
}

Conectando a Estados

En el archivo SCXML, especificamos los estados para cada luz: rojo, amarillo y verde. En el elemento <onentry>, especificamos el evento a enviar al entrar en el estado y el retardo en segundos antes de enviar el evento. En el elemento <transition>, especificamos el evento que desencadena la transición al estado especificado por el atributo 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>

Nos conectamos a los estados de la siguiente manera:

    states: [
        // Suppress qmllint warning, dynamic statemachine properties not known at compile-time
        // qmllint disable missing-property
        State {
            name: "Red"
            when: lights.stateMachine.red

            PropertyChanges { redLight.opacity: 1 }
        },
        State {
            name: "RedGoingGreen"
            when: lights.stateMachine.redGoingGreen

            PropertyChanges { redLight.opacity: 1 }
            PropertyChanges { yellowLight.opacity: 1 }
        },
        State {
            name: "Yellow"
            when: lights.stateMachine.yellow || lights.stateMachine.blinking

            PropertyChanges { yellowLight.opacity: 1 }
        },
        State {
            name: "Green"
            when: lights.stateMachine.green

            PropertyChanges { greenLight.opacity: 1 }
        }
        // qmllint enable missing-property
    ]

Proyecto de ejemplo @ 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.