HistoryStateサンプル


HistoryStateのサンプル

テスト用QML

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQml.StateMachine 1.0 as DSM
import QtMultimedia 5.9

ApplicationWindow {
    id: root
    width: 640
    height: 480
    title: "HistoryState Test"
    visible: true

    Audio { id: sound; source: "Sounds/btn01.mp3" }


    Row {
        spacing: 2

        Rectangle { id: colorBox; width: root.width / 2; height: root.height }

        // ボタン
        Button {
            id: button
            width: root.width / 2
            height: root.height
            text: "Press me"
            onClicked: sound.play()

            // StateMachine 定義
            // 初期状態は parentState
            DSM.StateMachine {
                id: stateMachine
                initialState: parentState
                running: true

                // parentState 定義
                // 初期子状態は child2
                DSM.State {
                    id: parentState
                    initialState: child2
                    onEntered: console.log("parentState entered")
                    onExited: console.log("parentState exited")

                    // child1 子状態定義
                    DSM.State {
                        id: child1
                        onEntered: { console.log("child1 entered"); colorBox.color = "blue"; }  // 青くする
                        onExited: console.log("child1 exited")
                    }

                    // child2 子状態定義
                    DSM.State {
                        id: child2
                        onEntered: { console.log("child2 entered"); colorBox.color = "red"; }   // 赤くする
                        onExited: console.log("child2 exited")
                    }

                    // HistoryState 定義
                    // 初期状態の履歴は child1 にする
                    // HistoryState により、child1 と child2 を繰り返す
                    DSM.HistoryState {
                        id: historyState
                        defaultState: child1
                    }

                    // トリガはボタンのクリックとする
                    DSM.SignalTransition {
                        targetState: historyState
                        signal: button.clicked
                    }
                }
            }
        }
    }
}

実行結果

SignalTransitionサンプル動画
※Linux Mint 18.2 & Qt 5.9.1使用