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
Print all keys from QML Item
打印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()
}
}
示例源码下载