PyQT5 software development - control Chapter 3 single line text box QLineEdit

Text box is a frequently used control in GUI interface. Text box is divided into single line text box and multi line text box. This paper first talks about single line text box. Single line text box is widely used, such as password account password box, search bar, path address bar, etc.

3.1 introduction

QLineEdit can input and display text information, and set display format and text box properties. The common methods in QLineEdit class are shown in the following table.

Common signals in QLineEdit class are as follows:

textChanged(str) sends this signal whenever the text changes. This signal is also sent when the text is changed programmatically by calling setText(), and editingFinished() when the return or enter key is pressed or the line editing loses focus.

3.2 QLineEdit instance

First, use QT Designer to drag several controls. The effects are as follows:

The next step is to implement the logic code.

# -*- coding: utf-8 -*-
"""
@file                mainMainpage.py
@author              BruceOu
@version             V1.0
@date                2021-11-25
@blog                https://blog.bruceou.cn/
@Official Accounts   Embedded experimental building
@brief               MainWindow
"""
from PyQt5 import QtWidgets
from PyQt5.QtGui import QGuiApplication, QIcon, QDesktopServices, QFont
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QButtonGroup, QToolButton, QMenu, QAction
from PyQt5.QtCore import Qt,QUrl
import re 

from ui.ui_mainpage import Ui_MainWindow

## MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    
    #init
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('QRadioButton')
        
        self.setupUi(self)
        
        self.show()
        
        ## login ###############################################################################################
        ## user
        self.lineEditUser.setPlaceholderText('Please enter user name')
        
        self.lineEditUser.setStyleSheet("color:red")
        
        ## set font
        ## Method 1
        font = QFont()
        font.setFamily('Microsoft YaHei ')
        font.setBold(True)
        font.setPointSize(10)
        font.setWeight(75)
        self.lineEditUser.setFont(font)
        
        ## Method 2
        # self.lineEditUser.setFont(QFont('microsoft YaHei ', 20))
        
        ## Set the maximum user name input to 16
        self.lineEditUser.setMaxLength(16)
        
        ## Password
        self.lineEditPassword.setPlaceholderText('Please enter password')
        self.lineEditPassword.setEchoMode(QtWidgets.QLineEdit.Password)
        
        ## PasswordNoecho
        self.lineEditPasswordNoecho.setEchoMode(QtWidgets.QLineEdit.NoEcho)
        self.lineEditPasswordNoecho.setPlaceholderText('Please enter password')
        
        ## PasswordEchoOnEdit
        self.lineEditPasswordEchoOnEdit.setEchoMode(QtWidgets.QLineEdit.PasswordEchoOnEdit)
        self.lineEditPasswordEchoOnEdit.setPlaceholderText('Please enter password')
        
        ## setting #############################################################################################
        # IP
        self.lineEditIP.setInputMask('000.000.000.000;_')
        
        self.lineEditMask.setInputMask('000.000.000.000;_')
        
        
        ### event
        self.lineEditPassword.editingFinished.connect(self.check_password)
        
        self.pushButtonLogin.clicked.connect(self.btn_clicked) ## Bind button event
        self.pushButtonSetting.clicked.connect(self.btn_clicked)
        
        
    def check_password(self):
        """
        Brief
        ----------
            check password
        
        Parameters
        ----------
            None

        Returns
        ----------
            None
        """        
        sender = self.sender()
        
        passwd = sender.text()
        if(len(passwd) < 6 or len(passwd) > 16):
            QMessageBox.warning(self, 'Warning','The password should be 6 - 16!')
        elif(None == re.match("^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$" ,passwd)):
            QMessageBox.warning(self, 'Warning','Password must contain uppercase and lowercase letters and numbers!')
        else:
            pass
            
    def btn_clicked(self):
        """
        Brief
        ----------
            pushButton clicked
        
        Parameters
        ----------
            None

        Returns
        ----------
            None
        """
        sender = self.sender()
        
        if(sender == self.pushButtonLogin):
            QMessageBox.about(self, 'Login','User: {}, Password: {}, PasswordNoecho: {}, PasswordEchoOnEdit: {}'\
                              .format(self.lineEditUser.text(), self.lineEditPassword.text(), self.lineEditPasswordNoecho.text(), self.lineEditPasswordEchoOnEdit.text()))
        
        elif(sender == self.pushButtonSetting):
             QMessageBox.about(self, 'Setting','IP: {}, Mask: {}'\
                              .format(self.lineEditIP.text(), self.lineEditMask.text())) 

    def closeEvent(self, event):
        """
        Brief
        ----------
            Close Event
        
        Parameters
        ----------
            event

        Returns
        ----------
            None
        """
        event.accept()

[refer to attachment QLineEdit for complete code]

Demonstration effect:


The code is very simple. Just use it according to the previous API and the actual situation. Here are some explanations.

setPlaceholderText(str) indicates to set the prompt text of the line text. Setting this property will make the line edit display a gray placeholder text. When there is input text, the prompt text will disappear.

setInputMask() is used to set the mask, which is mainly used in IP address, License, date and other places to limit the input format. A mask consists of a mask character and a separator string, which can be followed by a semicolon and a white space character.

Examples of common masks are as follows:



Resource acquisition method

1. scan the following two-dimensional code, pay attention to the official account [AI laboratory building]
2. get the data extraction code in the official account reply to the keyword [PyQt5].

Welcome to my website

Bruce Ou's beep beep beep
Bruce Ou's home page
Bruce Ou's blog
Bruce Ou's CSDN blog
Bruce Ou's short book
What does Bruce ou know

Tags: PyQt5

Posted on Fri, 26 Nov 2021 19:57:20 -0500 by aaaaCHoooo