Search code examples
qtqmlqtquick2qspinbox

How to use float in a QML spinbox


I use a QML Spinbox but I have trouble to use floats in it. If I write something like value: 5.0 , it will be displayed as 5 , so as an int instead of a float.

Do you have any idea of how to proceed ?

Thanks a lot and have a good day !


Solution

  • You can create a Spinbox with custom texts

    DoubleSpinBox.qml

    import QtQuick 2.0
    
    import QtQuick.Controls 2.1
    
    Item {
        property int decimals: 2
        property real realValue: 0.0
        property real realFrom: 0.0
        property real realTo: 100.0
        property real realStepSize: 1.0
    
        SpinBox{
            property real factor: Math.pow(10, decimals)
            id: spinbox
            stepSize: realStepSize*factor
            value: realValue*factor
            to : realTo*factor
            from : realFrom*factor
            validator: DoubleValidator {
                bottom: Math.min(spinbox.from, spinbox.to)*spinbox.factor
                top:  Math.max(spinbox.from, spinbox.to)*spinbox.factor
            }
    
            textFromValue: function(value, locale) {
                return parseFloat(value*1.0/factor).toFixed(decimals);
            }
    
        }
    }
    

    Example:

    DoubleSpinBox{
        realValue: 5.0
        realStepSize: 0.01
    }
    

    enter image description here