———————-*.pro———————————
QT += core gui
QT += virtualkeyboard
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
—————————–mainwindow.h——————————-
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
bool eventFilter(QObject *obj, QEvent *event) override; // 事件过滤器
private:
Ui::MainWindow *ui;
private slots:
void showKeyboard(); // 点击输入框时显示键盘
};
#endif // MAINWINDOW_H
—————————–mainwindow.cpp——————————–
#include “mainwindow.h”
#include “ui_mainwindow.h”
#include
#include
#include
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 安装事件过滤器
ui->lineEdit->installEventFilter(this);
this->setFocus(); // 将焦点设置到主窗口
}
MainWindow::~MainWindow()
{
delete ui;
}
// 实现事件过滤器
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->lineEdit && event->type() == QEvent::FocusIn) {
showKeyboard(); // 点击输入框时显示键盘
}
return QMainWindow::eventFilter(obj, event);
}
void MainWindow::showKeyboard()
{
QGuiApplication::inputMethod()->show(); // 显示虚拟键盘
}
—————————–main.cpp—————————————
#include
#include
#include “mainwindow.h”
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
qputenv(“QT_IM_MODULE”, QByteArray(“qtvirtualkeyboard”));
qputenv(“QT_VIRTUALKEYBOARD_LANGUAGE”, QByteArray(“fr_FR”)); // 法语
qputenv(“QT_VIRTUALKEYBOARD_LANGUAGE”, QByteArray(“de_DE”)); // 德语
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
————————*.ui—————————————————-
添加 lineEdit