什么是qml
和qtquick
- qml:qt公司开发的一种声明式型语言,相较于c++更加的方便,也更容易写出好看的界面
- QtQuick是一个基于QML的框架。
基本语法
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("qml1")
Rectangle{
id:rect1
x:50
y:50
z:1 //z轴可以决定平面上的覆盖关系
width: 100
height:50
color: "red"
focus: true
rotation: 30;
}
Rectangle{
id:rect2
x:120
y:120
z:2
width: 100
height: 50
color: "blue"
MouseArea
{
anchors.fill: parent
onClicked:
{
console.log(rect1.color)
if(rect1.color=="#ff0000"){rect1.color="#000000"}
else if(rect1.color=="#000000"){rect1.color="#ff0000"}
rect1.rotation+=10
}
}
}
}
-
import语句导入一个模块qt6可以不写版本号自动加载最高版本的模块
-
对于单行注释,可以使用//,对于多行注释,可以通过/**/进行注释。
-
就像在C/C++和JavaScript中一样每个QML文件都需要有一个唯一的根元素,就像HTML一样
-
元素声明形式为:type{}元素可以有属性,形式为:name:valueQML文档中的任意元素可以通过使用其id(不带引号的标识符)进行访问
-
元素可以嵌套,这意味着父元素可以有子元素子元素可以使用parent关键字访问父元素
-
QML中集成了JavaScript,你可以在QML文件中使用JavaScript表达式来计算属性值、处理事件等。JavaScript表达式可以包含算术运算、逻辑运算、条件语句等。
属性
Text {
id: thisLabel
x: 300; y: 100
height: 2 * width
property int times: 24//定义新属性
property alias anotherTimes: thisLabel.times
text: "thisLable " + anotherTimes
font.family: "微软雅黑"
font.pixelSize: 24
KeyNavigation.tab:rect1 //切换焦点到某个item(指定tab键)
onHeightChanged: console.log('height:', height)
focus: true
color: focus ? "red" : "black" //color属性改变时就会自动生效
}
Rectangle{
id:rect1
x:50
y:50
width: 100
height:50
rotation: 30;
color: focus ? "red" : "black"
KeyNavigation.tab:thisLabel
}
- id是用于引用QML文件(在QML中称为“document”)中的元素。id在文档中必须是唯一的,不能重置为其他值。(类似于C++的引用。)
- 属性可以设置值,具体取决于其类型。如果没有为属性指定值,将使用默认初始值。属性可以依赖于一个或多个其他属性。这称为绑定。
- 可以使用property限定符向元素添加新属性,后跟类型、名称和可选的初始值(
property 类型 名称:值
)。 - 声明属性的另一种重要方式是使用别名关键字(
property alias 名称 :引用
)。 - 基于int的值将自动转换为字符串类型。每次times属性更改时都会更新文本。
- 编写grouped property的另一种方法是
font{family:“Ubuntu”; pixelSize:24}
。 - 可以为属性提供处理程序,属性更改后被调用。
JavaScript
Text {
id: thisLabel
x: 300; y: 100
height: 2 * width
property int spacetimes: 0//定义新属性
property alias anotherTimes: thisLabel.spacetimes//相当于引用
text: "thisLable " + anotherTimes
font.family: "微软雅黑"
font.pixelSize: 24
KeyNavigation.tab:rect1 //切换焦点到某个item(指定tab键)
onHeightChanged: console.log('height:', height)
focus: true
color: focus ? "red" : "black" //color属性改变时就会自动生效
Keys.onSpacePressed: increment();//focus时才生效
onTextChanged: (text)=>{console.log(text)}
function increment(){
spacetimes+=1;
}
}
- 以
function name(parameters){…}
的形式定义JavaScript函数,它增加了计数器。每次SpacePress递增时,绑定属性也将更新。 - 也可以使用箭头函数((text)=>{})。