目录
QML对象声明
QML对象特性一般使用下面的顺序进行构造:
- id
- 属性声明
- 信号声明
- JavaScript函数
- 对象属性
- 子对象
- 状态
- 状态切换
为了获取更好的可读性,建议在不同部分之间添加一个空行。例如,下面使用一个Photo对象作为示例:
Rectangle {
id: photo // id放在第一行,便于找到一个对象
property bool thumbnail: false //属性声明
property alias image: photoImage.source
signal clicked // 信号声明
function doSomething(x) // javascript 函数
{
return x + photoImage.width
}
color: "gray" // 对象属性
x: 20; y: 20; height: 150 // 相关属性放在一起
width: { // 绑定
if (photoImage.width > 200) {
photoImage.width;
} else {
200;
}
}
Rectangle { // 子对象
id: border
anchors.centerIn: parent; color: "white"
Image { id: photoImage; anchors.centerIn: parent }
}
states: State { // 状态
name: "selected"
PropertyChanges { target: border; color: "red" }
}
transitions: Transition { //过渡
from: ""; to: "selected"
ColorAnimation { target: border; duration: 200 }
}
}
属性组
如果使用了一组属性中的多个属性,那么使用组表示法,而不要使用点表示法,这样可以提高可读性。例如:
Rectangle {
anchors.left: parent.left; anchors.top: parent.top;
anchors.right: parent.right; anchors.leftMargin: 20
}
Text {
text: "hello"
font.bold: true; font.italic: true; font.pixelSize: 20;
font.capitalization: Font.AllUppercase
}
可以写成这样:
Rectangle {
anchors { left: parent.left; top: parent.top; right: parent.right; leftMargin: 20 }
}
Text {
text: "hello"
font { bold: true; italic: true; pixelSize: 20; capitalization: Font.AllUppercase }
}
列表
如果一个列表只包含一个元素,那么我们通常忽略方括号。例如下面的代码:
states: [
State {
name: "open"
PropertyChanges { target: container; width: 200 }
}
]
可以写成:
states: State {
name: "open"
PropertyChanges { target: container; width: 200 }
}
JavaScript代码
如果脚本是一个单独的表达式,建议直接使用:
Rectangle { color: "blue"; width: parent.width / 3 }
如果脚本只有几行,那么建议写成一块:
Rectangle {
color: "blue"
width: {
var w = parent.width / 3
console.debug(w)
return w
}
}
如果脚本有很多行,或者需要被不同的对象使用,那么建议创建一个函数,然后像下面这样来调用它:
function calculateWidth(object)
{
var w = object.width / 3
// ...
// more javascript code
// ...
console.debug(w)
return w
}
Rectangle { color: "blue"; width: calculateWidth(parent) }
如果是很长的脚本,我们可以将这个函数放在独立的 JavaScript 文件中,然后像下面这样来导入它:
import "myscript.js" as Script
Rectangle { color: "blue"; width: Script.calculateWidth(parent) }
如果代码超过一行,因此在块中,我们使用分号来指示每个语句的末尾:
MouseArea {
anchors.fill: parent
onClicked: {
var scenePos = mapToItem(null, mouseX, mouseY);
console.log("MouseArea was clicked at scene pos " + scenePos);
}
}