https://blog.csdn.net/cloud_castle/article/details/28685075
http://doc.qt.io/qt-5/qml-codingconventions.html
每一种语言都需要规范,首先是规范的写法可以避免一些不必要的错误,另外方便与其它的代码兼容,也方便其他人理解,规范比标准第一个层次,但是遵守规范,可以让自己受益无穷
- 对象声明(QML Object Declarations)
QML对象属性总是以以下结构层次组织起来
id
property declarations
signal declarations
JavaScript functions
object properties
child objects
states
transitions
我们看看它的一个例子
Rectangle {
id: photo // id on the first line makes it easy to find an object
property bool thumbnail: false // property declarations
property alias image: photoImage.source
signal clicked // signal declarations
function doSomething(x) // javascript functions
{
return x + photoImage.width
}
color: "gray" // object properties
x: 20 // try to group related properties together
y: 20
height: 150
width: { // large bindings
if (photoImage.width > 200) {
photoImage.width;
} else {
200;
}
}
Rectangle { // child objects
id: border
anchors.centerIn: parent; color: "white"
Image {
id: photoImage
anchors.centerIn: parent
}
}
states: State { // states
name: "selected"
PropertyChanges { target: border; color: "red" }
}
transitions: Transition { // transitions
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 }
}
如果脚本有多行并且被多个不同对象所使用,考虑到代码的重复性,我们必须把它创建为function
function calculateWidth(object)
{
var w = object.width / 3
// ...
// more javascript code
// ...
console.debug(w)
return w
}
Rectangle { color: "blue"; width: calculateWidth(parent) }
对于很长的脚本,我们将这些functions放在一个单独的JavaScript文件中并像这样进行引入:
import "myscript.js" as Script
Rectangle { color: "blue"; width: Script.calculateWidth(parent) }