这个笔记就是记录一下Qt 官方在示例代码和文档中遵循的QML编码约定,我很多时候的开发的时候也是遵循这个原则,方便后面调试程序,也方便后期维护程序。
QML对象属性的结构顺序如下:
为了更好的可读性,我们用空行分隔这些不同的部分。
例如,一个假设的photo QML对象看起来像这样:
Rectangle {id: photo // id on the first line makes it easy to find an objectproperty bool thumbnail: false // property declarationsproperty alias image: photoImage.sourcesignal clicked // signal declarationsfunction doSomething(x) // javascript functions{return x + photoImage.width}color: "gray" // object propertiesx: 20 // try to group related properties togethery: 20height: 150width: { // large bindingsif (photoImage.width > 200) {photoImage.width;} else {200;}}Rectangle { // child objectsid: borderanchors.centerIn: parent; color: "white"Image {id: photoImageanchors.centerIn: parent}}states: State { // statesname: "selected"PropertyChanges { target: border; color: "red" }}transitions: Transition { // transitionsfrom: ""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 }
}
如果脚本是一个表达式,我们建议将其内联编写:
Rectangle { color: "blue"; width: parent.width / 3 }
如果脚本只有几行,我们通常使用一个块:
Rectangle {color: "blue"width: {var w = parent.width / 3console.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 ScriptRectangle { color: "blue"; width: Script.calculateWidth(parent) }
如果代码超过一行,并且在一个块中,我们使用分号表示每个语句的结束:
MouseArea {anchors.fill: parentonClicked: {var scenePos = mapToItem(null, mouseX, mouseY);console.log("MouseArea was clicked at scene pos " + scenePos);}
}