QML Popup Overlay.modal 转换不工作

QML Popup Overlay.modal transition not working

我有以下 QML 组件,它使用 Overlay.modal 功能来模糊和调暗背景:

import QtQuick 2.0
import QtQuick.Controls 2.15
import QtGraphicalEffects 1.12

Popup {
    readonly property color backdropColor

    id: root
    visible: true
    padding: 50
    modal: true
    anchors.centerIn: parent
    width: 500
    height: 300

    contentItem: CB.Button {}

    background: CB.Card {}

    Overlay.modal: GaussianBlur {
        source: ShaderEffectSource {
            sourceItem: root.parent
            live: true
        }
        radius: 10
        samples: radius * 2

        Rectangle {
            id: backdropDim

            color: backdropColor
            anchors.fill: parent
        }
    }

    exit: Transition {
        NumberAnimation { property: "opacity"; from: 1; to: 0; duration: 120 }
        NumberAnimation { target: backdropDim; property: "opacity"; from: 1; to: 0; duration: 120 }
    }
    enter: Transition {
        NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 120 }
    }
}

我正在尝试使背景淡出(就像弹出窗口本身一样有效)。为此,我为背景的矩形指定了 id backdropDim。 但是,一旦模式关闭,Overlay.modal 就会消失,我会收到以下错误:

ReferenceError: backdropDim is not defined

我做错了什么? / 如何让背景平滑过渡消失?

问题是 Overlay.modal 是一个 Component,它(在 C++ 术语中)就像一个 class 定义,而不是那个 class 的一个实例。您正在尝试访问 class 的成员,但您实际上并没有对该 class.

的实例的引用

解决此问题的最佳方法是拉出要更改的 属性 (opacity),使其在组件定义之外:

Popup {
    // Maintain backdrop opacity outside of the modal component
    property real backdropOpacity: 1.0

然后在您的组件中使用新的 属性:

        Rectangle {
            id: backdropDim

            color: backdropColor
            anchors.fill: parent
            opacity: backdropOpacity    // <--
        }

最后还要在您的过渡中使用 属性:

    exit: Transition {
        NumberAnimation { property: "opacity"; from: 1; to: 0; duration: 120 }
        NumberAnimation { property: "backdropOpacity"; from: 1; to: 0; duration: 120 }
    }

更新:

Popup对象hides/shows模态组件通过改变其opacity属性。因此,您可以使用 Behavior 而不是过渡来轻松地为其设置动画。

    Overlay.modal: GaussianBlur {
        source: ShaderEffectSource {
            sourceItem: root.parent
            live: true
        }
        radius: 10
        samples: radius * 2

        Rectangle {
            id: backdropDim

            color: backdropColor
            anchors.fill: parent
        }

        Behavior on opacity {
            NumberAnimation {
                duration: 120
            }
        }

    }

    exit: Transition {
        NumberAnimation { property: "opacity"; from: 1; to: 0; duration: 120 }
    }
    enter: Transition {
        NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 120 }
    }