简述

为了风格统一、代码规范,QML 提供了一套编码约定,在 QML 的参考文档和示例中均遵循此规则,建议大家以后编写 QML 时也同样遵循。

| 版权声明:一去、二三里,未经博主允许不得转载。

QML 对象声明

在整个文档和示例中,QML 对象属性总按照以下顺序结构化:

  • id
  • 属性声明
  • 信号声明
  • JavaScript 函数
  • 对象属性
  • 子对象
  • 状态
  • 过渡

为了更好的可读性,我们用空行将他们分隔为不同的部分。

例如,假如有一个 QML 对象 photo,如下所示:

Rectangle {
id: photo // id 放到第一行,便于查找对象

property bool thumbnail: false // 属性声明
property alias image: photoImage.source

signal clicked // 信号声明

function doSomething(x) // javascript 函数
{
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.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" italic: true; pixelSize: 20; capitalization: Font.AllUppercase }
}

列表

如果列表只包含一个元素,我们通常会省略方括号。

例如,组件只有一个状态是非常常见的。

在这种情况下,我们不应该这样写:

states: [
State {
name: "open" width: 200

而应该这样:

states: State {
name:"open"; width:200}
}

JavaScript 代码

如果脚本是单个表达式,建议将其写为内联的形式:

Rectangle { color:"blue"; width:3}

如果脚本只有几行,通常使用一个代码块:

Rectangle {
color:"blue"
width: {
var w = parent.width / 3
console.debug(w)}
}

如果脚本多于几行,或者需要被不同的对象使用,建议创建一个函数并像下面这样调用它:

function calculateWidth(object)
{
var w = object.width / 3
// ...
// 更多的 javascript 代码
// ...
console.debug(w)
return w
}

Rectangle { color: "blue"; width: calculateWidth(parent) }

对于是很长的脚本,建议将函数放在自己的 JavaScript 文件中,并像下面这样导入它:

import "myscript.js" as Script

Rectangle { color:"blue"; width:calculateWidth(parent)}

如果代码长度超过一行,并因此在一个代码块内,使用分号来表示每个语句的结尾:

MouseArea {
anchors.fill: parent
onClicked: {
var scenePos = mapToItem(null, mouseX, mouseY);
console.log("MouseArea was clicked at scene pos " +