Search code examples
qtqmlqtquick2qtquickcontrols2

How to set alignment for SpinBox in QtControls 2.0?


The text alignment for text in my SpinBox is centered by default. The SpinBox documentation states that there is a horizontalAlignment property, but when I try to specify the horizontal alignment, I get the following error:

Invalid property name "horizontalAlignment". (M16)

My full SpinBox code is here:

SpinBox {
    editable: true
    horizontalAlignment: Qt.AlignLeft
    from: 1
    to: 10000
    value: model.numberOfElements
}

How would I go about aligning text in a SpinBox in Qt Controls 2.0?


Solution

  • First of all the link of the docs that you point out is from SpinBox of Qt Quick Controls 1, the link of Qt Quick Controls 2 is: https://doc.qt.io/qt-5/qml-qtquick-controls2-spinbox.html.

    Considering the above Qt Quick Controls 2 has a docs that indicates how to customize the controls: Customizing Qt Quick Controls 2.

    In the case of SpinBox the solution is:

    import QtQuick.Controls 2.5
    
    SpinBox {
        id: control
        value: 50
        editable: true
        contentItem: TextInput {
            z: 2
            text: control.textFromValue(control.value, control.locale)
    
            font: control.font
            color: "#21be2b"
            selectionColor: "#21be2b"
            selectedTextColor: "#ffffff"
            horizontalAlignment: Qt.AlignLeft
            verticalAlignment: Qt.AlignVCenter
    
            readOnly: !control.editable
            validator: control.validator
            inputMethodHints: Qt.ImhFormattedNumbersOnly
        }
    }