2018年5月5日

switchparent.qml

switchparent.qml:

import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Layouts 1.3

Window {
    id: window

    visible: true

    minimumWidth: 300
    minimumHeight: 300

    RowLayout {
        id: topLayout

        anchors.fill: parent
        anchors.margins: spacing

        Rectangle {
            id: leftRect

            Layout.fillWidth: true
            Layout.fillHeight: true

            objectName: "leftRect"
            color: "red"

            Rectangle {
                id: innerRect

                x: 10; y: 10
                width: (minimumWidth - 3*topLayout.spacing)/2 - 2*10
                height: width

                color: "blue"

                Text {
                    anchors.centerIn: parent

                    text: "%1\n%2, %3\n%4x%5".arg(innerRect.parent.objectName)
                                             .arg(parent.x).arg(parent.y)
                                             .arg(parent.width).arg(parent.height)
                    color: "white"
                }
            }
        }

        Rectangle {
            id: rightRect

            Layout.fillWidth: true
            Layout.fillHeight: true

            objectName: "rightRect"
            color: "green"
        }
    }

    contentItem.states: State {
        name: "switchToRight"

        ParentChange {
            target: innerRect
            parent: rightRect
            x: rightRect.width - innerRect.width - 10
            y: rightRect.height - innerRect.height - 10
        }

        PropertyChanges {
            target: innerRect
            color: "darkblue"
        }
    }

    contentItem.transitions: Transition {
        ParentAnimation {
            via: contentItem

            NumberAnimation {
                properties: "x, y"
                duration: 3000
            }

            ColorAnimation {
                duration: 3000
            }
        }
    }

    MouseArea {
        anchors.fill: parent

        onClicked: {
            if (contentItem.state === "") {
                contentItem.state = "switchToRight";
            } else {
                contentItem.state = "";
            }
        }
    }
}
ウィンドウをクリックすると青い Rectangle の parent を右側の Rectangle に変更し右下に配置する。もう一度クリックすると parent を元に戻している。ParentAnimation 内の 2 つのアニメーションは並列に動作する。ParentAnimation で via を指定しないと青い Rectangle が右側から左側に移動するときに右側の Rectangle の裏に隠れてしまう。これはアニメーション開始時に青い Rectangle の parent が左側の Rectangle に変わることと、左側の Rectangle の parent 設定が右側の Rectangle の parent 設定よりも先に行われているので左側の Rectangle が右側の Rectangle の下に描画されるためである。