zoukankan      html  css  js  c++  java
  • 通过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模型中很像了。

  • 相关阅读:
    [翻译]关于堆和堆栈
    sql 字符+数值 混合排序 lcs
    证明DataReader分页的可行性 lcs
    谈谈我对小公司、大公司及个人成长的见解 lcs
    sina 通用js代码说明 lcs
    Linux系统下生成证书 https证书
    【转】51单片机外部中断的C51编程
    【转】如何建立个人网站
    【转】关于C51的中断编程[原创]
    【转】毫不费力:破解加密PDF文档就使用这两三招
  • 原文地址:https://www.cnblogs.com/aoldman/p/3985562.html
Copyright © 2011-2022 走看看