Qt Quick 虚拟键盘

This example shows how to use the virtual keyboard in a Qt Quick application.

范例有 2 个实现:一个用于桌面平台,另一用于嵌入式平台。前一版本允许使用虚拟键盘将文本输入到多个文本字段,而后一版本使用相同 UI (用户界面) 但采用自定义虚拟键盘 InputPanel . The following snippets show how to set up the project to choose the appropriate implementation based on the CONFIG options:

  • In qmake ( basic.pro ):
    !qtConfig(vkb-desktop) {
    DEFINES += MAIN_QML=\\\"basic-b2qt.qml\\\"
    } else {
    DEFINES += MAIN_QML=\\\"Basic.qml\\\"
    }
    								
  • In CMake ( CMakeLists.txt ):
    if(NOT QT_FEATURE_vkb_desktop)
    target_compile_definitions(basic PUBLIC
    MAIN_QML="basic-b2qt.qml"
    )
    endif()
    ...
    if(QT_FEATURE_vkb_desktop)
    target_compile_definitions(basic PUBLIC
    MAIN_QML="Basic.qml"
    )
    endif()
    								

范例启用虚拟键盘通过设置 QT_IM_MODULE 环境变量先于加载 .qml 文件:

#include <QQuickView>
#include <QGuiApplication>
#include <QQmlEngine>
int main(int argc, char *argv[])
{
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
    QGuiApplication app(argc, argv);
    QQuickView view(QString("qrc:/%2").arg(MAIN_QML));
    if (view.status() == QQuickView::Error)
        return -1;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.show();
    return app.exec();
}
						

除此外,它使用自定义 TextField and TextArea 项以配置 [ENTER] 键行为使用 EnterKeyAction 附加特性。

import QtQuick
import QtQuick.Controls
import QtQuick.VirtualKeyboard
import "content"
Rectangle {
    ...
                TextField {
                    width: parent.width
                    placeholderText: "One line field"
                    enterKeyAction: EnterKeyAction.Next
                    onAccepted: passwordField.focus = true
                }
    ...
                TextArea {
                    id: textArea
                    width: parent.width
                    placeholderText: "Multiple line field"
                    height: Math.max(206, implicitHeight)
                }
}
						

The TextField and TextArea 控件分别扩展 Qt Quick Controls 2 类型采用 enterKeyEnabled and enterKeyAction 特性。 TextField and TextArea 实例片段可以将这些特性设为更改默认行为。

运行范例

要运行范例从 Qt Creator ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,见 Qt Creator: Tutorial: Build and run .

范例工程 @ code.qt.io