有兩種方法可以創建,都是全局對象Qt提供的方法
一:用Qt.createComponent加載一個qml文件並創建Component
二:用Qt.createQmlObject從一個qml字符串創建Component
注意,以上兩種方法返回的是Component,Component在QML中是一種類型,參考文檔:
http://qt-project.org/doc/qt-5/qml-qtqml-component.html#details
因此還要調用Component的createObject來創建真正可用的對象。createObject第一個參數是指定掛在誰的下方,也就是父窗口是誰。如果傳遞null,則代表暫時不顯示。
如果要銷毀,只需要調用對象的destroy方法即可。
調用createObject方法需要注意qml文件已經被加載完成才行,因為這種機制允許遠程加載qml文件,所以需要檢查Component的status屬性:
This property holds the status of component loading. The status can be one of the following:
Component.Null - no data is available for the component
Component.Ready - the component has been loaded, and can be used to create instances.
Component.Loading - the component is currently being loaded
Component.Error - an error occurred while loading the component. Calling errorString() will provide a human-readable description of any errors.
This property holds the status of component loading. The status can be one of the following:
Component.Null - no data is available
for
the component
Component.Ready - the component has been loaded, and can be used to create instances.
Component.Loading - the component is currently being loaded
Component.Error - an error occurred
while
loading the component. Calling errorString() will provide a human-readable description of any errors.
下面是例子代碼:
function createItem() {
if (itemComponent.status == Component.Ready && draggedItem == null) {
draggedItem = itemComponent.createObject(
window,
{
"image": paletteItem.image,
"x": posnInWindow.x,
"y": posnInWindow.y,
"z": 3
}
);
// make sure created item is above the ground layer
} else if (itemComponent.status == Component.Error) {
draggedItem = null;
console.log("error creating component");
console.log(itemComponent.errorString());
}
}
注意在JavaScript中沒有真正的類型,類型也是由對象模擬的。所以Qml 的Component在JavaScript代碼中也表現為一個對象,比如上面代碼的itemComponent就是Qml的Component,但也是一個對象。用它的createObject再創建真正可用的對象掛在window對象下面。
官方文檔參考:
http://qt-project.org/doc/qt-4.8/qdeclarativedynamicobjects.html
http://qt-project.org/doc/qt-5/qml-qtqml-qt.html#createComponent-method
http://qt-project.org/doc/qt-5/qml-qtqml-qt.html#createQmlObject-method
這就和web開發用JavaScript動態創建HTML的tag並插入到DOM模型中很像了。