QML被用来设计用户界面,而HTML被用来设计文本文档。
一个典型的QML代码:
import QtQuick 2.0
// The root element is the Rectangle
Rectangle {
// name this element root
id: root
// properties: <name>: <value>
width: 120; height: 240
// color property
color: "#D8D8D8"
// Declare a nested element (child of root)
Image {
id: rocket
// reference the parent
x: (parent.width - width)/2; y: 40
source: 'assets/rocket.png'
}
// Another child of root
Text {
// un-named element
// reference element by id
y: rocket.y + rocket.height + 20
// reference root element
width: root.width
horizontalAlignment: Text.AlignHCenter
text: 'Rocket'
}
}
属性
Text {
// (1) identifier:类似于身份证号,唯一标识。
id: thisLabel
// (2) set x- and y-position:属性能赋的值依赖于类型,没有赋值,则采用默认值。
x: 24; y: 16
// (3) bind height to 2 * width:属性绑定
height: 2 * width
// (4) custom property:自己定义的属性需加上property修饰符、类型、名称、值
property int times: 24
// (5) property alias:转发一个属性或者转发一个属性对象自身到另一个作用域,类似于c++中的别名&
property alias anotherTimes: thisLabel.times
// (6) set text appended by value
text: "Greetings " + times//times每次改变的时候刷新text
// (7) font is a grouped property:需要匹配起来一起定义
font.family: "Ubuntu"
font.pixelSize: 24
// (8) KeyNavigation is an attached property:元素自身的附加属性
KeyNavigation.tab: otherLabel
// (9) signal handler for property changes
onHeightChanged: console.log('height:', height)//高度改变的时候输出控制台信息
// focus is neeed to receive key events
focus: true
// change color based on focus value
color: focus?"red":"black"
}
脚本
QML+JS=PERFECT
Text {
id: label
x: 24; y: 24
// custom counter property for space presses
property int spacePresses: 0
text: "Space pressed: " + spacePresses + " times"
// (1) handler for text changes
onTextChanged: console.log("text changed to:", text)
// need focus to receive key events
focus: true
// (2) handler with some JS
Keys.onSpacePressed: {
increment()
}
// clear the text on escape
Keys.onEscapePressed: {
label.text = ''
}
// (3) a JS function
function increment() {
spacePresses = spacePresses + 1
}
}
QML中:为绑定,而JS中=为赋值。也就是绑定一直存在于生存周期内,而赋值只是一次性的。