Saturday, April 28, 2012

Showing numerical virtual keyboard in QML

Getting the virtual keyboard to show in numerical input mode is not hard, but perhaps poorly documented.

Here's an example code how to do it:

TextField {
    inputMethodHints: Qt.ImhDigitsOnly
    validator: RegExpValidator { regExp: /\d*/ }

The above code allows unlimited amount of numbers to be entered, yet allows for an empty field.

If you want the field to have at least one to three numbers entered, something like this can be used:

TextField {
    inputMethodHints: Qt.ImhDigitsOnly
    validator: RegExpValidator { regExp: /\d{1,3}/ }

If the field is empty, you'll notice its border is red - as a mark that it is invalid input. This won't prevent the user to leave the field empty though. It's application specific how to handle such a case: whether to display a warning, an error, or preventing leaving the page.

The basic operation is nevertheless this:

  • inputMethodHints instructs the virtual keyboard to open in numerical mode only.
  • validator is used to match the key presses to the regular expression pattern, so that unwanted input can not be entered to the field. As a practical example, the numerical keyboard on harmattan allows entering characters such as '+', '-' and '.'. Validator can be used to disallow those, as has been done in above examples.

No comments:

Post a Comment