本文翻译自: https://doc.qt.io/qt-5/qml-codingconventions.html
原作者: Qt官网
本文档包含我们在文档和示例中应该遵循的QML编码约定,并建议其他人也遵循。
0x01 QML对象声明
在整个文档和示例中,QML对象属性始终按以下顺序构造:
- id
- property declarations(自定义属性声明)
- signal declarations(信号声明)
- JavaScript function(js函数)
- object properties(对象属性)
- child object(子对象)
- states(状态机)
- transitions(过渡效果)
为了提高可读性,我们用空行将这些不同的部分分开。
例如,photo的QML对象如下所示:
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 } } }
0x02 分组属性
如果使用一组属性中的多个属性,请考虑使用组符号代替点符号,以提高可读性。
例如:
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 } }
0x03 列表
如果列表对象仅包含一个元素,则通常会省略方括号。例如,一个组件仅具有一个状态是很常见的。在这种情况下,如果这样写:
states: [ State { name: "open" PropertyChanges { target: container; width: 200 } } ]
但这样写更合适:
states: State { name: "open" PropertyChanges { target: container; width: 200 } }
0x04 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); } }
更多精彩内容请关注公众号Qt君。
来源:https://www.cnblogs.com/qthub/p/12207759.html