我正在qt中创建一个登录表单,其中的输入来自数字键盘。小键盘在屏幕上创建。当我尝试从小键盘上获取输入时, 它在lineEdit字段中都接受输入。那么,在从小键盘上获取输入时,如何将两者分开?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mainscreen.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->dB1,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB2,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB3,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB4,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB5,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB6,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB7,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB8,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB9,SIGNAL(released()),this,SLOT(display()));
connect(ui->dB0,SIGNAL(released()),this,SLOT(display()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::display()
{
QPushButton *qp=(QPushButton*)sender();
ui->lineEdit->setText(ui->lineEdit->text()+qp->text());
ui->lineEdit_2->setText(ui->lineEdit_2->text()+qp->text());
}
void MainWindow::on_pushButton_clicked()
{
QString username=ui->lineEdit->text();
QString password=ui->lineEdit_2->text();
if(username=="text"&&password=="text")
{
hide();
main_scn=new MainScreen();
main_scn->setWindowFlags(Qt::Window|Qt::FramelessWindowHint);
main_scn->show();
}
}
用户界面在这里,请检查一下
答案 0 :(得分:0)
以这种方式创建数字键盘很不方便,因为它将文本同时放入QLineEdit中,并且通常用户名和密码并不总是相同。
我的建议是创建一个不需要通过信号连接的数字键盘,但会发送一个事件,以便具有焦点的小部件。
numpadwidget.h
#ifndef NUMPADWIDGET_H
#define NUMPADWIDGET_H
#include <QApplication>
#include <QGridLayout>
#include <QKeyEvent>
#include <QToolButton>
#include <QWidget>
class NumpadWidget : public QWidget
{
Q_OBJECT
public:
explicit NumpadWidget(QWidget *parent = nullptr) : QWidget(parent)
{
QGridLayout *lay = new QGridLayout(this);
const std::vector<QPair<QString, int>> values{{"1", Qt::Key_1}, {"2", Qt::Key_2}, {"3", Qt::Key_3},
{"4", Qt::Key_4}, {"5", Qt::Key_5}, {"6", Qt::Key_6},
{"7", Qt::Key_7}, {"8", Qt::Key_8}, {"9", Qt::Key_9},
{".", Qt::Key_Colon}, {"0", Qt::Key_0}, {"*", Qt::Key_Asterisk}};
int i = 0;
int j = 0;
for(const QPair<QString, int> & value : values){
QToolButton *button =new QToolButton;
button->setText(value.first);
button->setFixedSize(40,40);
lay->addWidget(button, i, j);
button->setProperty("text", value.first);
button->setProperty("key", value.second);
connect(button, &QToolButton::clicked, this, &NumpadWidget::onClicked);
j++;
if(j % 3 == 0){
j=0;
i++;
}
}
setFixedSize(sizeHint());
}
private slots:
void onClicked()
{
if(QWidget *widget = QApplication::focusWidget()){
QString text = sender()->property("text").toString();
int key = sender()->property("key").toInt();
QKeyEvent * event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, text);
QCoreApplication::postEvent(widget, event);
}
}
};
#endif // NUMPADWIDGET_H
然后将NumpadWidget升级,以便可以在Qt Designer中使用,在下面的link中指出如何进行操作
可以在以下link中找到完整的项目。