1、信号的连接方式
-
通过on<Signal>信号处理器接收信号
Window {
visible: true
Rectangle{
id: rect1
x: 0
y: 0
width: parent.width / 2
height: parent.height
z: 1
}
Rectangle{
id: rect2
x: parent.width / 2
y: 0
width: parent.width / 2
height: parent.height
z: 1
}
Button{
text: "改变颜色"
onClicked: {
rect1.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
rect2.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
}
z: 2
}
} -
通过<附加属性>.on<Signal>信号接收器接受附加属性的信号
用于接收那些并非由对象自身或其基类定义,而是由外部"附加类型"额外提供的信号
例如:Component.onCompleted:这是最常用的附加信号,由Component附加到对象上,当对象创建完成时自动触发,常用于执行初始化逻辑;
Keys.onPressed:用Keys附加类型提供,当对象获得焦点并发生键盘按键时触发,用于处理键盘交互
Window {
visible: true
Rectangle{
id: root
anchors.fill: parent
focus: true //必须获得焦点,信号才会触发
color: "lightgrey"
Text{
id: info
anchors.centerIn: parent
text: "请按任意键"
font.pixelSize: 20
}
//Component附加信号,对象创建完成时触发
Component.onCompleted: {
print("Rectangle已创建完成,开始初始化")
info.text = "初始化完成,请按键"
}
//Keys附加信号,键盘按下时触发
Keys.onPressed: (event) => {
print("按下了键,key=", event.key)
info.text = "按下了键:" + event.key
//避免继续传播
event.accepted = true
}
}
}
- on<Property>Changed属性更改信号处理器
属性值变化时会触发一个<Property>Changed信号,我们便可以通过on<Property>Changed信号处理器去处理他,但也有极少属性没有<Property>Changed信号
Window {
visible: true
TextField{
id: input
anchors.centerIn: parent
width: 250
placeholderText: "请输入:"
font.pixelSize: 18
onTextChanged: {
display.text = "输入了:" + input.text
}
Text{
id: display
anchors.top: input.bottom
anchors.horizontalCenter: parent.horizontalCenter
text: "1111"
}
}
}
- 使用Connections对象建立信号连接
写法:
Connections{
target: xxx //表示发出信号的对象
on<Signal>: {
//进行target对象发出信号的处理
}
}
Window {
visible: true
Row{
id: row
Rectangle{
width: 100
height: 100
id: rect1
color: "blue"
}
Rectangle{
width: 100
height: 100
id: rect2
color: "red"
}
}
MouseArea{
anchors.fill: row
id: area
}
Connections{
target: area
onClicked:{
rect1.color = Qt.rgba(Math.random(), Math.random(), Math.random())
rect2.color = Qt.rgba(Math.random(), Math.random(), Math.random())
}
}
}
-
使用signal信号的connect()进行连接
Window {
visible: trueRectangle{ id: root width: 100 height: 100 color: "red" signal mySignal(string msg) //定义一个带参数的信号 function myHandler(text){ //准备一个函数作为"槽" print("收到信号:", text) } Component.onCompleted: { //将mySignal信号连接到myHandler函数 root.mySignal.connect(myHandler) } MouseArea{ anchors.fill: parent onClicked: root.mySignal("hello world") //发送信号 } }}