Qt's dialog box and window--Splash and login window

Splash and login window

1 Overview of instance functions

Generally, a large application will display a splash screen when it is started, that is, the Splash window. The Splash window is a borderless dialog box that generally displays a picture to display software information. When the Splash window is displayed, the program does some time-consuming startup preparations in the background. The Splash window is automatically closed after being displayed for a period of time, and then the main window of the software is displayed. Qt has a QSplashScreen class that can implement the functions of the Splash window. It provides functions such as loading images and automatically setting the window borderless effect.

Some applications also have software login interfaces that require users to enter their username and password before entering the software.

Splash windows and login screens are essentially dialog boxes, which are displayed when the program starts. Splash login dialog box, this dialog box combines the functions of Splash window and login interface.
Insert image description here

Figure 1 Splash and login window of example samp6_5

This example demonstrates how to implement some of the following functions:

How to implement a borderless dialog box with the characteristics of Splash;
how to design a borderless dialog box that can be dragged with the mouse;
how to use the QSettings class to store user names, passwords and other information;
how to use the QCryptographicHash class for string encryption;
how to determine startup based on the login input status. Main window or terminate the program.

2 Dialog interface design and class definition

Use the method of creating a new Qt Designer Form Class to create a startup login dialog box, which is inherited from QDialog, and set the class name to QDlgLogin. The interface design is carried out in the UI designer. The main area is a QLabel component used to display pictures. Load the picture in the resource file and specify the picture for the pixmap of the QLabel component.

Below the dialog box is the QLineEdit component for user name and password input. Two buttons are used to select user input. The clicked() signal of the "Cancel" button is set to be associated with the reject() slot function of the dialog box. However, the clicked() signal of the "OK" button should not be set to be associated with any slot function of the dialog box. Custom slot function code needs to be written for it, because the result returned by the dialog box needs to be determined based on user input. Set up the layout for the components on the dialog interface.

The following is the definition of the QDlgLogin class in the qdlglogin.h file:

class QDlgLogin : public QDialog
{
    
    
   Q_OBJECT
private:
   bool   m_moving=false;//表示窗口是否在鼠标操作下移动
   QPoint  m_lastPos;  //上一次的鼠标位置
   QString  m_user="user"; //初始化用户名
   QString  m_pswd="12345";//初始化密码,未加密的
   int   m_tryCount=0; //试错次数
   void   readSettings(); //读取设置,注册表
   void   writeSettings();//写入设置,注册表
   QString  encrypt(const QString& str);//字符串加密
protected:
//用于鼠标拖动窗口的鼠标事件
   void mousePressEvent(QMouseEvent *event);
   void mouseMoveEvent(QMouseEvent *event);
   void mouseReleaseEvent(QMouseEvent *event);
public:
   explicit QDlgLogin(QWidget *parent = 0);
   ~QDlgLogin();
private slots:
   void on_btnOK_clicked();
private:
   Ui::dlgLogin *ui;
};

In the QDlgLogin class, some private member variables are defined.

m_moving and m_lastPos are used to record the movement status and last position when dragging the window. Since the Splash window does not have a title bar, the window is moved by dragging on the picture. Three mouse events are used to implement the window drag operation.
m_user, m_pswd, m_tryCount are used to record user name, password and number of attempts and errors.
readSettings() is used to read the stored settings, and writeSettings() is used to store the settings. Under Windows systems, this information is stored in the registry.
The encrypt() function is used to encrypt a string.

3 QDlgLogin class function implementation

1. Initialization in constructor

The constructor code of the QDlgLogin class is as follows:

QDlgLogin::QDlgLogin(QWidget *parent) :   QDialog(parent),   ui(new Ui::dlgLogin)
{
    
    
   ui->setupUi(this);
   ui->editPSWD->setEchoMode(QLineEdit::Password); //设置为密码输入模式
   this->setAttribute(Qt::WA_DeleteOnClose);//设置为关闭时删除
   this->setWindowFlags(Qt::SplashScreen); //设置为SplashScreen 
// this->setWindowFlags(Qt::FramelessWindowHint);//无边框,但在任务栏显示标题
   readSettings(); //读取存储的用户名和密码
}

The QLineEdit::setEchoMode() function sets the edit box echo mode. The parameter is the QLineEdit::EchoMode enumeration type. Here it is set to the QLineEdit::Password echo mode, which is used to echo the password input as a symbol without displaying the actual value. character.

Use the setWindowFlags() function to set the window flag to Qt::SplashScreen, so that the dialog box is displayed as a Splash window, without borders, and is not displayed on the Windows taskbar. Another similar flag is Qt::FramelessWindowHint, which makes the dialog box borderless but displays the dialog box title on the taskbar.

After the initial setting, call the readSettings() function to read the stored settings, and display the user name in the edit box on the window according to the stored conditions.

2. Storage of application settings

The custom member function readSettings() is used to read application settings, and writeSettings() is used to save settings. The implementation code is as follows:

void QDlgLogin::readSettings()
{
    
    //读取存储的用户名和密码, 密码是经过加密的
   QString  organization="WWB-Qt";//用于注册表,
   QString  appName="samp6_5"; 
   QSettings  settings(organization,appName);
   bool  saved=settings.value("saved",false).toBool();//读取 saved
   m_user=settings.value("Username", "user").toString();//读取Username 
   QString  defaultPSWD=encrypt("12345"); //缺省密码"12345"加密后的数据
   m_pswd=settings.value("PSWD",defaultPSWD).toString();//读取PSWD
   if (saved)
      ui->editUser->setText(m_user);
   ui->chkBoxSave->setChecked(saved);
}
void QDlgLogin::writeSettings()
{
    
     //保存用户名,密码等设置
   QSettings   settings("WWB-Qt","samp6_5"); //注册表键组
   settings.setValue("Username",m_user); //用户名
   settings.setValue("PSWD",m_pswd);   //密码,经过加密的
   settings.setValue("saved",ui->chkBoxSave->isChecked());
}

Application settings refer to some information that the application needs to save. Under Windows systems, this information is saved in the registry. Reading and writing of setting information can be achieved using the QSettings class.

When creating a QSettings object, you need to pass organization and appName, for example:

QSettings   settings("WWB-Qt","samp6_5");

The registry directory pointed to isHKEY_CURRENT_USER/Software/WWB-Qt/samp6_5

Parameters in the registry are saved in "key-key-value" pairs. The setValue() function is used in the writeSettings() function to write the key value, and the value() function is used in readSettings() to read the key value. When reading the key value, you can specify a default value, that is, if the key does not exist, the default value will be used as the read value.

Enter regedit in the input box of the Windows start menu, open the registry, find the directory HKEY_CURRENT_USER/Software/WWB-Qt/samp6_5, and you can see the parameter storage in the registry. Among them, the stored password is an encrypted string.

3.String encryption

In this example, the password is stored in an encrypted string, which ensures security in practical applications. Qt provides the class QCryptographicHash for encryption. The custom function encrypt() uses this class to encrypt strings. The implementation code is as follows:

QString QDlgLogin::encrypt(const QString &str)
{
    
     //字符串MD5算法加密
   QByteArray btArray;
   btArray.append(str); 
   QCryptographicHash hash(QCryptographicHash::Md5);  //Md5加密算法
   hash.addData(btArray);  //添加数据
   QByteArray resultArray =hash.result();  //返回最终的散列值
   QString md5 =resultArray.toHex();//转换为16进制字符串
   return  md5;
}

When creating QCryptographicHash, you need to specify an encryption algorithm. The encryption algorithm variable is the enumeration type QCryptographicHash::Algorithm. Commonly used constant values ​​include QCryptographicHash::Md4, QCryptographicHash::Md5, QCryptographicHash::Sha512, etc. For a complete description, please refer to Qt. Help documentation.

QCryptographicHash only provides encryption functions, not decryption functions.

4. Username and password input judgment

After the login window is running, click the "OK" button, and the program will judge the input content. The slot function code of the "OK" button is as follows:

void QDlgLogin::on_btnOK_clicked()
{
    
    //"确定"按钮
   QString  user=ui->editUser->text().trimmed();//输入用户名
   QString  pswd=ui->editPSWD->text().trimmed(); //输入密码
   QString  encrptPSWD=encrypt(pswd); //对输入密码进行加密
   if ((user==m_user)&&(encrptPSWD==m_pswd)) 
   {
    
       writeSettings();
      this->accept(); //对话框 accept(),关闭对话框
   }
   else
   {
    
       m_tryCount++; //错误次数
      if (m_tryCount>3)
      {
    
       QMessageBox::critical(this, "错误", "输入错误次数太多,强行退出");
         this->reject(); //退出
      }
      else
         QMessageBox::warning(this, "错误提示", "用户名或密码错误");
   }
}

Since QCryptographicHash only provides the encryption function but not the decryption function, after reading the application settings, the encrypted password cannot be decrypted and displayed on the window. The program can only echo the user name, but not the password. .

This program will encrypt the entered password. Because the encrypted password is read from the registry, it can compare whether the entered user name and password match the stored user name and password.

If the input is correct, call the accept() slot function of the window to close the dialog box. The return value of the dialog box is QDialog::Accepted. Otherwise, the number of trials and errors is increased by one; if the number of trials and errors is greater than 3, the reject() slot function of the window is called. Close the dialog box. The return value of the dialog box is QDialog::Rejected.

5. Implementation of window dragging function

Since Splash windows have no borders, you cannot drag the window by dragging its title bar like a normal window. In order to realize the dragging function of the window, the three mouse events of the window are processed. The implemented code is as follows:

void QDlgLogin::mousePressEvent(QMouseEvent *event)
{
    
     //鼠标按键被按下
   if (event->button() == Qt::LeftButton)
   {
    
       m_moving = true;
      m_lastPos = event->globalPos() - pos();//记录下鼠标相对于窗口的位置
   }
   return QDialog::mousePressEvent(event);  
}
void QDlgLogin::mouseMoveEvent(QMouseEvent *event)
{
    
    //鼠标按下左键移动
   if (m_moving && (event->buttons() && Qt::LeftButton) && (event->globalPos()-m_lastPos).manhattanLength() > QApplication::startDragDistance())
   {
    
    
      move(event->globalPos()-m_lastPos);
      m_lastPos = event->globalPos() - pos();
   }
   return QDialog::mouseMoveEvent(event);
}
void QDlgLogin::mouseReleaseEvent(QMouseEvent *event)
{
    
    //鼠标按键释放
   m_moving=false; //停止移动
}

The mousePressEvent (QMouseEvent *event) event occurs when the mouse button is pressed. The passed parameter event contains mouse button and coordinate information. If it is judged that the left mouse button is pressed, the variable m_moving value is set to true, indicating that the movement starts and is recorded. Mouse coordinates. event->globalPos() and pos() of the dialog box are coordinates in different coordinate systems, which will be introduced in detail in the drawing chapter.

The mouseMoveEvent (QMouseEvent *event) event is emitted when the mouse moves. The program determines whether the movement has started and pressed the left mouse button; if so, the move() function of the window is called to move a certain distance horizontally and vertically, and is recorded again. Coordinate points.

The mouseReleaseEvent(QMouseEvent *event) event occurs when the mouse button is released, and stops window movement when the left button is released.

So, when you press the left mouse button on a window and move it, the window will move with it.

4 Use of Splash login window

After designing the startup and login window QDlgLogin, use the startup and login dialog box in the main() function. The code of the main() function is as follows:

int main(int argc, char *argv[])
{
    
    
   QApplication a(argc, argv);
   QDlgLogin   *dlgLogin=new QDlgLogin; 
   if (dlgLogin->exec()==QDialog::Accepted)
   {
    
    
      QWMainWindow w;
      w.show();
      return a.exec();
   }
   else
      return  0;
}

Create the Splash login dialog object dlgLogin before the main window, and call this dialog box in a modal display. If the dialog box returns QDialog::Accepted, it means that the user name and password verification has been passed, and the main window will be created and displayed; otherwise, the application will exit. Since QDlgLogin is set to delete on close, verify that the object is automatically deleted after closing the login window.

Guess you like

Origin blog.csdn.net/simple_core/article/details/124670430