1. QML 类型系统
QML 中支持的类型大概有三类,语言支持的基本类型、QtQuick模块扩展的类型、Js内置的类型
1.1 QML语言支持的基本类型列表
bool布尔double双精度小数enumeration枚举int整数listQML对象列表real小数string字符串url资源定位器var通用属性类型,Js中类型。可查看Js的详细说明
1.2 QtQuick模块支持的类型
QML模块可以使用更基本的类型扩展QML语言。
例如,下面是QtQuick模块提供的基本类型:
date日期point有x,y属性的对象rect有x,y,width,height属性的对象size有width,height属性的对象
Qt 全局对象(https://doc.qt.io/qt-5/qml-qtqml-qt.html)提供了用于操作基本类型值的有用函数。Qt全局对象是必须要了解的类,后续会详细说明。支持应用退出、语言、翻译、应用属性、获取操作系统平台等接口。更多的是提供对象构造方法。比如:
import QtQuick 2.0
Text {
color: Qt.rgba(1, 0, 0, 1)
text: Qt.md5("hello, world")
}
目前只有Qt提供的QML模块可以定义基本类型,但是在Qt QML的未来版本中可能会发生变化。为了使用特定 QML 模块提供的类型,客户端必须在其 QML 文档中导入该模块。
1.3 JavaScript 类型
JavaScript 对象和数组受 QML 引擎支持。任何标准的JavaScript类型都可以使用泛型var类型创建和存储。
例如,标准Date和Array类型可用,如下所示:
import QtQuick 2.0
Item {
property var theArray: []
property var theDate: new Date()
Component.onCompleted: {
for (var i = 0; i < 10; i++)
theArray.push("Item " + i)
console.log("There are", theArray.length, "items in the array")
console.log("The time is", theDate.toUTCString())
}
}
泛型var,是可以引用任何数据类型的泛型属性类型,它等效于常规的 JavaScript 变量。例如,var 属性可以存储数字、字符串、对象、数组和函数:
Item {
property var aNumber: 100
property var aBool: false
property var aString: "Hello world!"
property var anotherString: String("#FF008800")
property var aColor: Qt.rgba(0.2, 0.3, 0.4, 0.5)
property var aRect: Qt.rect(10, 10, 10, 10)
property var aPoint: Qt.point(10, 10)
property var aSize: Qt.size(10, 10)
property var aVector3d: Qt.vector3d(100, 100, 100)
property var anArray: [1, 2, 3, "four", "five", (function() { return "six"; })]
property var anObject: { "foo": 10, "bar": 20 }
property var aFunction: (function() { return "one"; })
}