Reputation: 5566
I'm creating a custom text input in QML. One of its configuration is that it's a field that should only accept digits I did it like this:
import QtQuick 2.6
Item {
property string vmFont: "Mono"
property string vmPlaceHolder: "Some text ..."
property bool vmNumbersOnly: false
// Qt Quick approach to make internal variables.
Item {
id: own
property string enteredText: ""
}
Rectangle {
id: lineEditRect
anchors.fill: parent
color: "#e4f1fd"
radius: 2
}
TextInput {
id: lineEdit
text: vmPlaceHolder
color: "#5499d5"
font.family: vmFont
font.pixelSize: 13
anchors.bottom: parent.bottom
//inputMethodHints: vmNumbersOnly ? Qt.ImhDigitsOnly : Qt.ImhNone
inputMethodHints: Qt.ImhDigitsOnly
verticalAlignment: TextInput.AlignVCenter
leftPadding: 10
width: lineEditRect.width
height: lineEditRect.height
onActiveFocusChanged: {
if (activeFocus){
if (own.enteredText === ""){
// Removing the placeholder
lineEdit.text = "";
}
}
}
onEditingFinished: {
own.enteredText = lineEdit.text;
if (lineEdit.text === ""){
lineEdit.text = vmPlaceHolder
}
}
}
}
However, even though that the inputMethodHits is set to Qt.ImhDigitsOnly, the text input still accepts all kinds of keypresses. What am I doing wrong?
Upvotes: 0
Views: 4145
Reputation: 100
it worked for me in any device:
TextInput {
validator: RegExpValidator{regExp: /[0-9]+/}
}
Upvotes: 0
Reputation: 24416
I think that inputMethodHints
is for virtual keyboards (e.g. mobile phone software keyboards, Qt Virtual Keyboard, etc.). For restricting input when a physical keyboard is in use (though it can also be used when a virtual keyboard is in use), you can use inputMask
and validator
. For example, the following code would allow only four digits from 0 to 9 to be entered:
TextInput {
inputMask: "9999"
}
Think of inputMethodHints
as affecting what the virtual keyboard displays and how it behaves, and these properties as affecting what the TextInput
itself allows as input.
Upvotes: 2