In QML, in some situations, I need to remove the old method to a signal and redefine a new method to handle the signal, a demo is as following:
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MouseArea {
id:mouse
anchors.fill: parent
onClicked: {
console.log("11111");
}
}
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
Component.onCompleted: {
//if(false){
//}
// mouse.clicked = null;
//mouse.clicked.disconnect();
mouse.clicked.connect(
function(){
console.log("22222")
});
}
}
I connect a new function, however it will show both "11111" and "22222", seems it add a new function to handle the signal.
I tried set "mouse.clicked = null", still doesn't work.
I also tried disconnect the method,like as following:
MouseArea {
id:mouse
anchors.fill: parent
onClicked:say()
}
Component.onCompleted: {
mouse.clicked.disconnect(say);
mouse.clicked.connect(
function(){
console.log("22222")
});
}
function say(){
console.log("11111");
}
Still print both "11111" and "22222", how can I remove the old methond and redefine the method in Component.onCompleted()?
update on 2017-6-13:
Thanks, guys.I also use connections,still cannot disconnect as I use qt5.6.1, there is no enable property :( . if we use explicitly connect() function, it works. but in my case, I think I can't connect a method , I need to check some If situations to define whether I need to remove the signal handler in Component.onCompleted.
Also a quick question, why the window component completed faster than mouseArea? the log "first load" first loaded.
MouseArea {
id:mouse
anchors.fill: parent
Connections{
onClicked:say()
}
Component.onCompleted: {
//mouse.clicked.connect(say)
console.log("second load")
}
}
Component.onCompleted: {
console.log("first load")
mouse.clicked.connect(
function(){
mouse.clicked.disconnect(say);
//mouse.clicked.disconnect(say);
console.log("22222")
});
}
You can't disconnect the default signal handler onSignal: { do what ever }
.
You can only dissconnect, when you have connected with onSignal.connect(say)
beforehand. You could do this in Component.onCompleted
.
If you use the syntax:
onSignal: say()
this equals
onSignal.connect(function() { say() })
and therefore you can't use onSignal.disconnect(say)
as say
was never connected. (I don't know whether it is connected to onSignal
or to signal
- both could be done manually, or whether it is not connected at all. You can't disconnect it, without having a reference to the implicitly created function.)
In QML, the nicer way would be to stay declarative. For this you can use the Connections
-construct:
Connections {
target: mouse // set to null to disconnect (Qt<=5.6)
onClicked: { do what ever }
enabled: true // change this, when you want to disconnect it (Qt>=5.7)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With