Qt之QML编码约定
生活随笔
收集整理的這篇文章主要介紹了
Qt之QML编码约定
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 概述
- QML對象聲明
- 分組屬性
- 列表
- JavaScript代碼
概述
之前看到一篇Qt 官方的關于QML 開發的編碼約定,這里做個簡單的總結。一個良好的編碼習慣可提高代碼的可閱讀性,并且整個代碼結構會非常清晰,也利于自己進行代碼調試。那么,接下來看看官方推薦使用的 有哪些QML 編碼規范。
QML對象聲明
在 QML 的代碼結構中,對象屬性的聲明順序通常是:
- id
- property declarations
- signal declarations
- JavaScript functions
- object properties
- child objects
- states
- transitions
為了更好的可閱讀性,通常用空行來分隔這些不同部分。
下面來看一個示例:
分組屬性
如果使用一組屬性中的多個屬性,如果它提高了可讀性,請考慮使用組標記而不是點標記。
例如:
Rectangle {anchors.left: left: parent.left; anchors.top: top: parent.top; anchors.right: right: parent.right; anchors.leftMargin: leftMargin: 20 }Text {text: "hello"font.bold: bold: true; font.italic: italic: true; font.pixelSize: pixelSize: 20; font.capitalization: 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 } }JavaScript代碼
如果腳本是單個表達式,建議將它內聯編寫:
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);} }參考地址:http://doc.qt.io/qt-5/qml-codingconventions.html
總結
以上是生活随笔為你收集整理的Qt之QML编码约定的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt 设置应用程序图标
- 下一篇: Qt QML实现阴影字体