信号创建
signal testSig(string s, int value)
槽函数
function func(ss, ii){console.log("s: ",ss, " i: ", ii)}
信号绑定
Component.onCompleted: {testSig.connect(func) //绑定信号处理函数}
信号触发
Button{width: 50height: 20onClicked:{//触发信号testSig("zhangsan", 22)}}
//定义一个信号signal testSig(string s, int value)function func(ss, ii){console.log("s: ",ss, " i: ", ii)}Button{width: 50height: 20onClicked:{//触发信号testSig("zhangsan", 22)}}Component.onCompleted: {testSig.connect(func) //绑定信号处理函数}
Connections
属性
enabled : boolignoreUnknownSignals : bool //target无改信号的时候忽略掉function绑定无效信号导致的编译警告target : Object //信号发出者
替换绑定方式1:
Connections{target:rootonTestSig:{console.log(s," ", value) //参数名称不直接}}
on+信号首字母大写的方式绑定信号槽不推荐,这主要是qml自带槽的写法。
替换绑定方式2:
function on+首字母大写信号名+括号信号参数名称(可以自己指定), 然后槽具体实现
Connections{target:rootfunction onTestSig(str, ivalue){console.log("onTestSig func ", str, " ", ivalue)}}
自定义组件信号槽的应用:
import QtQuick 2.0import QtQuick.Controls 2.15Rectangle {width: 200height: 100anchors.centerIn: parentproperty Component com1 //不给默认值property Component com2border.color: "red"Loader{id: loader1sourceComponent: com1anchors.bottom: parent.bottomanchors.bottomMargin: 20anchors.right: parent.rightanchors.rightMargin: 100Connections{target: loader1.itemignoreUnknownSignals: true //当该信号不存在时忽略掉function onBtnSig(value){console.log("top value ", value)}function onRightBtnPressed(){loader2.item.focus = trueloader2.item.forceActiveFocus()console.log("onRightBtnPressed")}}Component.onCompleted: {loader1.item.focus = trueloader1.item.forceActiveFocus()}}Loader{id: loader2sourceComponent: com2anchors.bottom: parent.bottomanchors.bottomMargin: 20anchors.right: parent.rightanchors.rightMargin: 20Connections{target: loader2.itemignoreUnknownSignals: truefunction onBtnSig(value){console.log("bottom value ", value)}function onLeftBtnPressed(){loader1.item.focus = trueloader1.item.forceActiveFocus()console.log("onLeftBtnPressed")}}}}
Component{id: comButton{id: btn1width:50height: 20background: Rectangle{border.color: btn1.activeFocus ? "red":"green" //activeFocus体现了唯一性border.width: 2}//// signal btnSig(int v)// onClicked: {//// btnSig(22)// }signal leftBtnPressed()Keys.onLeftPressed: {leftBtnPressed()console.log("btn onLeftPressed")}signal rightBtnPressed()Keys.onRightPressed: {rightBtnPressed()console.log("btn onRightPressed")}}}MyComponent{com1:comcom2:com}

自定义组件中使用Loader进行自定义组件的加载,通过Loader属性item获取到自定义的组件并赋给Connections的target属性,为了防止未定义的方法的绑定,加上ignoreUnknownSignals:true防止编译器报错,正式项目中可不加不然bug不好找。

