Sunday, January 29, 2012

Closing virtual keyboard when pressing enter/return in QML

The stock apps on N9/N950 close the virtual keyboard on single line text edit when pressing the enter/return key on the virtual keyboard. This allows easily to see the content of the whole page without trying to aim at some area in the page that is not used for input.

Unfortunately, when you create UIs with QML this is not the default behavior. With some help from IRC #harmattan channel and some googling, this is how I got it to work:

TextField {
    Keys.onReturnPressed: {
        platformCloseSoftwareInputPanel()
    }
}

Now the virtual keyboard is closed. But there is still one issue. The keyboard is closed, but the text input still retains focus. If you try clicking on the text field again to start typing, nothing happens. You will have to click somewhere else, so that it loses focus, and then click again the text field. The stock applications make the input field lose focus when the virtual keyboard is closed.

This was a little more hackish to implement. TextField contains a TextInput, which has focus property. But unfortunately TextField does not contain an alias for that property, so you can't just simply set focus = false for the TextField. This kind of rather ugly workaround does the job:

TextField {
    Keys.onReturnPressed: {
        platformCloseSoftwareInputPanel()
        dummy.focus = true
    }
}
// This is just a dummy invisible item that takes the focus when virtual keyboard is closed
Item { id: dummy }