zoukankan      html  css  js  c++  java
  • QML调用JS

    一、使用JS文件中的函数

    1、新建js文件nomal_fun.js

    function getColor(){
        return "red";
    }

    2、在qml中使用

    import QtQuick 2.0
    import "nomal_fun.js" as Balls
    Rectangle{
        width: 600
        height: 480
        color: "gray"
        Rectangle {
             100
            height: 100
            anchors.centerIn: parent
            Component.onCompleted: {
               color = Balls.getColor()
            }
        }
    }

     注意:这里并没有将js文件加入到工程的资源中,而是直接通过文件访问的。

    二、在js中动态创建自定义qml对象

    1、dynamic-image.qml.js

    // M1>>
    var component;
    
    function createImageObject() {
        component = Qt.createComponent("dynamic-image.qml");
        if (component.status === Component.Ready || component.status === Component.Error) {
            finishCreation();
        } else {
            component.statusChanged.connect(finishCreation);
        }
    }
    
    function finishCreation() {
        if (component.status === Component.Ready) {
            var image = component.createObject(root, {"x": 100, "y": 100});
            if (image === null) {
                console.log("Error creating image");
            }
        } else if (component.status === Component.Error) {
            console.log("Error loading component:", component.errorString());
        }
    }
    
    // <<M1

    dynamic-image.qml是自定义的qml

    2、使用

    import QtQuick 2.5
    import "create-component.js" as ImageCreator
    
    Item {
        id: root
    
         1024
        height: 600
    
        Component.onCompleted: ImageCreator.createImageObject();
    }

    三、传回调进入js

    1、在qml里定义函数

    function print(info) {
        console.log(info);
    }

    2、定义js文件

    A.js

    function test(info, callback)
    {
        callback(info);
    }

    3、qml中使用

    import "A.js" as AObject
    
    Item {
        id: root
    
        function addUfo() {
            AObject.test("123", print);
        }
    
        function print(info) {
            console.log(info);
        }
    }

    和C++一致

    四、stateful/statelss

    如希望某个js是单例的,只需要在js文件开头加入:

    .pragma library

    注意这种形式类似于共享,它不可以直接访问QML文件中的object尽管可以通过参数的传人对所要求的object进行修改;

    stateful:【不加.pragma library,默认情况】

    如果在js中定义一个var count=0;那么每import一次这个js,就会有独立的count;默认是有状态【stateful】的,js文件可以直接访问在我们QML文件中所定义的object。

    statelss:【加.pragma library】

    count是静态的;函数里无法在里面访问id,只能将id作为参数传进去才能访问;

    官方说明:https://doc.qt.io/qt-5/qtqml-javascript-resources.html

  • 相关阅读:
    node连接mysql数据库
    mysql重置密码
    CSS vertical-align 属性
    JS中常用的字符串方法
    JS中的常用数组方法
    获取下拉菜单中具有SELECTED属性元素的序号和值的方法
    基本的正则表达式符号
    让多个文本输入框左侧对齐方法
    CSS选择器权重对比
    让内联元素支持宽高的几个设置
  • 原文地址:https://www.cnblogs.com/judes/p/15672337.html
Copyright © 2011-2022 走看看