#include "SoftKeyboard.h"
SoftKeyboard::SoftKeyboard(QWidget *parent) : QDialog(parent), isUpperCase(false) {
QGridLayout *layout = new QGridLayout(this);
// 定义键盘布局内容
QStringList keys = {"1","2","3","4","5","6","7","8","9","0",
"q","w","e","r","t","y","u","i","o","p",
"a","s","d","f","g","h","j","k","l","Back",
"Shift","z","x","c","v","b","n","m",",",".","Enter"};
int row = 0, col = 0;
for (const QString &key : keys) {
QPushButton *btn = new QPushButton(key, this);
// 记录每个按钮的原始文本
btn->setProperty("originalText", key);
// 如果是 Shift 按钮,则单独处理其点击事件
if (key == "Shift") {
connect(btn, &QPushButton::clicked, this, [this]() {
toggleCase(); // 切换大小写状态
});
} else {
connect(btn, &QPushButton::clicked, this, &SoftKeyboard::onKeyClicked);
}
layout->addWidget(btn, row, col++);
if (col >= 10) { col = 0; row++; }
}
}
void SoftKeyboard::toggleCase() {
isUpperCase = !isUpperCase;
// 遍历所有按键并更新文本
QList<QPushButton*> buttons = findChildren<QPushButton*>();
foreach (QPushButton *button, buttons) {
QString originalText = button->property("originalText").toString();
// 只针对字母按键进行大小写转换
if (originalText.length() == 1 && originalText.contains(QRegExp("[a-zA-Z]"))) {
button->setText(isUpperCase ? originalText.toUpper() : originalText.toLower());
}
}
}
// 连接 QLineEdit 的槽函数不变
void SoftKeyboard::linkLineEdit(QLineEdit *le) {
linkedLineEdit = le;
}
// 键盘按下时的操作逻辑
void SoftKeyboard::onKeyClicked() {
QPushButton *btn = qobject_cast<QPushButton*>(sender());
if (!btn || !linkedLineEdit) return;
QString text = btn->text();
if (text == "Back") {
linkedLineEdit->backspace();
} else if (text == "Enter") {
this->hide();
} else {
// 插入时尊重当前大小写状态
linkedLineEdit->insert(text);
}
}
修改代码,将数字键和符号单独放到另一个界面,当通过点击某个按键切换