c++qtqmlqtvirtualkeyboard

How launch Qt Virtual keyboard only for Tablet Mode in Windows


I am making an application for Windows desktops and tablets. I need to launch Qt virtual keyboard in tablet mode.

I followed this example in Qt docs

I just put one line of code in my main.cpp to get Qt virtual keyboard working

qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

But now virtual keyboard launches in desktop mode also, which is not needed. How do I restrict the Qt virtual keyboard for tablet mode only?

I am using Qt 5.9 and tried 5.12. Windows on-screen keyboard does not launch all the time when needed


Solution

  • For checking tablet mode you can use bool QWindowsWindowFunctions::isTabletMode() static function which is introduced in Qt 5.9. For enabling virtual keyboard in table mode and disabling in desktop mode you can periodically check it in a timer and show/hide InputPanel respectively:

    InputPanel {
        id: inputPanel
    
        property bool enableKeyboard: false
        ...
        states: State {
            name: "visible"
            when: enableKeyboard && inputPanel.active
            PropertyChanges {
                target: inputPanel
                y: appContainer.height - inputPanel.height
            }
        }
        ...
    }
    

    enableKeyboard property is defined to activate/deactivate keyboard and it should be updated regularly using a Timer like:

    Timer {
        onTriggered: enableKeyboard = utils.isTabletMode()
        running: true
        repeat: true
        interval: 1000
    }
    

    You should define isTabletMode function in a QObject based class like:

    #include <QtPlatformHeaders/QWindowsWindowFunctions>
    ...
    Q_INVOKABLE bool isTabletMode() {
         return QWindowsWindowFunctions::isTabletMode();
    }
    

    Do not forget to expose you class to qml by:

    qmlengine->rootContext()->setContextProperty("utils", pointerToMyClass);