通过JavaScript创建Qml对象

有两种方法可以创建,都是全局对象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模型中很像了。

posted @ 2014-09-22 10:38  ZN大叔  阅读(4039)  评论(0编辑  收藏  举报