QML Code Style
基本原则
better readability = 易读就能减少错误
对象属性的排列顺序
-
id
-
property declarations
-
signal declarations
-
JavaScript functions
-
object properties
-
x、y
-
width、height
-
anchors
-
other properties
-
states
-
transitions
-
Binding
-
property changed signal
-
MouseArea
-
-
child properties
-
visual items
- Item Rectangle …
-
Qt provided non-visual items
-
Timer
-
Connections
-
-
custom provided non-visual items
- MyCppObject
-
-
QtObject
-
Component.onCompleted
示例
import QtQuick 2.0
Rectangle {
// id
id: photo
// property declarations
property bool thumbnail: false
property alias image: photoImage.source
// signal declarations
signal clicked
// JavaScript functions
function doSomething(x) {
return x + photoImage.width
}
// object properties
x: 20
y: 20
width: {
if (photoImage.width > 200) {
photoImage.width
} else {
200
}
}
height: 150
// anchors.fill: parent
color: "gray" // other properties
// states
states: [
State {
name: "selected"
PropertyChanges {
target: border
color: "red"
}
}
]
// transitions
transitions: [
Transition {
from: ""
to: "selected"
ColorAnimation {
target: border
duration: 200
}
}
]
// Binding
// Binding on value {
// when: mouse.pressed
// value: mouse.mouseX
// }
// MouseArea
MouseArea {
id: rootArea
}
// child objects
// visual items
Rectangle {
id: border
anchors.centerIn: parent
color: "white"
Image {
id: photoImage
anchors.centerIn: parent
}
}
Text {
id: time
text: attributes.name
}
// Timer
Timer {
interval: 500
running: true
repeat: true
onTriggered: time.text = Date().toString()
}
// Connections
Connections {
target: rootArea
function onClicked(mouse) {
foo(mouse)
}
}
// custom provided non-visual items
// MyQmlType {
// id: customType
// }
// QtObject: 可以通过 objectName 传递给 C++,但不建议这么做!
QtObject {
id: attributes
objectName: "myObject"
property string name
property int size
property variant attributes
}
// Component.onCompleted
Component.onCompleted: {
width = 640
height = 480
}
}
Note
-
以上风格只是参考,特殊情况另外考虑
-
QML 中对象的构建顺序为:由外到内、由底向上,例如示例中顺序为:photo、time、border,由此实际开发中可能需要调整相关顺序
-
相关属性应该写在一起
Text { text: "hello" font { bold: true; italic: true; pixelSize: 20; capitalization: Font.AllUppercase } // Grouped Properties } -
自定义属性时应该考虑到类型安全(Type Safety)
// Bad property var name property var size property var optionsMenu // Good property string name property int size property MyMenu optionsMenu
参考
https://github.com/Furkanzmc/QML-Coding-Guide
本文介绍了QML代码风格的基本原则,包括对象属性的排列顺序,如先声明id、属性、信号,再到JavaScript函数等。提供了示例并强调了可读性的重要性。注意,QML对象构建顺序通常为从外到内,从底向上,并提示开发者在实际开发中可能需要根据情况调整顺序,同时提倡自定义属性时考虑类型安全。
716

被折叠的 条评论
为什么被折叠?



