本文翻譯自: 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君。