使用QLineEdit和QPushButton实现了输入用户名、密码并验证的功能。该程序使用正则表达式限制了用户名和密码只能包含数字、字母和下划线,且长度在4到16个字符之间。如果输入的用户名和密码符合要求,则弹出一个消息框显示“登录成功”,否则弹出一个消息框显示“登录失败”。
#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QRegExpValidator>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
w.resize(300, 150);
QLineEdit userLineEdit(&w);
userLineEdit.setPlaceholderText("请输入用户名");
userLineEdit.setGeometry(50, 30, 200, 30);
QRegExp userRegExp("[A-Za-z0-9_]{4,16}");
userLineEdit.setValidator(new QRegExpValidator(userRegExp, &userLineEdit));
QLineEdit passwordLineEdit(&w);
passwordLineEdit.setPlaceholderText("请输入密码");
passwordLineEdit.setGeometry(50, 70, 200, 30);
passwordLineEdit.setEchoMode(QLineEdit::Password);
QRegExp passwordRegExp("[A-Za-z0-9_]{4,16}");
passwordLineEdit.setValidator(new QRegExpValidator(passwordRegExp, &passwordLineEdit));
QPushButton loginButton("登录", &w);
loginButton.setGeometry(100, 110, 100, 30);
QObject::connect(&loginButton, &QPushButton::clicked, [&]() {
QString username = userLineEdit.text();
QString password = passwordLineEdit.text();
if (userLineEdit.hasAcceptableInput() && passwordLineEdit.hasAcceptableInput()) {
if (username == "admin" && password == "123456") {
QMessageBox::information(&w, "登录成功", "欢迎您,管理员!");
} else {
QMessageBox::warning(&w, "登录失败", "用户名或密码错误,请重试!");
}
} else {
QMessageBox::warning(&w, "输入错误", "用户名或密码格式错误,请重新输入!");
}
});
w.show();
return a.exec();
}