qt模拟系统登录框,要有数据库的验证操作
时间: 2024-03-09 22:48:16 浏览: 22
模拟系统登录框,需要用到 Qt 中的 QDialog 和 QLineEdit 控件,以及数据库连接和操作。实现步骤如下:
1. 创建登录对话框 LoginDialog,并在该对话框中添加两个 QLineEdit 控件,一个用于输入用户名,一个用于输入密码,还需要添加两个 QPushButton 控件,一个用于登录,一个用于退出。
2. 在登录按钮的 clicked() 信号槽函数中,获取用户名和密码,然后根据数据库中的用户信息进行验证。如果验证成功,则关闭登录对话框,否则弹出提示框提示用户名或密码错误。
3. 在退出按钮的 clicked() 信号槽函数中,关闭登录对话框。
下面是示例代码:
login_dialog.h:
```cpp
#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSqlDatabase>
class LoginDialog : public QDialog
{
Q_OBJECT
public:
explicit LoginDialog(QWidget *parent = nullptr);
private:
QLabel *m_userLabel;
QLabel *m_pwdLabel;
QLineEdit *m_userEdit;
QLineEdit *m_pwdEdit;
QPushButton *m_loginBtn;
QPushButton *m_exitBtn;
QSqlDatabase m_db;
private slots:
void login();
void exit();
};
#endif // LOGINDIALOG_H
```
login_dialog.cpp:
```cpp
#include "login_dialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent)
{
setWindowTitle(tr("Login"));
m_userLabel = new QLabel(tr("Username:"));
m_pwdLabel = new QLabel(tr("Password:"));
m_userEdit = new QLineEdit;
m_pwdEdit = new QLineEdit;
m_pwdEdit->setEchoMode(QLineEdit::Password);
m_loginBtn = new QPushButton(tr("Login"));
m_exitBtn = new QPushButton(tr("Exit"));
QHBoxLayout *userLayout = new QHBoxLayout;
userLayout->addWidget(m_userLabel);
userLayout->addWidget(m_userEdit);
QHBoxLayout *pwdLayout = new QHBoxLayout;
pwdLayout->addWidget(m_pwdLabel);
pwdLayout->addWidget(m_pwdEdit);
QHBoxLayout *btnLayout = new QHBoxLayout;
btnLayout->addWidget(m_loginBtn);
btnLayout->addWidget(m_exitBtn);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(userLayout);
mainLayout->addLayout(pwdLayout);
mainLayout->addLayout(btnLayout);
setLayout(mainLayout);
connect(m_loginBtn, SIGNAL(clicked()), this, SLOT(login()));
connect(m_exitBtn, SIGNAL(clicked()), this, SLOT(exit()));
// 连接数据库
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName("users.db");
if (!m_db.open()) {
QMessageBox::critical(this, tr("Error"), tr("Failed to connect to database."));
}
}
void LoginDialog::login()
{
QString username = m_userEdit->text();
QString password = m_pwdEdit->text();
QSqlQuery query(m_db);
QString sql = QString("SELECT * FROM users WHERE username='%1' AND password='%2'").arg(username).arg(password);
if (query.exec(sql) && query.next()) {
accept();
} else {
QMessageBox::warning(this, tr("Warning"), tr("Username or password incorrect."));
}
}
void LoginDialog::exit()
{
reject();
}
```
在这个示例中,我们利用了 Qt 的信号槽机制来响应登录和退出按钮的点击事件,利用了 Qt 的 QSqlDatabase 和 QSqlQuery 类来连接和操作数据库。当用户点击登录按钮时,我们将获取到的用户名和密码与数据库中的用户信息进行验证,如果验证成功,则调用 QDialog 的 accept() 函数关闭对话框并返回 QDialog::Accepted,否则弹出一个提示框提示用户名或密码错误。当用户点击退出按钮时,我们调用 QDialog 的 reject() 函数关闭对话框并返回 QDialog::Rejected。