当前位置:网站首页>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 .
边栏推荐
猜你喜欢

Kirin V10 source code compilation qtcreater4.0.3 record
![[pyGame practice] playing poker? Win or lose? This card game makes me forget to eat and sleep.](/img/ba/a174c5daccef7a6ea72c11dad8601d.png)
[pyGame practice] playing poker? Win or lose? This card game makes me forget to eat and sleep.

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

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

适用于顺序磁盘访问的1分钟法则

7.13WEB安全作业
![[ctfhub] the data of JWT header and payload are transmitted in clear text. If sensitive information is contained in it, sensitive information will be leaked. Try to find the flag. Format is flag{}](/img/d0/133d628a304f5c6b5f0d514c9fe222.jpg)
[ctfhub] the data of JWT header and payload are transmitted in clear text. If sensitive information is contained in it, sensitive information will be leaked. Try to find the flag. Format is flag{}

SCA在得物DevSecOps平台上应用

BGP federal experiment

BGP联邦实验
随机推荐
【HiFlow】定期发送腾讯云短信发送群
Opnsense - multifunctional, highly reliable and easy-to-use firewall (II)
SCA在得物DevSecOps平台上应用
Application of ERP management system in equipment manufacturing enterprise management
Chapter 4 use%rest API classes create rest services
Go: Gin urlencoded format
800V高压快充落地进程加快均胜电子获5亿欧元项目定点
适用于顺序磁盘访问的1分钟法则
VMware虚拟机下载安装使用教程
没有了华为,高通任意涨价,缺乏核心技术的国产手机只能任由宰割
麒麟V10源码编译qtCreator4.0.3记录
Use of RSA encryption
[machine learning basics] unsupervised learning (5) -- generation model
Dynamic planning - force buckle
xlswriter - excel导出
String and integer convert each other
ERP管理系统在装备制造企业管理中的应用
C语言注释的方法
aws篇3 go语言如何publish message 到iot的MQTT
Open source quadruped robot with design drawings and code "suggestions collection"