-2

Doing my first steps in QML, so this might be obvious... When using a TextInput with a simple validator (say an IntValidator), is there a way to know the maximum width that TextInput field will take? As an example, if I create a IntValidator for a number from 0 to 999, I would like to find the width required to display that 999 (or whichever will be the widest, based on the font etc...). I am trying to wrap that textinput into an item which will have a fixed size, just the right size for the worst case input, nothing less, nothing more? Thanks.

Will59
  • 1,430
  • 1
  • 16
  • 37

1 Answers1

1

Use TextMetrics:

import QtQuick 2.9
import QtQuick.Controls 2.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TextMetrics {
        id: textMetrics
        font: textField.font
        text: "999"
    }

    TextField {
        id: textField
        width: textMetrics.width + leftPadding + rightPadding
        validator: IntValidator {
            bottom: 0
            top: 999
        }
    }
}
Mitch
  • 23,716
  • 9
  • 83
  • 122