信号创建
signal testSig(string s, int value)
槽函数
function func(ss, ii){
console.log("s: ",ss, " i: ", ii)
}
信号绑定
Component.onCompleted: {
testSig.connect(func) //绑定信号处理函数
}
信号触发
Button{
width: 50
height: 20
onClicked:
{
//触发信号
testSig("zhangsan", 22)
}
}
//定义一个信号
signal testSig(string s, int value)
function func(ss, ii){
console.log("s: ",ss, " i: ", ii)
}
Button{
width: 50
height: 20
onClicked:
{
//触发信号
testSig("zhangsan", 22)
}
}
Component.onCompleted: {
testSig.connect(func) //绑定信号处理函数
}
Connections
属性
enabled : bool
ignoreUnknownSignals : bool //target无改信号的时候忽略掉function绑定无效信号导致的编译警告
target : Object //信号发出者
替换绑定方式1:
Connections{
target:root
onTestSig:{
console.log(s," ", value) //参数名称不直接
}
}
on+信号首字母大写的方式绑定信号槽不推荐,这主要是qml自带槽的写法。
替换绑定方式2:
function on+首字母大写信号名+括号信号参数名称(可以自己指定), 然后槽具体实现
Connections{
target:root
function onTestSig(str, ivalue)
{
console.log("onTestSig func ", str, " ", ivalue)
}
}
自定义组件信号槽的应用:
import QtQuick 2.0
import QtQuick.Controls 2.15
Rectangle {
width: 200
height: 100
anchors.centerIn: parent
property Component com1 //不给默认值
property Component com2
border.color: "red"
Loader{
id: loader1
sourceComponent: com1
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.right: parent.right
anchors.rightMargin: 100
Connections{
target: loader1.item
ignoreUnknownSignals: true //当该信号不存在时忽略掉
function onBtnSig(value)
{
console.log("top value ", value)
}
function onRightBtnPressed()
{
loader2.item.focus = true
loader2.item.forceActiveFocus()
console.log("onRightBtnPressed")
}
}
Component.onCompleted: {
loader1.item.focus = true
loader1.item.forceActiveFocus()
}
}
Loader{
id: loader2
sourceComponent: com2
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.right: parent.right
anchors.rightMargin: 20
Connections{
target: loader2.item
ignoreUnknownSignals: true
function onBtnSig(value)
{
console.log("bottom value ", value)
}
function onLeftBtnPressed()
{
loader1.item.focus = true
loader1.item.forceActiveFocus()
console.log("onLeftBtnPressed")
}
}
}
}
Component{
id: com
Button{
id: btn1
width:50
height: 20
background: 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:com
com2:com
}
自定义组件中使用Loader进行自定义组件的加载,通过Loader属性item获取到自定义的组件并赋给Connections的target属性,为了防止未定义的方法的绑定,加上ignoreUnknownSignals:true防止编译器报错,正式项目中可不加不然bug不好找。