本文翻译自: https://doc.qt.io/qt-5/qml-co...
原做者: Qt官网
本文档包含咱们在文档和示例中应该遵循的QML编码约定,并建议其余人也遵循。javascript
在整个文档和示例中,QML对象属性始终按如下顺序构造:html
为了提升可读性,咱们用空行将这些不一样的部分分开。 java
例如,photo的QML对象以下所示:api
Rectangle { id: photo // 第一行的id使查找对象变得很容易 property bool thumbnail: false // 自定义属性声明 property alias image: photoImage.source signal clicked // 信号声明 function doSomething(x) // js函数 { 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 } }
若是列表对象仅包含一个元素,则一般会省略方括号。例如,一个组件仅具备一个状态是很常见的。在这种状况下,若是这样写:debug
states: [ State { name: "open" PropertyChanges { target: container; width: 200 } } ]
但这样写更合适:code
states: State { name: "open" PropertyChanges { target: container; width: 200 } }
若是脚本是单个表达式,则建议内联编写:htm
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); } }
更多精彩内容请关注公众号Qt君。