通过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.
下面是例子代码:

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模型中很像了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值