1.简介
QML中,对于任何一个属性,都会生成一个属性修改的信号和槽函数,比如:在Window中以下就是宽和高改变时发出的信号。
void heightChanged(int arg)
void widthChanged(int arg)
则对应的槽函数就是,前面加 on 然后大写。
onWidthChanged: {
console.log("width = ",width);
}
onHeightChanged: {
console.log("Height = ",height);
}
自定义属性:
自定义了一个属性value,会自动生成valueChanged()信号,onValueChanged的槽函数。
然后创建了一个Button,每点击Button的时候,value自增。
property int value: 0
onValueChanged: {
console.log("value = ",value);
}
Button{
width: 50
height: 50
x:0
y:0
background: Rectangle{
color:"red"
}
onClicked: {
value++
}
}
2.自定义信号
连接方式一:使用connect方式。
Window {
visible: true
width: 500
height: 500
title: qsTr("Hello World")
signal test(string s,int value) //自定义信号
function func(s,v){ //槽函数
console.log(s,v)
}
Button{
width: 50
height: 50
x:0
y:0
background: Rectangle{
color:"red"
}
onClicked: {
test("test",2);
}
}
Component.onCompleted: {
test.connect(func) //连接信号槽
}
}
连接方式二:使用连接器
Window {
id: window
visible: true
width: 500
height: 500
title: qsTr("Hello World")
signal test(string s,int value) //自定义信号
Button{
width: 50
height: 50
x:0
y:0
background: Rectangle{
color:"red"
}
onClicked: {
test("test",2);
}
}
Connections{
target: window
// onTest:{ //方式一
// console.log(s,value) //名称和信号的名称一致
// }
function onTest(s,v){ //方式二 //自定义名称
console.log(s,v)
}
}
}