QT: Add a login interface for your own QT program

I took a private job, and I had to add this function after finishing it. I tried to do it myself. The modules are independent and will not be related to the main interface. The main interface has basically not changed. In general, it is still a method that I am thinking about. It may not be very professional, but in general it is simple and fast.

Insert picture description here
The login system that needs to be added does not have a registration function, which is equivalent to adding a password to the software, which is written in the source code.

1. Create a new ui interface

Right-click the project directory and choose to Add Newcreate a new file:
Insert picture description here

Blank interface is enough, we can add controls by ourselves
Insert picture description here

Set the name, and then you can.

Insert picture description here

2. Open the ui design page, drag the controls, and layout the interface.

Insert picture description here

Then design the following interface:

Insert picture description here
The total dragged controls are as follows:
Insert picture description here
As for the page layout, you can manually set it in the UI design interface, or you can set it in logwidget.cppthe code under the file, according to your own habits:

void LogWidget::form_init()
{
    // 文件标题名
    ui->label_title->setGeometry(120,25,160,25);
    ui->groupBox->setGeometry(50,60,300,125);
    ui->label_name->setGeometry(25,25,100,25);
    ui->edit_name->setGeometry(125,25,150,25);
    ui->label_pw->setGeometry(25,75,100,25);
    ui->edit_pw->setGeometry(125,75,150,25);
    ui->check_name->setGeometry(85,200,100,25);
    ui->check_pw->setGeometry(215,200,100,25);
    ui->btn_log->setGeometry(50,235,120,30);
    ui->btn_clear->setGeometry(230,235,120,30);


    //调整字体大小
    QFont font;
    font.setPointSize(16); //实际上是16的字号,但设成16却不行
    font.setFamily(("wenquanyi"));
    font.setBold(false);
    ui->label_title->setFont(font);
    font.setPointSize(12);
    ui->label_name->setFont(font);
    ui->label_pw->setFont(font);
}

3. How to log in to the main interface through the login interface

In fact, the first two parts are irrelevant, the core part starts here.
The main function code we used to open the main interface is generally:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

But the effect we want to make now is to first pop up the login interface, and then enter the main interface according to the login interface button;
my method is:
1. Create the login interface object LogWidget when the MainWindow object is initialized, and call the show method of the LogWidget object .
2. The main function does not call the show() function of the MainWindow object, but sends a signal through the LogWidget login button through the signal slot mechanism, and then calls the show method of MainWindow
3. Also through the signal slot mechanism, the LogWidget login button After sending the signal, call the close() function of LogWidget to close the login interface after logging in to the main interface.

logwidget.h

namespace Ui {
class LogWidget;
}


class LogWidget : public QWidget
{
    Q_OBJECT

public:
    explicit LogWidget(QWidget *parent = nullptr);
    ~LogWidget();

signals:
    void login(); //登录主界面信号
    void close_window(); //关闭登录界面信号

public slots:
    void btn_clear_clicked(); //重置按钮按下后触发的事件
    void btn_log_clicked(); //登录按钮按下后触发的事件

private:
    Ui::LogWidget *ui;
};

logwidget.cpp

LogWidget::LogWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogWidget)
{
    ui->setupUi(this);
    // connect 3个信号槽
    // 触发重置按钮的信号槽连接
    connect(ui->btn_clear,SIGNAL(clicked()),this,SLOT(btn_clear_clicked()));
    // 触发登录按钮的信号槽连接
    connect(ui->btn_log,SIGNAL(clicked()),this,SLOT(btn_log_clicked()));
    // 发出信号后关闭登录窗口的信号槽连接
    connect(this,SIGNAL(close_window()),this,SLOT(close()));
}

// 清理输入栏
void LogWidget::btn_clear_clicked()
{
    ui->edit_pw->clear();
    ui->edit_name->clear();
}

// 登录按钮触发事件
void LogWidget::btn_log_clicked()
{  
    // 发出登录信号
    emit(login());
   // 发出关闭窗口信号
    emit(close_window());
}

mainwindow.h

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private:
    Ui::MainWindow *ui;
    
    // 登录界面类的对象作为指针
    LogWidget * m_log;

};
#endif // MAINWINDOW_H

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 通过指针创建登录界面类的对象
    m_log = new LogWidget;
    // 调用登录窗口的show()函数显示登录界面
    m_log->show();

    // 建立信号槽,到接收到登录界面发来的login()信号后,调用主窗口的show()函数。
    connect(m_log,SIGNAL(login()),this,SLOT(show()));

}


4. Set the account and password of the login interface

This idea is determined according to actual needs. In my current situation, I just write these in the code. Then get the data of the input box and compare it with the built-in password.

namespace Ui {
class LogWidget;
}


class LogWidget : public QWidget
{
    Q_OBJECT


public:
    explicit LogWidget(QWidget *parent = nullptr);
    ~LogWidget();

signals:
    void login(); //登录主界面信号
    void close_window();  //关闭登录界面信号


public slots:
    void btn_clear_clicked();  //重置按钮按下后触发的事件
    void btn_log_clicked();  //登录按钮按下后触发的事件
    
private:
    Ui::LogWidget *ui;
    QString m_username;  // 自己设定的账号
    QString m_password;  // 自己设定的密码
};

logwidget.cpp
modify login button trigger event btn_log_clicked()

LogWidget::LogWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogWidget)
{
    ui->setupUi(this);
    // connect
    // 触发重置按钮的信号槽连接
    connect(ui->btn_clear,SIGNAL(clicked()),this,SLOT(btn_clear_clicked()));
    // 触发登录按钮的信号槽连接
    connect(ui->btn_log,SIGNAL(clicked()),this,SLOT(btn_log_clicked()));
    // 发出信号后关闭登录窗口的信号槽连接
    connect(this,SIGNAL(close_window()),this,SLOT(close()));
    ui->edit_pw->setEchoMode(QLineEdit::Password);//输入的时候就显示圆点
    m_username = "wuyongwen";
    m_password = "wuyongwen";
   }


void LogWidget::btn_log_clicked()
{  
    // 从输入框获取账号
    QString name = ui->edit_name->text();
    // 从输入框获取密码
    QString password = ui->edit_pw->text();

    //账号和密码匹配正确
    if (name == m_username && password == m_password)
    {
        emit(login());
        emit(close_window());
    }
    else // 账号或密码错误
        QMessageBox::information(this, "Warning","Username or Password is wrong !");
}

5. Realize the function of remembering account and remembering password

This function requires us to store part of the information as a configuration file, the program reads it during initialization, and then executes the corresponding settings.

Basic idea:
1. Create a json file
. 2. The json file will be read when the login interface is initialized.
3. According to the json file data, whether the account and password are automatically filled in, and the check box is automatically checked
4. Each time the login is triggered Button, if the login is successful, rewrite the json file according to the check box of the check box again.

json file setting
Insert picture description here
SAVE_NAME corresponding key value 0 means not saving the account, 1 means saving the account;
SAVE_PASSWORD corresponding key value 0 means not saving the password, 1 means saving the password;

logwidget.h

#include <QWidget>
#include <QMessageBox>
#include <QJsonDocument>
#include <QFile>
#include <QDebug>
#include <QJsonObject>
#include <QByteArray>


namespace Ui {
class LogWidget;
}


class LogWidget : public QWidget
{
    Q_OBJECT

public:
    explicit LogWidget(QWidget *parent = nullptr);
    ~LogWidget();

    void read_json(); //读json
    void write_json();//写json
    void message_init(QString flag1,QString flag2);//根据json内容决定是否填充输入框


signals:
    void login(); //登录主界面信号
    void close_window();  //关闭登录界面信号


public slots:
    void btn_clear_clicked();  //重置按钮按下后触发的事件
    void btn_log_clicked();  //登录按钮按下后触发的事件


private:
    Ui::LogWidget *ui;
    QString m_username;
    QString m_password;


};

logwidget.cpp

#include "logwidget.h"
#include "ui_logwidget.h"

LogWidget::LogWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogWidget)
{
    ui->setupUi(this);
// connect
    // 触发重置按钮的信号槽连接
    connect(ui->btn_clear,SIGNAL(clicked()),this,SLOT(btn_clear_clicked()));
    // 触发登录按钮的信号槽连接
    connect(ui->btn_log,SIGNAL(clicked()),this,SLOT(btn_log_clicked()));
    // 发出信号后关闭登录窗口的信号槽连接
    connect(this,SIGNAL(close_window()),this,SLOT(close()));
    
    ui->edit_pw->setEchoMode(QLineEdit::Password);//输入的时候就显示圆点
    m_username = "wuyongwen";
    m_password = "wuyongwen";
    // 读取json文件
    read_json();
}

void LogWidget::read_json()
{
    //打开文件
    QFile file(QApplication::applicationDirPath()+"/config.json");
    if(!file.open(QIODevice::ReadOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }
    QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
    QJsonObject obj = jdc.object();
    QString save_name_flag=obj.value("SAVE_NAME").toString();
    QString save_password_flag=obj.value("SAVE_PASSWORD").toString();
    message_init(save_name_flag,save_password_flag);
}

//根据json内容决定是否填充输入框
void LogWidget::message_init(QString flag1,QString flag2)
{
    //qDebug() << flag1 << "^^^" << flag2 ;
    if (flag1 == "1")
    {
        ui->edit_name->setText("wuyongwen");
        ui->check_name->setChecked(true);
    }
    if(flag2 == "1")
    {
        ui->edit_pw->setText("wuyongwen");
        ui->check_pw->setChecked(true);
    }
}

// 清理输入栏
void LogWidget::btn_clear_clicked()
{
    ui->edit_pw->clear();
    ui->edit_name->clear();
}

//登录按钮按下后触发的事件
void LogWidget::btn_log_clicked()
{
    QString name = ui->edit_name->text();
    QString password = ui->edit_pw->text();

    if (name == m_username && password == m_password)
    {
        emit(login());
        write_json();
        emit(close_window());
    }
    else
        QMessageBox::information(this, "Warning","Username or Password is wrong !");
}

// 更新json文件
void LogWidget::write_json()
{
    QFile file(QApplication::applicationDirPath()+"/config.json");
    if(!file.open(QIODevice::WriteOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }
    QJsonObject obj;
    bool flag = ui->check_name->isChecked();
    if(flag == true)
    {
        obj["SAVE_NAME"] = "1";
    }
    else
        obj["SAVE_NAME"] = "0";
    flag = ui->check_pw->isChecked();
    if(flag == true)
    {
        obj["SAVE_PASSWORD"] = "1";
    }
    else
        obj["SAVE_PASSWORD"] = "0";
    QJsonDocument jdoc(obj);
    file.write(jdoc.toJson());
    file.flush();
}

6. The final complete code:

logwidget.h

#ifndef LOGWIDGET_H
#define LOGWIDGET_H


#include <QWidget>
#include <QMessageBox>
#include <QJsonDocument>
#include <QFile>
#include <QDebug>
#include <QJsonObject>
#include <QByteArray>


namespace Ui {
class LogWidget;
}


class LogWidget : public QWidget
{
    Q_OBJECT


public:
    explicit LogWidget(QWidget *parent = nullptr);
    ~LogWidget();


    void form_init(); //格式初始化
    void func_init(); //功能初始化
    void read_json();
    void write_json();
    void message_init(QString flag1,QString flag2);


signals:
    void login(); //登录主界面信号
    void close_window();  //关闭登录界面信号


public slots:
    void btn_clear_clicked();  //重置按钮按下后触发的事件
    void btn_log_clicked();  //登录按钮按下后触发的事件


private:
    Ui::LogWidget *ui;


    QString m_username;
    QString m_password;


};


#endif // LOGWIDGET_H


logwidget.cpp

#include "logwidget.h"
#include "ui_logwidget.h"


LogWidget::LogWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogWidget)
{
    ui->setupUi(this);
    form_init();
    func_init();
}


LogWidget::~LogWidget()
{
    delete ui;
}


void LogWidget::form_init()
{
    // 文件标题名
    ui->label_title->setGeometry(120,25,160,25);
    ui->groupBox->setGeometry(50,60,300,125);
    ui->label_name->setGeometry(25,25,100,25);
    ui->edit_name->setGeometry(125,25,150,25);
    ui->label_pw->setGeometry(25,75,100,25);
    ui->edit_pw->setGeometry(125,75,150,25);
    ui->check_name->setGeometry(85,200,100,25);
    ui->check_pw->setGeometry(215,200,100,25);
    ui->btn_log->setGeometry(50,235,120,30);
    ui->btn_clear->setGeometry(230,235,120,30);


    //调整字体大小
    QFont font;
    font.setPointSize(16); //实际上是16的字号,但设成16却不行
    font.setFamily(("wenquanyi"));
    font.setBold(false);
    ui->label_title->setFont(font);
    font.setPointSize(12);
    ui->label_name->setFont(font);
    ui->label_pw->setFont(font);
}


void LogWidget::func_init()
{
    // connect
    // 触发重置按钮的信号槽连接
    connect(ui->btn_clear,SIGNAL(clicked()),this,SLOT(btn_clear_clicked()));
    // 触发登录按钮的信号槽连接
    connect(ui->btn_log,SIGNAL(clicked()),this,SLOT(btn_log_clicked()));
    // 发出信号后关闭登录窗口的信号槽连接
    connect(this,SIGNAL(close_window()),this,SLOT(close()));


    ui->edit_pw->setEchoMode(QLineEdit::Password);//输入的时候就显示圆点


    m_username = "wuyongwen";
    m_password = "wuyongwen";


    read_json();
}


// 清理输入栏
void LogWidget::btn_clear_clicked()
{
    ui->edit_pw->clear();
    ui->edit_name->clear();
}




void LogWidget::btn_log_clicked()
{
    QString name = ui->edit_name->text();
    QString password = ui->edit_pw->text();


    if (name == m_username && password == m_password)
    {
        emit(login());
        write_json();
        emit(close_window());
    }


    else
        QMessageBox::information(this, "Warning","Username or Password is wrong !");


}


void LogWidget::read_json()
{
    //打开文件
    QFile file(QApplication::applicationDirPath()+"/config.json");
    if(!file.open(QIODevice::ReadOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }
    QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
    QJsonObject obj = jdc.object();
    QString save_name_flag=obj.value("SAVE_NAME").toString();
    QString save_password_flag=obj.value("SAVE_PASSWORD").toString();
    message_init(save_name_flag,save_password_flag);


}


void LogWidget::write_json()
{
    QFile file(QApplication::applicationDirPath()+"/config.json");
    if(!file.open(QIODevice::WriteOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }
    QJsonObject obj;
    bool flag = ui->check_name->isChecked();
    if(flag == true)
    {
        obj["SAVE_NAME"] = "1";
    }
    else
        obj["SAVE_NAME"] = "0";
    flag = ui->check_pw->isChecked();
    if(flag == true)
    {
        obj["SAVE_PASSWORD"] = "1";
    }
    else
        obj["SAVE_PASSWORD"] = "0";
    QJsonDocument jdoc(obj);
    file.write(jdoc.toJson());
    file.flush();
}



void LogWidget::message_init(QString flag1,QString flag2)
{
    //qDebug() << flag1 << "^^^" << flag2 ;
    if (flag1 == "1")
    {
        ui->edit_name->setText("wuyongwen");
        ui->check_name->setChecked(true);
    }
    if(flag2 == "1")
    {
        ui->edit_pw->setText("wuyongwen");
        ui->check_pw->setChecked(true);
    }
}

mainwindow.h (irrelevant content omitted)

#include "logwidget.h"
#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE


class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    LogWidget * m_log;
}

mainwindow.cpp (omit irrelevant content)

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_log = new LogWidget;
    m_log->show();
    connect(m_log,SIGNAL(login()),this,SLOT(show()));
}

Guess you like

Origin blog.csdn.net/sazass/article/details/109445117