![QML:从其他元素覆盖信号处理程序](https://linux22.com/image/856240/QML%EF%BC%9A%E4%BB%8E%E5%85%B6%E4%BB%96%E5%85%83%E7%B4%A0%E8%A6%86%E7%9B%96%E4%BF%A1%E5%8F%B7%E5%A4%84%E7%90%86%E7%A8%8B%E5%BA%8F.png)
是否可以从按钮的 onClick() 中覆盖元素操作(例如计时器的 onTriggered())?
类似这样->
Button {
id: centerBtn
objectName: "button"
onClicked: {
delaytimer.running = true;
delayTimer.onTriggered {}; // override here
}
Timer {
id: delaytimer
interval: 1000
running: false
repeat: false
onTriggered: //something implemented here
}
}
答案1
您可以定义一个属性来存储信号处理程序的代码,并在需要时重新分配它:
看一下下面的代码片段:
import QtQuick 2.0
import Ubuntu.Components 0.1
Rectangle {
width: 200
height: 150
Button {
id: foo
text: "Foo"
onClicked: {
delaytimer.a = function () { console.log("Foo!") };
delaytimer.running = true;
}
}
Button {
id: bar
text: "Bar"
anchors.left: foo.right
onClicked: {
delaytimer.a = function () { console.log("Bar!") };
delaytimer.running = true;
}
}
Timer {
id: delaytimer
interval: 1000
running: false
repeat: false
property var a: function () { console.log("will be overridden!") };
onTriggered: a()
}
}