Qt 5.9 QML 编码规范
目录:
- QML对象声明
- 分组特性
- 列表
- JavaScript代码
QML对象声明
纵观我们的文档以及例子,QML对象属性用以下的顺序进行构造:
- id
- 属性声明
- 信号声明
- javaScript函数
- 对象属性
- 子对象
- 状态
- 转换
为了更好的阅读体验,我们通过使用空格来分开这些不同的部分。
例如,一个假定的图片QML对象就像是这样:
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);
}
}