问题
I want to understand the following question:
How can I store the previous value of a property in the declarative QML language?
The task is to memorize property value to another property before it change. The problem is that the existing signal mechanism onPropertyNameChanged(). This mechanism emits a signal about the property change after its modification. And in this handler it is impossible to get the previous value of the property for memorize it.
It is desirable to see code examples.
回答1:
Interesting question. The only way I see is a bit stupid:
Item {
id: item
property int prev: 0
property int temp: value
property int value: 0
onValueChanged: {
prev = temp;
temp = value;
console.log("prev=" + prev);
console.log("value=" + value)
console.log("---------------");
}
Timer {
interval: 1000
repeat: true
running: true
onTriggered: {
item.value = Math.round(Math.random() * 1000);
}
}
}
回答2:
Why not create your custom signal?
signal myValueChanged(int oldValue, int newValue)
Everytime you change the value, emit this signal:
function setValue(value) {
var previous = this.value
this.value = value
myValueChanged(previous, value)
}
onMyValueChanged: console.log(oldValue, newValue)
Component.onCompleted: setValue(10)
回答3:
why not create the buffer property yourself? eg)
property int value: 0
property int prevValue:
onValueChanged: {
... logic to deal with value change
... if you are trying to diff with prevValue, make sure check if prevValue is not undefined (first time Value changes)
prevValue = value;
}
if you are dealing with custom type "var" then you can try:
onValueChanged: {
prevValue = JSON.parse(JSON.stringify(value));
}
prevValue = JSON.parse(JSON.stringify(value));
来源:https://stackoverflow.com/questions/48442597/how-to-get-previous-property-value-before-it-changed-in-qml