【问题标题】:Animation for Qml Loader when loader.source changesloader.source 更改时 Qml Loader 的动画
【发布时间】:2015-07-04 09:27:11
【问题描述】:

当我们在 QML 中更改 Loader 组件的来源时,有什么方法可以应用动画吗? 例如假设我有以下Loader:

Loader {
     anchors.fill: parent
     id: loader
}

当我设置loader.source = "content.qml"时,我想要一个从左到右的动画

感谢您的帮助。

【问题讨论】:

    标签: qt qml qtquick2 qt-quick qt5.4


    【解决方案1】:

    这是一种方法:

    import QtQuick 2.4
    import QtQuick.Window 2.0
    
    Window {
        id: window
        width: 400
        height: 400
        visible: true
    
        Loader {
            id: loader
            onSourceChanged: animation.running = true
    
            NumberAnimation {
                id: animation
                target: loader.item
                property: "x"
                from: 0
                to: window.width - loader.item.width
                duration: 1000
                easing.type: Easing.InExpo
            }
        }
    
        // Replace this with some other action that changes the source.
        Component.onCompleted: loader.source = "MyRectangle.qml"
    }
    

    MyRectangle.qml:

    import QtQuick 2.0
    
    Rectangle {
        id: rect
        color: "red"
        width: 150
        height: 150
    }
    

    【讨论】:

    • 谢谢。这行得通,虽然它不像我想象的那么好。将动画添加到加载器组件并不是一种巧妙的方法。它有时运行得更快,有时运行得更慢,而且延迟很烦人!还是谢谢。
    • 您可以尝试将onSourceChanged 更改为onStatusChanged 并且仅在statusLoader.Ready 时才开始动画?如果没有代码来重现缓慢,很难提供更多建议。您可以粘贴由Loader 加载的项目的简化(但仍然“重”)版本,以便我可以尝试一下。
    【解决方案2】:

    必须使用Loader吗?

    如果不是,您可以使用 StackView(当然,如果您不想提供更复杂的导航,深度为 1)并通过使用 @987654323 将组件推送到堆栈来加载组件@ 选项设置为 true。

    也就是说,您可以获得您要求的结果如下:

    StackView {
        delegate: StackViewDelegate {
            function transitionFinished(properties) {
                properties.exitItem.x = 0
            }
    
            pushTransition: StackViewTransition {
                PropertyAnimation {
                    target: enterItem
                    property: "x"
                    from: enterItem.width
                    to: 0
                }
    
                PropertyAnimation {
                    target: exitItem
                    property: "x"
                    from: 0
                    to: -exitItem.width
                }
            }
        }
    }
    

    如果它不能按原样工作(即使它应该),我深表歉意,但我在手机上,我现在无法测试它。

    【讨论】:

    • 我不能使用这个替代方案。我使用 Loader 组件创建了一个自定义选项卡视图。在我的情况下无法使用堆栈视图,因为我只需要更改选项卡内容而不是整个页面。毕竟它对喜欢堆栈视图的人很有用。谢谢你的回答。
    • @a.toraby 就算我迟到了,干脆不要让 StackView 成为根元素!
    • @skypjack StackView 不是异步的
    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多