qml使用Loader动态创建和删除组件

qml使用Loader动态创建和删除组件

//SubComponent.qml
import QtQuick 2.12

Rectangle {
    id: subRect
    color: "red"
    width: 200
    height: 100
    property string strText

    Text {
        id: name
        text: strText
        color: "white"
        anchors.centerIn: parent
    }

    Component.onCompleted: {
        console.log("SubComponent===========Component.onCompleted=====")
    }

    Component.onDestruction: {
        console.log("SubComponent===========Component.onDestruction=====")
    }
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

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

    Loader {
        id: loadSubComponent
        anchors.top: parent.top
        anchors.topMargin: 100
        anchors.left: parent.left
        anchors.leftMargin: 50

        onLoaded: {
            if(item != null){
                item.color = "blue"
                item.strText = "Loader"
            }
        }

        onFocusChanged: {
            if(item != null) {
                item.focus = focus
            }
        }
    }


    Row {
        spacing: 5

        anchors.fill: parent
        Button {
            text: qsTr("add")
            onClicked: {
                console.log("============SubComponent.qml=========")
                loadSubComponent.source = "qrc:/SubComponent.qml"
                loadSubComponent.item.color = "green"
                loadSubComponent.item.strText = "Hello"
            }
        }
        Button {
            text: qsTr("delete")
            onClicked: {
                console.log("=============delete Component================")
                loadSubComponent.sourceComponent = undefined
                loadSubComponent.source = ""
            }
        }
    }
}

你可能感兴趣的:(qml,qml,Loader)