请使用C++借助Qt满足一个登录窗口 两个文本输入(账号 密码)和一个登录按键 要求有密码检测机制 同时正确的账号和密码保存在txt文件
时间: 2024-03-25 11:36:01 浏览: 24
好的,以下是使用 C++ 和 Qt 实现的登录窗口,包括账号密码的检测和读取:
```cpp
#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QFile>
#include <QTextStream>
class LoginWindow : public QWidget
{
public:
LoginWindow(QWidget *parent = nullptr) : QWidget(parent)
{
// 创建控件
QLabel *usernameLabel = new QLabel("账号:");
QLabel *passwordLabel = new QLabel("密码:");
QLineEdit *usernameEdit = new QLineEdit();
QLineEdit *passwordEdit = new QLineEdit();
passwordEdit->setEchoMode(QLineEdit::Password);
QPushButton *loginButton = new QPushButton("登录");
// 布局
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(usernameLabel);
layout->addWidget(usernameEdit);
layout->addWidget(passwordLabel);
layout->addWidget(passwordEdit);
layout->addWidget(loginButton);
setLayout(layout);
// 信号连接
connect(loginButton, &QPushButton::clicked, [=]() {
QString username = usernameEdit->text();
QString password = passwordEdit->text();
if (checkLogin(username, password)) {
QMessageBox::information(this, "登录成功", "欢迎回来!");
} else {
QMessageBox::warning(this, "登录失败", "账号或密码错误!");
}
});
}
bool checkLogin(QString username, QString password) {
// 打开存储正确账号密码的文件
QFile file("accounts.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, "错误", "无法打开账户文件!");
return false;
}
// 逐行读取文件中的账号密码信息进行匹配
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList items = line.split(":");
if (items.size() == 2) {
QString name = items.at(0);
QString pwd = items.at(1);
if (name == username && pwd == password) {
return true;
}
}
}
return false;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
LoginWindow window;
window.show();
return app.exec();
}
```
在这个实现中,我们使用了 Qt 的控件来创建登录窗口,包括标签、文本框和按钮,并使用垂直布局管理这些控件。在按钮的点击事件中,我们获取了文本框中输入的账号密码信息,并调用 `checkLogin` 函数进行检测。在 `checkLogin` 函数中,我们使用了 `QFile` 和 `QTextStream` 来打开和读取存储账号密码的文件,并逐行进行匹配验证。最终根据验证结果弹出相应的提示框。
注意,这个实现中的账号密码存储在名为 `accounts.txt` 的文件中,每行一个账号和密码,用冒号隔开。如果文件不存在或无法打开,程序会弹出相应的错误提示框。