QML6(Qt Quick)
基本语法
QML
是一种用于描述对象如何相互关联的声明式语言QtQuick
是一种基于QML
的框架
简单示例
1 | import QtQuick /*导入模块,qt6可以不写版本号,自动加载最高版本的模块*/ |
- 每个
QML
文件都需要一个唯一的根元素 QML
文档中的任意元素可以通过使用其id
进行访问- 元素可以嵌套,子元素可以使用
parent
关键字访问父元素 - 可以使用
property
限定符向元素添加新属性, 例如property int times:24
- 使用别名关键字 `property alias + 名称 : 引用
grouped property
`font{family:”Ubuntu”;pixelSize:24}
核心元素类型
Rectangle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15//自定义渐变色
Rectangle{
id:rect3
x:250; y:10
width:76; height:96
gradient: Gradient{
GradientStop{position:0; color:'red'}
GradientStop{position:1; color:'blue'}
}
// 0代表顶部 1代表底部
border.color: "lightsteelblue"
border.width:4
radius:10
}Text
1
2
3
4
5
6
7
8
9
10
11
12Rectangle{
id:rect3
x:250; y:10
width:76; height:96
gradient: Gradient{
GradientStop{position:0; color:'red'} // 0代表顶部 1代表底部
GradientStop{position:1; color:'blue'}
}
border.color: "lightsteelblue"
border.width:4
radius:10
}Image
1
2
3
4
5
6
7Image{
id: img1
source: "../../ai2.jpg"
//fillMode: Image.stretch
//fillMode: Image.PreserveAspectCrop
fillMode: Image.PreserveAspectFit
}MouseArea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20Rectangle{
id:rect1
x:12; y:12
width: 76; height:96
color: "lightsteelblue"
MouseArea{
id:area
width: parent.width
height: parent.height
onClicked: rect2.visible = !rect2.visible
}
}
Rectangle{
id:rect2
x:112; y:12
width: 76; height:96
border.color: "lightsteelblue"
border.width:4
radius:8
}TextInput
文本输入TextEdit
组件
- 组件是可重复使用的元素,最简单的形式是基于文件的组件
1 |
|
1 | import QtQuick |
简单变换
1 | import QtQuick |
1 | import QtQuick |
定位器
Row
1
2
3
4
5
6
7
8Row{
id:row
anchors.centerIn: parent
spacing: 10
RedSquare{}
GreenSquare{}
BlueSquare{}
}Column
1
2
3
4
5
6
7
8Column{
id:column
anchors.centerIn: parent
spacing: 10
RedSquare{}
GreenSquare{}
BlueSquare{}
}Grid
1
2
3
4
5
6
7
8
9
10
11
12
13Grid{
id:grid
anchors.centerIn: parent
spacing:10
rows:2
columns:3
RedSquare{}
GreenSquare{}
BlueSquare{}
RedSquare{}
GreenSquare{}
BlueSquare{}
}Flow
1
2
3
4
5
6
7
8
9
10
11
12Flow{
id:flow
anchors.fill: parent
anchors.margins: 20
spacing: 20
RedSquare{}
GreenSquare{}
BlueSquare{}
RedSquare{}
GreenSquare{}
BlueSquare{}
}
示例
1 | GraySquare{ |
布局
qml
使用锚来布局项目- 文本元素除了上图的锚外还有
baseline
,是指文本所在的线,如果item
没有文字则baseline
和top
的位置是相同的
- 文本元素除了上图的锚外还有
键盘输入
1 | import QtQuick |
动画
QML
动画使用插值的方式控制属性的更改
常用的动画类型元素动画:
PropertyAnimation:
属性值改变播放动画NumberAnimation:
qreal-type
值改变播放动画ColorAnimation:
颜色值改变播放动画RotationAnimation:
旋转值改变播放的动画
eg.
1 | import QtQuick |
可以通过多种方式执行动画
- 属性上的动画: 在元素完全加载后自动运行
- 属性上的行为: 属性值更改时自动运行
- 独立动画: 使用
start()
显示启动动画或将running
设置为true
时运行
eg.
1 | import QtQuick |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 STYX HELIX!