//test_signal.qml
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Rectangle
{
Component.onCompleted:
{
print("Rectangle onCompleted")
}
Component.onDestruction:
{
print("Rectangle onDestruction")
}
}
property Item myItem:Item
{
Component.onCompleted:
{
print("property Item onCompleted")
}
Component.onDestruction:
{
print("property Item onDestruction")
}
}
Button
{
/*
canceled()
clicked()
doubleClicked()
pressAndHold()
pressed()
released()
toggled()
*/
text:"test signal"
onClicked:
{
print("Button onClicked")
}
onPressed:
{
print("Button onPressed")
}
}
//signal <name>[([<type> <parameter name>[, ...]])]
//接收信号通知,定义一个名为on<Signal> 函数,其中<Signal>是信号的名称,第一个字母大写
Button
{
y:30
text:"mySignal"
signal mySignal
signal mySignalPara(int index,string str)
onClicked:
{
mySignal()
mySignalPara(99,"InButonnStr")
}
//on<Signal>
onMySignal:
{
print("call onMySignal1 ")
}
onMySignalPara:(i,s)=>
{
print("call onMySignalPara "+ i+":"+s)
}
}
Rectangle
{
x:100
width: 100
height: 100
color:"red"
property real size: 1.0
//on<Property>Changed 的形式编写,其中<Property>是属性的名称,第一个字母大写
onSizeChanged:
{
width = size*100
height = size*100
}
Button
{
text: "Change size"
onClicked: parent.size+=0.1
}
}
///手动将信号连接到方法
Item
{
signal testConnectSig
function testConnectInitSlot()
{
print("call testConnectInitSlot")
}
function testConnectSlot()
{
print("call testConnectSlot")
}
function testConnectSlot2()
{
print("call testConnectSlot2")
}
Button
{
text:"test connect"
x:250
onClicked:
{
//绑定信号和槽函数
//可以多次绑定同一个槽函数
parent.testConnectSig.connect(parent.testConnectSlot)
parent.testConnectSig.connect(parent.testConnectSlot)
parent.testConnectSig.connect(parent.testConnectSlot2)
parent.testConnectSig()
//同一个槽函数只需要销毁一次
print("-------------------------------")
parent.testConnectSig.disconnect(parent.testConnectSlot)
parent.testConnectSig()
parent.testConnectSig.disconnect(parent.testConnectSlot2)
}
}
//对象创建
Component.onCompleted:
{
testConnectSig.connect(testConnectInitSlot)
}
//对象销毁
Component.onDestruction:
{
testConnectSig.disconnect(testConnectInitSlot)
}
}
Item
{
//测试多个类型(QML文件)之间的信号槽传递
MyType
{
id:mytype
y:100
}
Rectangle
{
id:rect
width:200
height:200
color:"green"
x:200
y:100
function recvSetSize(w,h)
{
print("recvSetSize " + w +":"+h)
x+= w-width
width = w;
height = h
}
}
Component.onCompleted:
{
mytype.setSize.connect(rect.recvSetSize)
}
}
Connections
{
target:mytype
function onSetSize(w,h)
{
print("Connections "+w+":"+h)
}
}
}