How to validate Qml property value before assigning?

2.1k Views Asked by At

Element.qml

Item{
    property int step
    property int minValue
    property int maxValue
    property int value  //should accept values of form i*step+minValue
}

main.qml

Element{
    step:2
    minValue:-7
    maxValue:7
    value:0  //not an acceptable  value(2*i-7), should convert to 1 or -1
}

If I set the value, it should convert the value to nearest step*i+minValue, i.e. 0 to 1 and then emit valueChanged().

I want the valueChanged() signal to be emitted only when its value is step*i+minValue.

2

There are 2 best solutions below

0
folibis On

As far as I know there is no way to set a property validator. A possible workaround is shown below. Consider for instance a property that accepts only positive numbers. Such a property can be coded as follows:

Item {
    property int value: 0
    property int _value: 0
    on_ValueChanged: {
        if(_value > 0)
            value = _value;
    }
}

The same approach can be used in C++, if Item is your custom class.

0
Mido On

You cant do a pre test and on it the valueChanged signal will be sent. the only solution is to do the test in the onValueChanged slot and send a custom signal, you most not send valueChanged() sigal cause it's connected to the onValueChanged Slot.

import QtQuick 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.2

Item{
    property int step :2
    property int minValue :-7
    property int maxValue: 7
    property int value: 0  //should accept values of form i*step+minValue

    signal sgnValueChanged(int value)

    Column{

        TextInput{
            id:input
            width: 100
            height: 20
        }

        Rectangle{
            id:button
            width: 100
            height: 20
            color:"#f0ffff"
            MouseArea{
                anchors.fill:parent
                onClicked:
                {
                    value = parseInt(input.text)

                }
            }
        }
    }

    onValueChanged:
    {
        if(value >= minValue && value <= maxValue)
        {
            sgnValueChanged(step * value + minValue)
        }

        else
        {
            console.log("not acceptable value")
        }
    }
}