Custom component bindings
-
I am trying to implement a DoubleField component for input and output of floating point numbers. It should behave like a TextField with a DoubleValidator but also have a property value of type double that holds the current value. It should be possible to use it as follows:
DoubleField { precision: 2 value: foo onValueChanged: foo = value }I tried the following implementation:
// DoubleField.qml import QtQuick import QtQuick.Controls TextField { property double value property int precision validator: DoubleValidator{} onEditingFinished: value = parseFloat(text) onValueChanged: text = value.toFixed(precision) }However, this does not work. The problem is that when you assign to value in onEdititingFinished, then the bindning value: foo is broken.
Is there a way to make DoubleField work? After all, I am just trying to make DoubleField work exactly the same way as QtQuick controls such as Slider.
Here is a link to a small test app. It show a window with two examples:
-
Two Slider instances that control the same property. (Works fine. If you move either of the two sliders, then the other one is automatically updated.)
-
A Slider and a DoubleField that control the same property. (Does not work. If you first enter a value in the DoubleField and then move the Slider, then the DoubleField is not updated, because the binding has been broken.)
Thank you
Johan Råde -
-
You need to set the value and restore old binding. You can try some thing like follows.
TextField { id : _t4 property double value; property int precision; property bool editStart:false; validator: DoubleValidator{} onEditingFinished: { editStart = true editStart = false; } onValueChanged: { console.log(" onValueChanged") text = value.toFixed(precision) } Binding { target: _t4; property: 'value' value: parseFloat(_t4.text); when: _t4.editStart restoreMode :Binding.RestoreBinding } } -
You need to set the value and restore old binding. You can try some thing like follows.
TextField { id : _t4 property double value; property int precision; property bool editStart:false; validator: DoubleValidator{} onEditingFinished: { editStart = true editStart = false; } onValueChanged: { console.log(" onValueChanged") text = value.toFixed(precision) } Binding { target: _t4; property: 'value' value: parseFloat(_t4.text); when: _t4.editStart restoreMode :Binding.RestoreBinding } }@dheerendra
Your solution works perfectly.
As an extra benefit, I learnt a lot by studying your code.
Thank you so much! 🙏 -
J Johan_R has marked this topic as solved on