当前位置:网站首页>Quickly master QML Chapter 5 components
Quickly master QML Chapter 5 components
2022-07-23 15:44:00 【la_ vie_ est_ belle】
Catalog
5.1 Write and load a simple component
5.2 Load components from files
5.3 Small actual combat : Customize a button
When there is a lot of duplicate code in the project , We will write these repeated codes into a function , This makes the code simpler . The function of components is the same as that of functions , We extract the repeated elements , Weave into a component , This can reduce a lot QML Code. , Very convenient .
5.1 Write and load a simple component
If you want to put several rectangles with the same color and size on the window , We can write this without components , See the sample code below .
import QtQuick 2.0
Rectangle {
id: root
width: 300
height: 200
Rectangle { // 1
id: rect1
width: 50
height: 50
color: "red"
x: 10
y: 10
MouseArea {
anchors.fill: parent
onClicked: {
if (parent.color == "#ff0000") {
parent.color = "blue"
}
else {
parent.color = "red"
}
}
}
}
Rectangle { // 1
id: rect2
width: 50
height: 50
color: "red"
x: 60
y: 60
MouseArea {
anchors.fill: parent
onClicked: {
if (parent.color == "#ff0000") {
parent.color = "blue"
}
else {
parent.color = "red"
}
}
}
}
Rectangle { // 1
id: rect3
width: 50
height: 50
color: "red"
x: 110
y: 110
MouseArea {
anchors.fill: parent
onClicked: {
if (parent.color == "#ff0000") {
parent.color = "blue"
}
else {
parent.color = "red"
}
}
}
}
}Running results :

Code interpretation :
1. We added three rectangular elements , Each rectangular element receives mouse events . When the color is red , After clicking, it will be blue ; If it's blue , After clicking, it turns red .
These three rectangles except id And coordinates , Everything else is the same , So we can write a reusable component to simplify the code .
import QtQuick 2.0
Rectangle {
id: root
width: 300
height: 200
Component { // 1
id: rectComponent
Rectangle {
width: 50
height: 50
color: "red"
MouseArea {
anchors.fill: parent
onClicked: {
if (parent.color == "#ff0000") {
parent.color = "blue"
}
else {
parent.color = "red"
}
}
}
}
}
Loader { // 2
id: rect1
sourceComponent: rectComponent
x: 10
y: 10
onLoaded: {
console.log(" Finished importing components ") // 3
}
}
Loader {
id: rect2
sourceComponent: rectComponent
x: 60
y: 60
}
Loader {
id: rect3
sourceComponent: rectComponent
x: 110
y: 110
}
}1. We put the repeated rectangular element code into Component In the element , Be careful Component The element can only contain id attribute , Cannot have other attributes .
2. Use Loader Element when loading components , Only need to sourceComponent The value of the property is set to the id that will do .Loader It has its own attributes , Readers can go to Loader Document page see . We go through Loader Element coordinates to set the position of the rectangular element on the window .
3. Loaded Elements have loaded The signal , This signal will be transmitted after the component is loaded .
5.2 Load components from files
In the last section , We write components in elements , But for the convenience of project management , We can write the components in a separate file . We build a new one Rect.qml file , The current project structure is shown in the figure below .

hold 5.1 The components in the section are written Rect.qml in , As shown in the figure below .

notes : When we write components into a separate file , No more writing Component.
Now modify demo.qml The code in , As shown below .
import QtQuick 2.0
Rectangle {
id: root
width: 300
height: 200
Loader {
id: rect1
source: "./Rect.qml" // 1
x: 10
y: 10
onLoaded: {
console.log(" Finished importing components ")
}
}
}Code interpretation :
1. take Loader Elemental source Property to the file path containing the target component , Then you can load this component .
At present, we still pass Loader This element is used to load components , In fact, when components are written in a separate file , We don't need to use Loader, Only file name You can use components , It's very convenient . See the sample code below .
import QtQuick 2.0
Rectangle {
id: root
width: 300
height: 200
Rect { // 1
id: rect1
x: 10
y: 10
}
}Code interpretation :
1. take Rect.qml Suffix in file name .qml Just remove it .
5.3 Small actual combat : Customize a button
If you want to add a button to the window , We usually use Button Elements ( This element is introduced in Chapter 3 ). But sometimes we will customize a button with different appearance and function , Now use components to implement a .
First step :
Create a new one Button.qml file , As shown in the figure below .

The second step :
stay Button.qml Write code , The author will use Rectangle and MouseArea Element implements a custom button .
import QtQuick 2.0
Rectangle {
id: root
signal clicked // 1
width: 120
height: 30
radius: 5
// 2
property alias text: btnText.text
property alias textSize: btnText.font.pixelSize
// 3
property string gradientStopColor1: "#8a9195"
property string gradientStopColor2: "black"
gradient: Gradient {
GradientStop { position: 0.0; color: gradientStopColor1 }
GradientStop { position: 1.0; color: gradientStopColor2 }
}
Text { // 4
id: btnText
anchors.centerIn: root
text: "Button"
color: "white"
font.pixelSize: 20
font.weight: Font.Bold
}
MouseArea { // 5
anchors.fill: root
hoverEnabled: true
onClicked: {
root.clicked()
}
onPressed: {
root.gradientStopColor1 = "#6a7073"
}
onReleased: {
root.gradientStopColor1 = "#8a9195"
}
onEntered: {
root.gradientStopColor1 = "#7d8488"
}
onExited: {
root.gradientStopColor1 = "#8a9195"
}
}
}Code interpretation :
1. Customize a signal clicked, It will launch when the user presses the button .
2. adopt property Customize a alias attribute ,alias Used to set an alias for an element attribute in a component , For external use . Here we give Text Elemental text Property has an alias set text, to font.pixelSize Property has an alias set textSize. So we can use this when using components text Alias change button text , And pass textSize Alias changes text size . Format the alias as follows :

- stay name Fill in the alias .
- stay value Fill in the alias to refer to Target element attribute of .
3. Customize two properties gradientStopColor1 and gradientStopColor2, Their type is string string. We can use property Customize a QML Built in type Properties of , The format is as follows :

- stay type Fill in the built-in type name .
- stay name Fill in the attribute name .
- stay value Fill in the initial value of the attribute .
gradient Property is used to set a gradient background for rectangular elements , Readers can go to this Document page Understand this attribute .
4. Button text , Can pass font Property to set the style of the text .
5. MouseArea Element is used to realize the click function and effect of the button . take hoverEnabled Set to true Can let the mouse enter and leave the rectangular element when emitting entered and exited The signal . If the attribute is false, That's only when the mouse is pressed , Will detect the mouse entry and exit events ( In this example, click events will be affected ).
When pressed、released、entered as well as exited When the signal is transmitted , We changed it gradientStopColor1 Value , So when the mouse hovers 、 The color will change when you click or release the button , Respond to user actions . When MouseArea Of clicked When the signal is clicked , We launch customized clicked The signal .
The third step :
stay demo.qml Use custom Button Components , Look at the code below .
import QtQuick 2.0
Rectangle {
id: root
width: 300
height: 200
Button {
anchors.centerIn: root
text: " A button " // 1
textSize: 18
onClicked: { // 2
console.log(" I got clicked ")
}
}
}Running results :

Code interpretation :
1. Use alias properties text and textSize, Modify the button text and text size respectively through them .
2. When clicked When the signal is transmitted , Print a piece of text on the console .
5.4 Summary of this chapter
1. If the component is written in other elements , Then we need to use Component Elements , And pass Loader Element to load . If it is written in a single file , You can directly pass the file name ( Without the suffix ) Use components .
2. Use Loader Element when loading components , We can use sourceComponent and source attribute , Components of the former value id, The latter value is the path of the file where the component is located .
3. Use property You can set QML Built in standard attributes or alias Alias , Aliases are usually used to expose an element attribute inside a component , For external use .
边栏推荐
- 查找论文源代码
- Part III detailed explanation of RBAC authority management database design
- AWS篇1
- STL deque
- [7.16] code source - [array division] [disassembly] [select 2] [maximum common divisor]
- SCA在得物DevSecOps平台上应用
- 老照片上色——DeOldify快速上手
- Chapter 4 use%rest API classes create rest services
- day1
- VSCode的感叹号+tab的快捷键不能用,以及A-SOUL-live2d插件出问题的解决方法
猜你喜欢

麒麟V10源码编译qtCreator4.0.3记录

Axure advanced

Xlswriter - Excel export

【Pygame实战】打扑克牌嘛?赢了输了?这款打牌游戏,竟让我废寝忘食。

Skills to learn before going to primary school

946. 验证栈序列 ●● & 剑指 Offer 31. 栈的压入、弹出序列 ●●

The official redis visualization tool is coming. The needle doesn't poke

xlswriter - excel导出

Batch deletion with RPM -e --nodeps

VSCode的感叹号+tab的快捷键不能用,以及A-SOUL-live2d插件出问题的解决方法
随机推荐
【Try to Hack】sql注入 Less7 (into outfile和布尔盲注)
Learning about patents
Can multithreading optimize program performance?
bgp选路原则
The exclamation point of vscode +tab shortcut key cannot be used, and the solution to the problem of a-soul-live2d plug-in
深入理解CAS (自旋锁)
多线程一定能优化程序性能吗?
(Zset)Redis底层是如何用跳表进行存储的
《快速掌握QML》第五章 组件
day1
ClickHouse,让查询飞起来!!!
Deep understanding of L1 and L2 regularization
Application of ERP management system in equipment manufacturing enterprise management
第一篇 项目基本情况介绍
Start process of activity
Cookie和Session的区别
[CTFHub]JWT 的头部和有效载荷这两部分的数据是以明文形式传输的,如果其中包含了敏感信息的话,就会发生敏感信息泄露。试着找出FLAG。格式为 flag{}
记一次SQL优化
【2023提前批 之 面经】~ 京东方
Idea five free plug-ins to improve efficiency