QML语法

发布时间 2023-12-18 16:43:15作者: 飞说晓事

一,基本语法

1、import导入需要使用的模块。类似于C++,include。

2、一个QML文件只能有一个根元素。类似一个QML文件就是自然界的一棵树。

3、元素声明方法:类型{ }

4、元素下定义属性,属性赋值方法: name:value

5、元素可并行,也可嵌套。子元素可用通过父元素id访问它的子元素和属性。

6、一个QML文件下的元素可通过元素的id访问。

7、注释使用//或者/*     */。

二、属性

1、一个属性可用设置一个值,也可用设置与其他属性关联。id为特殊属性,不被设置其他值。

2、自定义属性需要使⽤property修饰符。方法:property    类型    名字:值

3、每个元素都可以提供⼀个属性变化信号操作。方法:on属性名Changed

4、alias关键字允许转发⼀个属性到另⼀个 作⽤域。方法:property alias :

Text {
     // (1) id为特殊属性,不能设置其他值
     id: thisLabel
     // (2) 赋值x,y,设置位置
     x: 24; y: 16
     // (3) 设置height与width属性关联
     height: 2 * width
     // (4) 自定义属性
     property int times: 24
     // (5) property alias使用方法
     property alias anotherTimes: thisLabel.times
     // (6) 设置text属性为times关联
     text: "Greetings " + times
     // (7) 赋值组属性,也可用直接font{family: "UBuntu"; pixelSize: 24}
     font.family: "Ubuntu"
     font.pixelSize: 24
     // (8) KeyNavigation is an attached property
     KeyNavigation.tab: otherLabel
     // (9) 属性值发送改变时信号处理
     onHeightChanged: console.log('height:', height)
     // focus is need to receive key events
     focus: true
     // change color based on focus value
     color: focus?"red":"black"
}

 三、脚本

1、QML与JavaScript是最好的配合。

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) JavaScript函数
  function increment() {
    spacePresses = spacePresses + 1
  }
}