为什么在加载时触发动画

时间:2019-02-22 10:26:45

标签: qt qml qt5

当窗口打开时,您可以看到矩形滑出。我将y属性设置为父级高度,因此它应该最初位于窗口之外,为什么要对此设置动画?
我的猜测是因为parent:height。也许是因为parent.height在加载时不可用,并且初始设置为0?

我有以下示例可以重现:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Rectangle {
        id: test;
        y: parent.height;
        states: [
            State {
                name: "slideOut"
                PropertyChanges{
                    target: test;
                    y: parent.height;
                }
            },
            State {
                name: "slideIn"
                PropertyChanges{
                    target: test;
                    y: 0;

                }
            }
        ]
        Behavior on y {
            NumberAnimation {
                duration: 500;
            }
        }
        color: "red";
        width: parent.width;
        height: parent.height;

    }

    MouseArea {
        anchors.fill: parent;
        onClicked: {
            if(test.state == "slideIn") {
                test.state = "slideOut";
            } else {
                test.state = "slideIn";
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的猜测听起来很真实。

您应该将transitions与状态一起使用:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Rectangle {
        id: test
        y: parent.height
        width: parent.width
        height: parent.height
        color: "red"

        states: [
            State {
                name: "slideOut"
                PropertyChanges {
                    target: test
                    y: parent.height
                }
            },
            State {
                name: "slideIn"
                PropertyChanges {
                    target: test
                    y: 0
                }
            }
        ]
        transitions: [
            Transition {
                NumberAnimation {
                    property: "y"
                    duration: 500
                }
            }
        ]
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            if (test.state == "slideIn") {
                test.state = "slideOut"
            } else {
                test.state = "slideIn"
            }
        }
    }
}

另一种解决方案是使用Behavior的enabled属性仅在窗口准备就绪时运行动画。我不确定您将基于哪个属性。一些想法:

  • enabled: window.height > 0
  • enabled: window.active