qtqmlqspinboxspinbox

QML - SpinBox - how to know if it's UP or DOWN pressed


I'm trying to create a custom CustomSpinBox in QML and I want to increase or decrease the value from stepSize based on which button is going to be pressed. For example, if I am pressing the UP button I want to increase the value by X and if I am pressing the DOWN button I want to decrease the value by Y.

I know about up.pressed and down.pressed but those are just properties, how can I get their value inside on stepSize function?

CustomSpinBox.qml

CustomSpinBox{
....
}

Usage:

CustomSpinBox{
    id: maximumSpeed


    maximumValue: 100
    minimumValue: 0.01
    suffix: " " + qsTr("m/s")
    decimals: 3
    value: connection && connection.maxSpeed.value > 0 ? connection.maxSpeed.value : 1.5
    enabled: idOverrideDefault.checked

    stepSize: {
        // if UP is pressed return UP_VALUE
        // if DOWN is pressed return DOWN_VALUE
    }

    onValueChanged: {
        if (connection) {
            editor.handleSpeedRestriction(idOverrideDefault.checked, value)
        }
    }
}

UPDATE:

Well, I have a number, for example, 1. If you will press the UP button is going to become 2, 3, 4, and so on. But If you will press the DOWN button it will become 0.9, 0.8, 0.7 .... 0.1 if you will press again the DOWN button it will become 0.09, 0.08, ... 0.01. The problem that I have is that I don't know how can I achieve something like this without knowing whether is going to go UP or DOWN.

I mean for example if my value is 1 I want that if I will press UP my stepSize to be 1, but if I will press DOWN to be 0.1 The same if my value will be 0.1, if I will press UP then my stepSize should be 0.1 but if I will press DOWN should be 0.01.

Because of this problem I need to know which button is pressed at each time.

Also if I am trying to write maximumSpeed.up.pressed is going to give me this error message: Cannot read property 'pressed' of undefined Also if I am going to define my property insider of CustomSpinBox for example something like this property bool isUp: root.up.pressed then this is never going to be updated so I will always have a false over there.


Solution

  • You should use property group syntax as :

    SpinBox
    {
        property bool isUpPressed: up.pressed
        property bool isDownPresed: down.pressed
    
        up.onPressedChanged: {
            isUpPressed = up.pressed
        }
        down.onPressedChanged: {
            isDownPresed = down.pressed
        }
    }
    

    for Quick.Controls 1. where up and down are not available, this trick can be used :

       SpinBox
        {
            property int oldValue: -1
          
            onValueChanged: {
                if (value > oldValue)
                {
                    console.log("up")
                }
                else
                {
                    console.log("down")
                }
                oldValue = value
            }
        }