虚拟键盘Qt Quick

该示例展示了如何在Qt Quick 应用程序中使用虚拟键盘。

该示例有两种实现方式:一种用于桌面平台,另一种用于嵌入式平台。前一个版本可以使用虚拟键盘在多个文本字段中输入文本,而后一个版本使用相同的用户界面,但使用自定义虚拟键盘InputPanel 。以下代码段展示了如何设置项目,以便根据 CONFIG 选项选择合适的实现:

  • 在 qmake (basic.pro) 中:
    !qtConfig(vkb-desktop) {
        DEFINES += MAIN_QML=\\\"basic-b2qt.qml\\\"
    } else {
        DEFINES += MAIN_QML=\\\"Basic.qml\\\"
    }
  • 在 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()

该示例在加载.qml 文件之前,通过设置QT_IM_MODULE 环境变量来启用虚拟键盘:

#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();
}

除此之外,它还使用自定义TextFieldTextArea 项,通过EnterKeyAction 附加属性配置[ENTER]键行为。

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)
                }
}

TextFieldTextArea 控件使用enterKeyEnabledenterKeyAction 属性扩展了各自的Qt Quick Controls 2类型。片段中的TextFieldTextArea 实例可以设置这些属性,以更改默认行为。

运行示例

运行示例 Qt Creator,打开Welcome 模式,并从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行

示例项目 @ code.qt.io

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.