如何为对话框设置动画以从屏幕外进入?

How can I animate a Dialog to enter from outside the screen?

This question is similar to - but no the same as , because my question is about Dialogs, instead of Items in general. The difference is explained below.

我有一个 Qt 对话框,我想从左边进入屏幕。

我采用的第一种方法是将对话框 x 属性 设置为 -width,然后添加 Behavior on x 或手动触发的 NumberAnimation

然而这种方法失败了,因为设置负 x 值是不允许的,并且该值会立即更改为 0。

通过使用锚点以及 AnchorChangestransitions 为这个问题提供了解决方案 - 但仅适用于项目。

但是,Dialog 类型既不提供状态,也不提供锚点,只提供坐标。

所以我的问题是:如何让 QML 对话框从屏幕左侧动画进入视图?

这是一个最小的代码示例,演示了 x 属性 被重置为 0:

import QtQuick 2.7
import QtQuick.Controls 2.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Dialog Demo")

    Dialog {
        id: dialog

        width: 200
        height: 200

        x: -width

        Text {
            anchors.centerIn: parent
            text: "Ok?"
        }

        standardButtons: Dialog.Ok
        onOpened: x = 100

        Behavior on x { NumberAnimation{ duration: 1000 } }
    }

    Component.onCompleted: dialog.open()
}

您可以使用继承自 Popupenter-transition:

import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 2.3

Window {
    id: window
    visible: true
    width: 600
    height: 600

    Dialog {
        id: dialog
        width: 300
        height: 300

        enter: Transition {
            NumberAnimation { properties: "x,y"; from: -300; to: 150 }
        }
    }

    Button {
        anchors.centerIn: parent
        onClicked: dialog.open()
    }
}

There seems to be a Bug with the Dialog. As soon as the Dialog has some content, it fails. I have not discovered all depths of it, but wrapping everything in an Item seems to help. Compare for this:

import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 2.3

ApplicationWindow {
    id: window
    visible: true
    width: 600
    height: 600

    Dialog {
        id: dialog
        width: 300
        height: 300

        enter: Transition {
            NumberAnimation { properties: "x,y"; from: -300; to: 150; duration: 5000 }
        }

        // HAVE A BUTTON IN THE DIALOG -> POSITIONING FAILS
        Button {
            anchors.centerIn: parent
        }    
    }

    Button {
        text: 'open'
        anchors.centerIn: parent
        onClicked: dialog.open()
    }
}

import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 2.3

ApplicationWindow {
    id: window
    visible: true
    width: 600
    height: 600

    Dialog {
        id: dialog
        width: 300
        height: 300

        enter: Transition {
            NumberAnimation { properties: "x,y"; from: -300; to: 150; duration: 5000 }
        }

        Item {  // WRAP IT IN THE ITEM -> WORKS FOR ME
            anchors.fill: parent
            Button {
                anchors.centerIn: parent
            }
        }
    }

    Button {
        text: 'open'
        anchors.centerIn: parent
        onClicked: dialog.open()
    }
}