C++如何写一个登陆窗口的代码
时间: 2023-11-27 15:51:19 浏览: 137
下面是一个简单的登陆窗口的代码示例,用到了Qt框架:
```c++
// 登陆窗口类的头文件 LoginDialog.h
#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H
#include <QDialog>
namespace Ui {
class LoginDialog;
}
class LoginDialog : public QDialog
{
Q_OBJECT
public:
explicit LoginDialog(QWidget *parent = nullptr);
~LoginDialog();
signals:
void loginSuccess();
private slots:
void on_loginButton_clicked();
private:
Ui::LoginDialog *ui;
};
#endif // LOGINDIALOG_H
```
```c++
// 登陆窗口类的实现文件 LoginDialog.cpp
#include "LoginDialog.h"
#include "ui_LoginDialog.h"
#include <QMessageBox>
LoginDialog::LoginDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::LoginDialog)
{
ui->setupUi(this);
}
LoginDialog::~LoginDialog()
{
delete ui;
}
void LoginDialog::on_loginButton_clicked()
{
QString username = ui->usernameLineEdit->text();
QString password = ui->passwordLineEdit->text();
if (username == "admin" && password == "123456") {
emit loginSuccess();
accept();
} else {
QMessageBox::warning(this, tr("Warning"), tr("Invalid username or password!"));
}
}
```
```c++
// 登陆窗口的界面文件 LoginDialog.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LoginDialog</class>
<widget class="QDialog" name="LoginDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Login</string>
</property>
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>50</x>
<y>50</y>
<width>301</width>
<height>201</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="usernameLabel">
<property name="text">
<string>Username:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="usernameLineEdit"/>
</item>
<item>
<widget class="QLabel" name="passwordLabel">
<property name="text">
<string>Password:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="passwordLineEdit"/>
</item>
<item>
<widget class="QPushButton" name="loginButton">
<property name="text">
<string>Login</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
```
使用方法:
```c++
#include "LoginDialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LoginDialog loginDialog;
QObject::connect(&loginDialog, &LoginDialog::loginSuccess, [&]() {
// 登陆成功后的操作
});
loginDialog.exec();
return a.exec();
}
```
需要注意的是,这个示例只是一个简单的登陆窗口,实际应用中需要加入更多的安全措施,例如对密码进行加密处理。
阅读全文