标签:
在这篇文章中,我们将介绍如何使用Loader来加载不同的QML文件来实现动态的UI。在之前的文章“如何使用Loader来动态载入一个基于item的Component”中,我们已经介绍了一些关于它的用法。Loader的好处是只有在我们需要的时候才装载我们所需要的QML文件,这样可以节省应用所需要的内存,也同时可以提高应用的启动时间(如果利用好的话)。下面我们以一个简单的例子来做一个介绍。更多关于动态生产QML UI的例子,请参阅“如何使用QML动态产生Component来完成我们的气球游戏(2)”。
import QtQuick 2.0
Rectangle {
    id: root
    
    width: 600
    height: 400
    
    property int speed: 0
    
    SequentialAnimation {
        running: true
        loops: Animation.Infinite
        
        NumberAnimation { target: root; property: "speed"; to: 145; easing.type: Easing.InOutQuad; duration: 4000; }
        NumberAnimation { target: root; property: "speed"; to: 10; easing.type: Easing.InOutQuad; duration: 2000; }
    }
    // M1>>
    Loader {
        id: dialLoader
        
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: analogButton.top
        onLoaded: {
            binder.target = dialLoader.item;
        }
    }
    Binding {
        id: binder
        
        property: "speed"
        value: speed
    }
    // <<M1
    Rectangle {
        id: analogButton
        
        anchors.left: parent.left
        anchors.bottom: parent.bottom
        
        color: "gray"
        
        width: parent.width/2
        height: 100
        
        Text {
            anchors.centerIn: parent
            text: "Analog"
        }
        
        MouseArea {
            anchors.fill: parent
            onClicked: root.state = "analog";
        }
    }
    
    Rectangle {
        id: digitalButton
        
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        
        color: "gray"
        
        width: parent.width/2
        height: 100
        
        Text {
            anchors.centerIn: parent
            text: "Digital"
        }
        
        MouseArea {
            anchors.fill: parent
            onClicked: root.state = "digital";
        }
    }
    
    state: "analog"
    
    // M3>>
    states: [
        State {
            name: "analog"
            PropertyChanges { target: analogButton; color: "green"; }
            PropertyChanges { target: dialLoader; source: "Analog.qml"; }
        },
        State {
            name: "digital"
            PropertyChanges { target: digitalButton; color: "green"; }
            PropertyChanges { target: dialLoader; source: "Digital.qml"; }
        }
    ]
    // <<M3
}
   Loader {
        id: dialLoader
        
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: analogButton.top
        onLoaded: {
            binder.target = dialLoader.item;
        }
    }版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/ubuntutouch/article/details/47002151