QT自制软键盘 最完美、最简单、支持中文输入(二)

目录

一、前言

二、本自制虚拟键盘特点

三、中文输入原理

四、组合键输入

五、键盘事件模拟

六、界面

 七、代码

7.1 frmKeyBoard 头文件代码

7.2 frmKeyBoard 源文件代码

八、使用示例

九、效果

十、结语


一、前言

        由于系统自带虚拟键盘不一定好用,也不一定好看,有的按键太小,有的电脑上可能没有自带的软键盘,干脆直接自己设计一个。        

        在现代的用户界面设计中,屏幕键盘是一种重要的辅助工具,特别是在触摸屏设备上。本文将深入解析一个使用Qt框架自制的屏幕键盘,具有丰富的功能和用户友好的界面,支持中文输入、组合键操作等多种特性。

        之前写过一篇不带中文的屏幕键盘,本文在该基础上升级部分功能:QT自制软键盘 最完美、最简单、跟自带虚拟键盘一样(一)

二、本自制虚拟键盘特点

1.支持中文输入。

2.支持组合键,例如“Ctrl+C”复制粘贴操作。

3.键盘界面保持在所有界面最上方。

4.点击键盘按钮不会改变底层文本输入框焦点。

5.通过模拟键盘点击事件完成键盘输入文本信息。

6.包含各种键盘自带符号输入。

7.长按按键可以持续重复输入键盘内容。

三、中文输入原理

        资源中包含了“PinYin_Chinese.txt”文本文件,文件内容为七千多个汉字以及对应的拼音,通过加载中文拼音数据,实现了基于拼音的中文输入。在用户输入拼音时,屏幕键盘匹配对应的汉字词组,并显示在候选列表中。

加载中文汉字代码:

void frmKeyBoard::loadChineseFontData()
{QFile pinyin(":/PinYin_Chinese.txt");if (!pinyin.open(QIODevice::ReadOnly)) {qDebug() << "Open pinyin file failed!";return;}while (!pinyin.atEnd()) {QString buf = QString::fromUtf8(pinyin.readLine()).trimmed();if (buf.isEmpty())continue;/* 去除#号后的注释内容 */if (buf.left(1) == "#")continue;buf=buf.replace("\t"," ");QString pinyin = buf.mid(1,buf.size() - 1);QString word = buf.mid(0,1);QString abb;QStringList pinyinList = pinyin.split(" ");for (int i = 0; i < pinyinList.count(); i++) {/* 获得拼音词组的首字母(用于缩写匹配) */abb += pinyinList.at(i).left(1);}QList<QPair<QString, QString>> &tmp = m_data[pinyin.left(1)];/* 将'拼音(缩写)'和'词组'写入匹配容器 */tmp.append(qMakePair(abb, word));/* 将'拼音(全拼)'和'词组'写入匹配容器 */tmp.append(qMakePair(pinyin.remove(" "), word));}qDebug() << m_data.size();pinyin.close();
}

点击列表选择汉字输入:

void frmKeyBoard::on_listWidget_itemClicked(QListWidgetItem *item)
{QKeyEvent keyPress(QEvent::KeyPress, 0, m_curModifier, item->text().right(1));QKeyEvent keyRelease(QEvent::KeyRelease, 0, m_curModifier, item->text().right(1));QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();
}

 另外,点击汉字对应的数字、点击空格都可以输入汉字,点击回车输入对应的英文字母,部分关键代码:


void frmKeyBoard::slotKeyButtonClicked()
{QPushButton* pbtn = (QPushButton*)sender();QString objectName = pbtn->objectName();if (pbtn->text().contains("Backspace")) {if(isChinese){if(recordLitterBuf.size() > 0){recordLitterBuf.remove(recordLitterBuf.size() - 1, 1);findChineseFontData(recordLitterBuf);if(!m_labelShowPinyin->text().isEmpty())m_labelShowPinyin->setText(recordLitterBuf);}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Backspace, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Backspace, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if(pbtn->text() == "Space") {if(isChinese){if(ui.listWidget->count() > 0){//按下空格输入列表第一汉字on_listWidget_itemClicked(ui.listWidget->item(0));}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Space, m_curModifier, " ");QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Space, m_curModifier, " ");QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text().contains("Enter")) {        if(isChinese){if(!m_labelShowPinyin->text().isEmpty()){//按下回车输入拼音字母QKeyEvent keyPress(QEvent::KeyPress, 0, m_curModifier, m_labelShowPinyin->text());QKeyEvent keyRelease(QEvent::KeyRelease, 0,m_curModifier, m_labelShowPinyin->text());QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Enter, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Enter, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text().contains("Shift")) {if (pbtn->isChecked()) {isChinese = true;m_curModifier = Qt::ShiftModifier;for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toUpper());}}else {isChinese = false;ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();m_curModifier = Qt::NoModifier;for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toLower());}}QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Shift, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Shift, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}
//......else {QString symbol;if (ui.pushButton_shift->isChecked())symbol = pbtn->text().split("\n").at(0);elsesymbol = pbtn->text().split("\n").at(1);QKeyEvent keyPress(QEvent::KeyPress, m_mapSymbolKeys.value(symbol), m_curModifier, symbol);QKeyEvent keyRelease(QEvent::KeyRelease, m_mapSymbolKeys.value(symbol), m_curModifier, symbol);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}
}

四、组合键输入

       4.1 定义m_curModifier 记录当前键盘模式。

Qt::KeyboardModifier m_curModifier = Qt::NoModifier;

       4.2 特殊按键选中时切换对应的按键模式 

if (pbtn->text().contains("Ctrl")) {if(pbtn->isChecked())m_curModifier = Qt::ControlModifier;elsem_curModifier = Qt::NoModifier;QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Control, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Control, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}

五、键盘事件模拟

        通过模拟键盘事件,实现了对底层文本输入框的模拟输入。这样,用户可以在使用屏幕键盘的同时,保持对其他界面元素的操作。

QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Enter, m_curModifier);
QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Enter, m_curModifier);
QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);
QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);

        另外,通过qApp->focusWidget()获取当前焦点所在的窗口,可以将键盘模拟输入到各个窗口的输入框中。

六、界面

界面新增了一个QListWidget用于显示候选汉字列表,列表方向从左至右。

 七、代码

7.1 frmKeyBoard 头文件代码

#pragma once
#pragma execution_character_set("utf-8")#include <QDialog>
#include "ui_frmKeyBoard.h"
#include <QPushButton>
#include <QKeyEvent>
#include <QDebug>
#include <QStyle>
#include <QListWidgetItem>
#include <QLabel>
#include <QVBoxLayout>
#include <QToolTip>class frmKeyBoard : public QDialog
{Q_OBJECTpublic:frmKeyBoard(QWidget *parent = nullptr);~frmKeyBoard();void initFocusWidget(QWidget*);private slots:void slotKeyButtonClicked();void slotKeyLetterButtonClicked();void slotKeyNumberButtonClicked();void on_listWidget_itemClicked(QListWidgetItem *item);void on_toolButton_lastPage_clicked();void on_toolButton_nextPage_clicked();private:Ui::frmKeyBoardClass ui;void initFrm();void initStyleSheet();void loadChineseFontData();void findChineseFontData(QString text);void addOneItem(QString text);QMap<QString, QList<QPair<QString, QString>>> m_data;bool isChinese = false;QString recordLitterBuf;QVector<QPushButton*> m_letterKeys;QVector<QPushButton*> m_NumberKeys;QMap<QString, Qt::Key> m_mapSymbolKeys;QStringList m_showTextList;int m_curPage = 0;QLabel* m_labelShowPinyin;Qt::KeyboardModifier m_curModifier = Qt::NoModifier;
};

7.2 frmKeyBoard 源文件代码

#include "frmKeyBoard.h"frmKeyBoard::frmKeyBoard(QWidget *parent): QDialog(parent)
{ui.setupUi(this);this->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus);this->setWindowTitle("屏幕键盘(源客V)");this->setWindowModality(Qt::WindowModal);this->setAttribute(Qt::WA_DeleteOnClose);this->initFrm();this->initStyleSheet();this->loadChineseFontData();
}frmKeyBoard::~frmKeyBoard()
{
}void frmKeyBoard::initFrm()
{m_letterKeys.clear();m_NumberKeys.clear();QList<QPushButton*> pbtns = this->findChildren<QPushButton*>();foreach(QPushButton * pbtn, pbtns) {pbtn->setAutoRepeat(true);    //允许自动重复pbtn->setAutoRepeatDelay(500);//设置重复操作的时延if (pbtn->text() >= 'a' && pbtn->text() <= 'z') {connect(pbtn, &QPushButton::clicked, this, &frmKeyBoard::slotKeyLetterButtonClicked);m_letterKeys.push_back(pbtn);}else if (pbtn->text().toInt() > 0 && pbtn->text().toInt() <= 9 || pbtn->text() == "0") {connect(pbtn, &QPushButton::clicked, this, &frmKeyBoard::slotKeyNumberButtonClicked);m_NumberKeys.push_back(pbtn);}else{connect(pbtn, &QPushButton::clicked, this, &frmKeyBoard::slotKeyButtonClicked);}}//添加label显示拼音m_labelShowPinyin = new QLabel();QVBoxLayout* vLayout = new QVBoxLayout();vLayout->addWidget(m_labelShowPinyin);vLayout->addStretch();ui.listWidget->setLayout(vLayout);m_mapSymbolKeys.insert("~", Qt::Key_AsciiTilde);m_mapSymbolKeys.insert("`", Qt::Key_nobreakspace);m_mapSymbolKeys.insert("-", Qt::Key_Minus);m_mapSymbolKeys.insert("_", Qt::Key_Underscore);m_mapSymbolKeys.insert("+", Qt::Key_Plus);m_mapSymbolKeys.insert("=", Qt::Key_Equal);m_mapSymbolKeys.insert(",", Qt::Key_Comma);m_mapSymbolKeys.insert(".", Qt::Key_Period);m_mapSymbolKeys.insert("/", Qt::Key_Slash);m_mapSymbolKeys.insert("<", Qt::Key_Less);m_mapSymbolKeys.insert(">", Qt::Key_Greater);m_mapSymbolKeys.insert("?", Qt::Key_Question);m_mapSymbolKeys.insert("[", Qt::Key_BracketLeft);m_mapSymbolKeys.insert("]", Qt::Key_BracketRight);m_mapSymbolKeys.insert("{", Qt::Key_BraceLeft);m_mapSymbolKeys.insert("}", Qt::Key_BraceRight);m_mapSymbolKeys.insert("|", Qt::Key_Bar);m_mapSymbolKeys.insert("\\", Qt::Key_Backslash);m_mapSymbolKeys.insert(":", Qt::Key_Colon);m_mapSymbolKeys.insert(";", Qt::Key_Semicolon);m_mapSymbolKeys.insert("\"", Qt::Key_QuoteLeft);m_mapSymbolKeys.insert("'", Qt::Key_Apostrophe);
}void frmKeyBoard::initStyleSheet()
{QString qss;qss += "QWidget{ background-color:rgb(26,26,26)}";    qss += "QToolButton{ color:white; font:bold 11pt;}";qss += "QLabel{ color:white; font:13pt;}";qss += "QListWidget{ color:white; border:none; padding-bottom:10px; }";qss += "QListWidget::item:hover,QListWidget::item:selected{font:bold; color:yellow; background-color:rgba(0,0,0,0)}";qss += "QPushButton{ color:white; background-color:rgb(51,51,51); height:50px; font-size:bold 15pt; border:1px solid rgb(26,26,26); border-radius: 0px; min-width:50px;}";qss += "QPushButton:hover{background-color:rgb(229,229,229); color:black;}";qss += "QPushButton:pressed,QPushButton:checked{background-color:rgb(0,118,215);}";qss += "#pushButton_closeKeyboard{background-color:rgba(0,0,0,0); border:0px}";qss += "#pushButton_closeKeyboard:hover{background-color:#b30220;}";qss += "#pushButton_space{min-width:500px;}";qss += "#pushButton_backspace,#pushButton_shift{min-width:100px;}";qss += "#pushButton_enter{min-width:120px;}";qss += "#pushButton_tab,#pushButton_ctrl{min-width:70px;}";qss += "#pushButton_capsLock{min-width:80px;}";qss += "#pushButton_up{min-width:150px;}";this->setStyleSheet(qss);
}void frmKeyBoard::loadChineseFontData()
{QFile pinyin(":/PinYin_Chinese.txt");if (!pinyin.open(QIODevice::ReadOnly)) {qDebug() << "Open pinyin file failed!";return;}while (!pinyin.atEnd()) {QString buf = QString::fromUtf8(pinyin.readLine()).trimmed();if (buf.isEmpty())continue;/* 去除#号后的注释内容 */if (buf.left(1) == "#")continue;buf=buf.replace("\t"," ");QString pinyin = buf.mid(1,buf.size() - 1);QString word = buf.mid(0,1);QString abb;QStringList pinyinList = pinyin.split(" ");for (int i = 0; i < pinyinList.count(); i++) {/* 获得拼音词组的首字母(用于缩写匹配) */abb += pinyinList.at(i).left(1);}QList<QPair<QString, QString>> &tmp = m_data[pinyin.left(1)];/* 将'拼音(缩写)'和'词组'写入匹配容器 */tmp.append(qMakePair(abb, word));/* 将'拼音(全拼)'和'词组'写入匹配容器 */tmp.append(qMakePair(pinyin.remove(" "), word));}qDebug() << m_data.size();pinyin.close();
}void frmKeyBoard::findChineseFontData(QString text)
{QString lowerText = text.toLower();m_labelShowPinyin->setText(lowerText);for (int i = 0; i < ui.listWidget->count(); i++) {QListWidgetItem *item = ui.listWidget->takeItem(i);delete item;item = NULL;}ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;if(lowerText.count() <= 0)return;const QList<QPair<QString, QString> > &tmp = m_data[lowerText.left(1)];bool fond = false;for (int i = 0; i < tmp.count(); i++) {const QPair<QString, QString> &each = tmp.at(i);if (each.first.left(lowerText.count()) != lowerText)continue;fond = true;addOneItem(each.second);m_showTextList.push_back(each.second);}if(!fond){if(recordLitterBuf.count() > 1){recordLitterBuf = recordLitterBuf.right(1);findChineseFontData(recordLitterBuf);}else{QKeyEvent keyPress(QEvent::KeyPress, int(recordLitterBuf.at(0).toLatin1()), m_curModifier, recordLitterBuf);QKeyEvent keyRelease(QEvent::KeyRelease, int(recordLitterBuf.at(0).toLatin1()), m_curModifier, recordLitterBuf);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}
}void frmKeyBoard::addOneItem(QString text)
{if(ui.listWidget->count() >= 9)return;QString itemText = QString("%1.%2").arg(ui.listWidget->count() + 1).arg(text);QListWidgetItem *item = new QListWidgetItem(itemText);QFont font;font.setPointSize(15);font.setBold(true);font.setWeight(50);item->setFont(font);/* 设置文字居中 */item->setTextAlignment(Qt::AlignBottom | Qt::AlignHCenter);bool isChineseFlag = QRegExp("^[\u4E00-\u9FA5]+").indexIn(text.left(1)) != -1;int width = font.pointSize();if (isChineseFlag)width += itemText.count()*font.pointSize()*1.5;elsewidth += itemText.count()*font.pointSize()*2/3;item->setSizeHint(QSize(width, 50));ui.listWidget->addItem(item);
}void frmKeyBoard::slotKeyButtonClicked()
{QPushButton* pbtn = (QPushButton*)sender();QString objectName = pbtn->objectName();if (pbtn->text().contains("Backspace")) {if(isChinese){if(recordLitterBuf.size() > 0){recordLitterBuf.remove(recordLitterBuf.size() - 1, 1);findChineseFontData(recordLitterBuf);if(!m_labelShowPinyin->text().isEmpty())m_labelShowPinyin->setText(recordLitterBuf);}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Backspace, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Backspace, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text().contains("Caps")) {if (pbtn->isChecked()) {for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toUpper());}}else {for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toLower());}}}else if(pbtn->text() == "Space") {if(isChinese){if(ui.listWidget->count() > 0){on_listWidget_itemClicked(ui.listWidget->item(0));}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Space, m_curModifier, " ");QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Space, m_curModifier, " ");QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text().contains("Tab")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Tab, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Tab, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("Enter")) {        if(isChinese){if(!m_labelShowPinyin->text().isEmpty()){QKeyEvent keyPress(QEvent::KeyPress, 0, m_curModifier, m_labelShowPinyin->text());QKeyEvent keyRelease(QEvent::KeyRelease, 0,m_curModifier, m_labelShowPinyin->text());QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();}}else{QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Enter, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Enter, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text().contains("Shift")) {if (pbtn->isChecked()) {isChinese = true;m_curModifier = Qt::ShiftModifier;for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toUpper());}}else {isChinese = false;ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();m_curModifier = Qt::NoModifier;for (auto pbtnKey : m_letterKeys) {pbtnKey->setText(pbtnKey->text().toLower());}}QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Shift, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Shift, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("Ctrl")) {if(pbtn->isChecked())m_curModifier = Qt::ControlModifier;elsem_curModifier = Qt::NoModifier;QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Control, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Control, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("Win")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Menu, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Menu, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("Alt")) {if(pbtn->isChecked())m_curModifier = Qt::AltModifier;elsem_curModifier = Qt::NoModifier;QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Alt, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Alt, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("↑")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Up, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Up, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("↓")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Down, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Down, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("←")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Left, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Left, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else if (pbtn->text().contains("→")) {QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Right, m_curModifier);QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Right, m_curModifier);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}else {QString symbol;if (ui.pushButton_shift->isChecked())symbol = pbtn->text().split("\n").at(0);elsesymbol = pbtn->text().split("\n").at(1);QKeyEvent keyPress(QEvent::KeyPress, m_mapSymbolKeys.value(symbol), m_curModifier, symbol);QKeyEvent keyRelease(QEvent::KeyRelease, m_mapSymbolKeys.value(symbol), m_curModifier, symbol);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}
}void frmKeyBoard::slotKeyLetterButtonClicked()
{QPushButton* pbtn = (QPushButton*)sender();if (pbtn->text() >= 'a' && pbtn->text() <= 'z') {if(isChinese){recordLitterBuf+=pbtn->text().toLower();findChineseFontData(recordLitterBuf);}else{ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();QKeyEvent keyPress(QEvent::KeyPress, int(pbtn->text().at(0).toLatin1()) - 32, m_curModifier, pbtn->text());QKeyEvent keyRelease(QEvent::KeyRelease, int(pbtn->text().at(0).toLatin1()) - 32, m_curModifier, pbtn->text());QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}else if (pbtn->text() >= 'A' && pbtn->text() <= 'Z') {if(isChinese){recordLitterBuf+=pbtn->text().toLower();findChineseFontData(recordLitterBuf);}else{ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();QKeyEvent keyPress(QEvent::KeyPress, int(pbtn->text().at(0).toLatin1()), m_curModifier, pbtn->text());QKeyEvent keyRelease(QEvent::KeyRelease, int(pbtn->text().at(0).toLatin1()), m_curModifier, pbtn->text());QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);}}if (ui.pushButton_ctrl->isChecked())ui.pushButton_ctrl->setChecked(false);if (ui.pushButton_win->isChecked())ui.pushButton_win->setChecked(false);if (ui.pushButton_alt->isChecked())ui.pushButton_alt->setChecked(false);m_curModifier = Qt::NoModifier;
}void frmKeyBoard::slotKeyNumberButtonClicked()
{QPushButton* pbtn = (QPushButton*)sender();int num = pbtn->text().toInt();if(isChinese){if(num > 0 && num < 9 && ui.listWidget->count() >= num){on_listWidget_itemClicked(ui.listWidget->item(num - 1));}}else {QKeyEvent keyPress(QEvent::KeyPress, num + 48, m_curModifier, pbtn->text());QKeyEvent keyRelease(QEvent::KeyRelease, num + 48, m_curModifier, pbtn->text());QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);if (ui.pushButton_ctrl->isChecked())ui.pushButton_ctrl->setChecked(false);if (ui.pushButton_win->isChecked())ui.pushButton_win->setChecked(false);if (ui.pushButton_alt->isChecked())ui.pushButton_alt->setChecked(false);}m_curModifier = Qt::NoModifier;
}void frmKeyBoard::on_listWidget_itemClicked(QListWidgetItem *item)
{QKeyEvent keyPress(QEvent::KeyPress, 0, m_curModifier, item->text().right(1));QKeyEvent keyRelease(QEvent::KeyRelease, 0, m_curModifier, item->text().right(1));QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyPress);QApplication::sendEvent(qApp->focusWidget() == nullptr ? this : qApp->focusWidget(), &keyRelease);ui.listWidget->clear();m_showTextList.clear();m_curPage = 0;m_labelShowPinyin->clear();recordLitterBuf.clear();
}void frmKeyBoard::on_toolButton_lastPage_clicked()
{if(m_curPage <= 0)return;m_curPage--;ui.listWidget->clear();for (int i = m_curPage * 9; i < m_curPage * 9 + 9; i++) {if(i >= m_showTextList.count())break;addOneItem(m_showTextList.at(i));}
}void frmKeyBoard::on_toolButton_nextPage_clicked()
{if(m_curPage >= m_showTextList.count() / 9)return;m_curPage++;ui.listWidget->clear();for (int i = m_curPage * 9; i < m_curPage * 9 + 9; i++) {if(i >= m_showTextList.count())break;addOneItem(m_showTextList.at(i));}
}

八、使用示例

MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);this->setWindowTitle("屏幕键盘测试(源客V)");QHBoxLayout* layout = new QHBoxLayout();layout->setContentsMargins(0, 0, 0, 0);layout->addWidget(ui->pushButton, 0, Qt::AlignRight);ui->lineEdit->setLayout(layout);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{frmKeyBoard* keyBoard = new frmKeyBoard();keyBoard->show();
}

九、效果

Qt自制虚拟键盘2(支持中文)

十、结语

        通过深度解析,我们更全面地了解了这个使用Qt框架自制的屏幕键盘。其设计理念、功能特点和实现原理展示了在用户界面开发中如何灵活运用Qt框架,为用户提供强大而友好的输入方式。对于需要在触摸屏设备上提供良好用户体验的应用,这个自制的屏幕键盘提供了一种出色的解决方案。

前序文章:QT自制软键盘 最完美、最简单、跟自带虚拟键盘一样(一)

源码资源:Qt自制虚拟键盘(支持中文) 

本方案已经能满足屏幕键盘输入的大部分需求了,还有不足的地方欢迎大家留言补充。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/249942.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

政安晨的机器学习笔记——演绎一个TensorFlow官方的Keras示例(对服装图像进行分类,很全面)

导语 Keras是一个高级API接口&#xff0c;用于构建和训练神经网络模型。它是TensorFlow的一部分&#xff0c;提供了一种简洁、直观的方式来创建深度学习模型。 Keras的主要特点如下&#xff1a; 简洁易用&#xff1a;Keras提供了一组简单的函数和类&#xff0c;使模型的创建和…

深⼊理解指针1(指针和数组)

⽬录 1. 数组名的理解 2. 使⽤指针访问数组 3. ⼀维数组传参的本质 4. 冒泡排序 5. ⼆级指针 6. 指针数组 7. 指针数组模拟⼆维数组 正文开始&#xff1a; 1.数组名的理解 首先我们已经知道应该如何用指针来访问数组 #define _CRT_SECURE_NO_WARNINGS #include <…

Pytest中doctests的测试方法应用

在 Python 的测试生态中,Pytest 提供了多种灵活且强大的测试工具。其中,doctests 是一种独特而直观的测试方法,通过直接从文档注释中提取和执行测试用例,确保代码示例的正确性。本文将深入介绍 Pytest 中 doctests 的测试方法,包括基本用法和实际案例,以帮助你更好地利用…

Task05:PPO算法

本篇博客是本人参加Datawhale组队学习第五次任务的笔记 【教程地址】https://github.com/datawhalechina/joyrl-book 【强化学习库JoyRL】https://github.com/datawhalechina/joyrl/tree/main 【JoyRL开发周报】 https://datawhale.feishu.cn/docx/OM8fdsNl0o5omoxB5nXcyzsInGe…

微服务—RabbitMQ

目录 初识MQ 同步和异步通讯 同步通讯的优缺点 异步调用方案 异步通信优缺点 常见MQ技术对比 RabbitMQ快速入门 安装RabbitMQ RabbitMQ整体架构与相关概念 常见消息模型​编辑 入门案例 SpringAMQP 基本介绍 SpringAMQP案例——模拟HelloWorld消息模型 Sprin…

如何在Shopee平台上进行手机类目选品?

在Shopee平台上进行手机类目的选品是一个关键而复杂的任务。卖家需要经过一系列的策略和步骤&#xff0c;以确保选品的成功和销售业绩的提升。下面将介绍一些有效的策略&#xff0c;帮助卖家在Shopee平台上进行手机类目选品。 先给大家推荐一款shopee知虾数据运营工具知虾免费…

ffmpeg合成mp3音频,解决音频属性不一致问题

1. 需求&#xff0c;amr转成mp3&#xff0c;再将此mp3和其他mp3合成 2. 问题&#xff1a;拼接后的第一段音频可以播放&#xff0c;第二段自动跳过&#xff0c;无法播放。 3. 解决&#xff1a; 3.1 查看各文件属性 # 查看amr转为mp3文件的属性&#xff1a;ffprobe 文件名&am…

Pytorch从零开始实战18

Pytorch从零开始实战——人脸图像生成 本系列来源于365天深度学习训练营 原作者K同学 文章目录 Pytorch从零开始实战——人脸图像生成环境准备模型定义开始训练可视化总结 环境准备 本文基于Jupyter notebook&#xff0c;使用Python3.8&#xff0c;Pytorch2.0.1cu118&#…

[力扣 Hot100]Day20 旋转图像

题目描述 给定一个 n n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 你必须在原地旋转图像&#xff0c;这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。 出处 思路 旋转时每四个位置为一组进行swap操作&#xff0c;找好对…

【蓝桥杯51单片机入门记录】LED

目录 一、基础 &#xff08;1&#xff09;新建工程 &#xff08;2&#xff09;编写前准备 二、LED &#xff08;1&#xff09;点亮LED灯 &#xff08;2&#xff09;LED闪烁 延时函数的生成&#xff08;stc-isp中生成&#xff09; 实现 &#xff08;3&#xff09;流水灯…

OpenHarmony—开发及引用动态共享包

对于企业大型应用开发&#xff0c;有部分公共的资源和代码&#xff0c;只能在开发态静态共享&#xff0c;并且打包到每个依赖的HAP里&#xff0c;这样导致包体积较大&#xff0c;且有重复多份公共资源和代码重复打包到应用中。 为了解决运行态状态无法共享&#xff0c;以及减少…

2024美赛B题保姆级分析完整思路代码数据教学

2024美国大学生数学建模竞赛B题保姆级分析完整思路代码数据教学 B题&#xff1a;Searching for Submersibles 搜索潜水器 从给定的背景信息中&#xff0c;我们知道MCMS是一家位于希腊的公司&#xff0c;他们制造能够将人类运送到海洋深处的潜水艇。他们现在希望使用他们的潜水…

UML---用例图,类图

用例图 用例图&#xff08;Use Case Diagram&#xff09;主要描述系统的功能需求和参与者与系统之间的交互。它是用户与系统交互的最简表示形式&#xff0c;展现了用户和与他相关的用例之间的关系。用例图被视为系统的蓝图&#xff0c;通过它&#xff0c;人们可以获知系统不同种…

C语言·贪吃蛇游戏(下)

上节我们将要完成贪吃蛇游戏所需的前置知识都学完了&#xff0c;那么这节我们就开始动手写代码了 1. 程序规划 首先我们应该规划好我们的代码文件&#xff0c;设置3个文件&#xff1a;snack.h 用来声明游戏中实现各种功能的函数&#xff0c;snack.c 用来实现函数&#xff0c;t…

C# 根据USB设备VID和PID 获取设备总线已报告设备描述

总线已报告设备描述 DEVPKEY_Device_BusReportedDeviceDesc 模式 winform 语言 c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Window…

2024美赛数学建模C题思路分析 - 网球的动量

1 赛题 问题C&#xff1a;网球的动量 在2023年温布尔登绅士队的决赛中&#xff0c;20岁的西班牙新星卡洛斯阿尔卡拉兹击败了36岁的诺瓦克德约科维奇。这是德约科维奇自2013年以来首次在温布尔登公开赛失利&#xff0c;并结束了他在大满贯赛事中历史上最伟大的球员之一的非凡表…

hivesql的基础知识点

目录 一、各数据类型的基础知识点 1.1 数值类型 整数 小数 float double(常用) decimal(针对高精度) 1.2 日期类型 date datetime timestamp time year 1.3 字符串类型 char varchar / varchar2 blob /text tinyblob / tinytext mediumblob / mediumtext lon…

EtherCAT FP介绍系列文章—UDP gateway

EtherCAT主站上的Mailbox Gateway功能&#xff0c;可以用于将EtherCAT mailbox相关协议从外部设备的工具通过邮箱网关路由到EtherCAT从站设备。在EtherCAT规范中定义的所有邮箱协议在此功能中都可用&#xff0c;例如CoE, FoE, VoE, SoE。 但是&#xff0c;这里特别注意的是Mai…

2024美赛数学建模E题思路分析 - 财产保险的可持续性

1 赛题 问题E&#xff1a;财产保险的可持续性 极端天气事件正成为财产所有者和保险公司面临的危机。“近年来&#xff0c;世界已经遭受了1000多起极端天气事件造成的超过1万亿美元的损失”。[1]2022年&#xff0c;保险业的自然灾害索赔人数“比30年的平均水平增加了115%”。[…

【STM32F103单片机】利用ST-LINK V2烧录程序 面包板的使用

1、ST‐LINK V2安装 参考&#xff1a; http://t.csdnimg.cn/Ulhhq 成功&#xff1a; 2、烧录器接线 背后有标识的引脚对应&#xff1a; 3、烧录成功 烧录成功后&#xff0c;按下核心板的RESET键复位&#xff01;&#xff01;&#xff01;即可成功&#xff01; 4、面包板的…