Qt6 QML Book/JavaScript/JS对象

JS Objects

JS对象

While working with JS there are some objects and methods which are more frequently used. This is a small collection of them.

在使用JS时,有一些更常用的对象和方法。这是它们的一小部分。

  • Math.floor(v)Math.ceil(v)Math.round(v) - largest, smallest, rounded integer from float

  • Math.floor(v)Math.ceil(v)Math.round(v) - 浮点中的最大、最小、四舍五入整数

  • Math.random() - create a random number between 0 and 1

  • Math.random() - 创建一个介于0和1之间的随机数

  • Object.keys(o) - get keys from object (including QObject)

  • Object.keys(o) - 从对象(包括QObject)获取键值对

  • JSON.parse(s)JSON.stringify(o) - conversion between JS object and JSON string

  • JSON.parse(s)JSON.stringify(o) - JS对象和JSON字符串之间的转换

  • Number.toFixed(p) - fixed precision float

  • Number.toFixed(p) - 固定精度浮点数

  • Date - Date manipulation

  • Date - 日期处理

You can find them also at: JavaScript reference

​您也可以在以下网址找到它们:JavaScript reference

Here some small and limited examples of how to use JS with QML. They should give you an idea how you can use JS inside QML

下面是一些关于如何将JS与QML结合使用的小而有限的示例。他们应该让你知道如何在QML中使用JS

打印QML项中的所有键值对

Item {
    id: root
    Component.onCompleted: {
        var keys = Object.keys(root);
        for(var i=0; i<keys.length; i++) {
            var key = keys[i];
            // prints all properties, signals, functions from object
            console.log(key + ' : ' + root[key]);
        }
    }
}

Parse an object to a JSON string and back

将对象解析为JSON字符串并返回

Item {
    property var obj: {
        "key": 'value'
    }

    Component.onCompleted: {
        var data = JSON.stringify(obj);
        console.log(data);
        var obj = JSON.parse(data);
        console.log(obj.key); // > 'value'
    }
}

Current Date

当前日期

Item {
    Timer {
        id: timeUpdater
        interval: 100
        running: true
        repeat: true
        onTriggered: {
            var d = new Date();
            console.log(d.getSeconds());
        }
    }
}

Call a function by name

按名称调用函数

Item {
    id: root

    function doIt() {
        console.log("doIt()")
    }

    Component.onCompleted: {
        // Call using function execution
        root["doIt"]();
        var fn = root["doIt"];
        // Call using JS call method (could pass in a custom this object and arguments)
        fn.call()
    }
}

示例源码下载 ​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值