1、认识组件
⼀个组件是⼀个可以重复使⽤的元素,QML提供⼏种不同的⽅法来创建组 件。但是我们只对其中⼀种⽅法进⾏讲解:⼀个⽂件就是⼀个基础组 件。⼀个以⽂件为基础的组件在⽂件中创建了⼀个QML元素,并且将⽂件以 元素类型来命名(例如Button.qml)。你可以像任何其它的QtQuick模块中使 ⽤元素⼀样来使⽤这个组件。在我们下⾯的例⼦中,你将会使⽤你的代码作 为⼀个Button(按钮)来使⽤。
2、使用组件
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Rectangle { // our inlined button ui
id: button
x: 12; y: 12
width: 116; height: 26
color: "lightsteelblue"
border.color: "slategrey"
Text {
anchors.centerIn: parent
text: "Start"
}
MouseArea {
anchors.fill: parent
onClicked: {
status.text = "Button clicked!"
}
}
}
Text { // text changes when button was clicked
id: status
x: 12; y: 76
width: 116; height: 26
text: "waiting ..."
horizontalAlignment: Text.AlignHCenter
}
}
运行结果:
点击后:
这个不是直接使用button的元素,而是间接使用矩形和文本这些基本元素的组合这个达到效果。