组件这个词,英文叫component,但是中文翻译的很好,按字面来讲,很好理解,就是把件组合起来。
于是,组件就是各种东西组合起来当作一个东西。
做界面,为了复用代码,一定会用到组件。
QtQuck提供了非常方便的创建组件的方式。
一般有两种方式:
1,直接在代码里定义Component。
2,在单独文件中创建Component
先说第一种方法
一,定义Component
其实很简单,先举个例子:
Component{
id:myComponent
Rectangle{
id:rect
width:100
height:100
color:"red"
}
}
这就是一个组件,然后里面放了一个长100,宽100,红色的矩形。
使用时,一般用loader来加载它
Loader{
sourceComponent:myComponent
}
但其实这种方式我并不推崇,因为这个会让一个文件变得很大,可读性不好,作为写代码来讲,应该尽量使用第二种方法。
二,在单独文件中创建Component
在单独文件中创建Componen有个规则,那就是文件名首字母必须是大写,这样才会被认为是个Component
一般最外层会定义一个Item,例如创建一个文件,叫做MyComponent.qml:
Item{
Rectangle{
id:rectangle
width:100
height:100
color:"red"
}
}
然后使用的时候:
MyComponent{
id:myComponent
}
这样一个组件就做成了。
但是,作为一个组件,这个肯定是不能满足需求的, 我们需要自己定义的属性。
三,给组件增加属性
修改MyComponent.qml中代码如下:
Item{
property int intProperty:0 //增加的代码
Rectangle{
id:rectangle
width:100
height:100
color:"red"
}
}
这就是给MyCompoent增加了一个名叫intProperty的属性,默认值是0。
在使用的时候,就可以直接给属性赋值:
MyComponent{
id:myComponent
intProperty:1
}
还可以直接给Item包含的对象的属性起个别名,作为组件的属性:
Item{
property int intProperty:0
property alias color:rectangle.color //增加的代码
Rectangle{
id:rectangle
width:100
height:100
color:"red"
}
}
MyComponent{
id:myComponent
intProperty:1、
color:"blue"
}
Item{
property int intProperty:0
signal colorChanged //增加的代码
Rectangle{
id:rectangle
width:100
height:100
color:"red"
}
}
signal colorChanged(string arg1,string arg2)
触发事件时,只需要调用一下声明signal
Item{
property int intProperty:0
signal colorChanged
Rectangle{
id:rectangle
width:100
height:100
color:"red"
onColorChanged:{
colorChanged("test1","test2")
}
}
}
则在使用的MyComponent的时候,可以增加处理函数。
MyComponent{
id:myComponent
intProperty:1、
onColorChanged:{
console.log(arg1)
console.log(arg2)
}
}
注意:上面的代码都是运行不了的,只是为了解释语法。