Imagine that you're developer preferring Qt, and:
- you convinced your manager to try out Qt/Qt Quick as UI framework for your custom device (cash machine, POS, ticket machine etc.) to port some old app.
- it lacks hardware and software keyboard (the original application's hardcoded its keyboard inside so you can't reuse it).
- main Qt5 modules are working on the target device (QtCore, QtGui, QtQuick)
- you have to provide demo of Qt Quick features on such device (animations, transitions, particles).
- deadline is yesterday.
- you know that if you provide some forms with text input fields and virtual keyboard along with animations and other fireworks then the status of the meeting will change from demo/POC to pre-alpha presentation :)
The main classes are QPlatformInputContext and QPlatformInputContextPlugin:
QPlatformInputContextPlugin registers QPlatformInputContext in Qt way. QPlatformInputContext on the other hand is the magic class used for implementing virtual keyboard. In our case we need to overload only few methods.
I reviewed some relevant bitsof the Qt sources to know the meaning of the virtual methods. I will explain it later. First look at QInputMethod documentation and it's Qt Quick equivalent. This class is much related to QPlatformInputContext.
- isValid() - true if the input method (eg. The virtual keyboard) is valid. We could come up with some cases where keyboard is invalid (in client server architecture for example - no connection to the server).
- keyboardRect() - virtual keyboard geometry. QGuiApplication::inputMethod()->keyboardRect() returns this value.
- showInputPanel() - this method is invoked by the internal Qt input system when any editor or widget gains focus.
- hideInputPanel() - this method is invoked by the internal Qt input system when any editor or widget loses its focus or QGuiApplication::inputMethod()->setVisible(false) is called.
- isInputPanelVisible() - true if the virtual keyboard is visible.
class MockupKeyEventDispatcher : public QObject
The whole source code is available in my kde scratch git repository under MockupVirtualKeyboard. It's pure Qt5 project. Make install command installs this plugin in $$[QT_INSTALL_PLUGINS]/platforminputcontexts directory. I have tested in on my desktop with some simple Qt Quicks projects and Qt Designer (see the screenshot). Worked as expected. To turn off this virtual keyboard you can remove plugin from the mentioned directory.
Summary:Once again I was astounded by Qt well-thought-out API and its simplicity. Actually writing this post took me more time than development of virtual keyboard. Below are some statistics that speak for themselves:
|C++ code||164 lines|
|QML code||245 lines|