使用"虚拟键盘"注意 (例子的Qt版本:5.12.4)
注意一:
/* 必须在main.cpp开始处加入如下代码,否则无法使用"虚拟键盘" */
qputenv(“QT_IM_MODULE”,QByteArray(“qtvirtualkeyboard”));
注意二:
键盘大小是根据宽度自动计算的,所以,应用程序应该只设置InputPanel 的宽度和y 坐标,不能设置高度。
源码
main.cpp
1 #include <QGuiApplication>
2 #include <QQmlApplicationEngine>
3
4 int main(int argc, char *argv[])
5 {
6 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
7
8 // 必须加入否则无法使用"虚拟键盘"
9 qputenv("QT_IM_MODULE",QByteArray("qtvirtualkeyboard"));
10
11 QGuiApplication app(argc, argv);
12
13 QQmlApplicationEngine engine;
14 const QUrl url(QStringLiteral("qrc:/main.qml"));
15 QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
16 &app, [url](QObject *obj, const QUrl &objUrl) {
17 if (!obj && url == objUrl)
18 QCoreApplication::exit(-1);
19 }, Qt::QueuedConnection);
20 engine.load(url);
21
22 return app.exec();
23 }
main.qml
1 import QtQuick 2.12
2 import QtQuick.Window 2.12
3 import QtQuick.Layouts 1.12
4 import QtQuick.Controls 2.5
5
6 import QtQuick.VirtualKeyboard 2.2
7 import QtQuick.VirtualKeyboard.Settings 2.2
8
9 Window
10 {
11 id: root
12 visible: true
13 width: 800
14 height: 600
15 title: qsTr("Hello World")
16
17 ColumnLayout
18 {
19 anchors.top: parent.top
20 anchors.topMargin: root.height * 0.2
21 anchors.horizontalCenter: parent.horizontalCenter
22 spacing: 25
23
24 RowLayout
25 {
26 spacing: 25
27
28 Text
29 {
30 text: qsTr("用户名:")
31 font.family: "微软雅黑"
32 font.pixelSize: 20
33 }
34 TextField
35 {
36 placeholderText: "输入用户名.."
37 font.family: "微软雅黑"
38 font.pixelSize: 16
39 Layout.preferredWidth: root.width * 0.25
40
41 background: Rectangle
42 {
43 radius: 4
44 border.color: parent.focus ? "#498ff8" : "#C4DBFC"
45 }
46 }
47 }
48
49 RowLayout
50 {
51 spacing: 25
52
53 Text
54 {
55 text: qsTr("密 码:")
56 font.family: "微软雅黑"
57 font.pixelSize: 20
58 }
59 TextField
60 {
61 placeholderText: "输入密码.."
62 font.family: "微软雅黑"
63 font.pixelSize: 16
64 Layout.preferredWidth: root.width * 0.25
65
66 background: Rectangle
67 {
68 radius: 4
69 border.color: parent.focus ? "#498ff8" : "#C4DBFC"
70 }
71 }
72 }
73 }
74
75 InputPanel
76 {
77 id: inputPannelID
78 z: 99
79 y: root.height // 默认让其处于窗口最下方,貌似隐藏一样
80 width: root.width
81 visible: true // 一直显示
82
83 states: State
84 {
85 name: "visible"
86 when: inputPannelID.active
87 PropertyChanges
88 {
89 target: inputPannelID
90 y: root.height-inputPannelID.height
91 }
92 }
93 transitions: Transition
94 {
95 from: ""
96 to: "visible"
97 reversible: true
98 ParallelAnimation
99 {
100 NumberAnimation
101 {
102 properties: "y"
103 duration: 250
104 easing.type: Easing.InOutQuad
105 }
106 }
107 }
108
109
110 Component.onCompleted:
111 {
112 VirtualKeyboardSettings.styleName = "retro" // 复古样式
113 VirtualKeyboardSettings.wordCandidateList.alwaysVisible = true
114 VirtualKeyboardSettings.activeLocales = ["en_US","zh_CN","ja_JP"] // 英语、中文、日语 (若不设置,则语言就有很多种)
115 }
116 }
117 }