上节介绍了Component的概念,本节介绍一下如何使用javascript动态创建对象。
1. 创建工程,新建一个MyComponent.qml的qml
import QtQuick
Rectangle {
    color: "red"
}
它很简单就是一个红色框
2. 编辑main.qml
import QtQuick
Window {
    id: root
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    property var myObject : null
    MouseArea {
        anchors.fill: parent
        onClicked: {
            if (null === myObject)
                createObject(100, 50, 100, 100)
            else
                destoryObject()
        }
    }
    function createObject(x, y, width, height) {
        var component = Qt.createComponent("MyComponent.qml");
         if (component.status === Component.Ready) {
             myObject = component.createObject(root, {x: x, y: y, width: width, height: height});
         }
    }
    function destoryObject(){
        myObject.destroy()
    }
}- 定义了两个javascript方法【createObject】和【destoryObject】并在点击鼠标时调用这两个方法
- 定义了一个myObject的属性用来接收创建出来的对象
- 在【createObject】方法中,首先使用【Qt.createComponent】创建一个Component对象,然后再用创建出来的Component对象创建Object。
- 在【destoryObject】方法中调用对象的【destroy】方法销毁对象
3. 运行程序
连续点击鼠标红框会出现和消失




















