PyQt4 User Input Validation - QlineEdit

后端 未结 1 389
無奈伤痛
無奈伤痛 2021-01-12 17:45

I\'m having a little trouble understanding input validation with PyQt4. This is my first GUI application and first time working with the PyQt4 framework. I\'ve been reading

相关标签:
1条回答
  • 2021-01-12 18:32

    I hope that I understand your question, so you got a QLineEdit somewhere in your app. and you want to stop users to enter "strange" characters like: ~!@#$#%)(& ...and so on, well from what I read in your question you use the input that is gathered from the user to send it in a database, which in this case if is a database you need to avoid sending again I say "strange" characters, well... If this is the case then, I made a quick app. to show how you can avoid that here is the code:

    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    import sys
    
    
    class main_window(QDialog):
        def __init__(self):
            QDialog.__init__(self)
    
            # Create QLineEdit
            le_username = QLineEdit(self)
            le_username.setPlaceholderText("Enter username")
            le_password = QLineEdit(self)
            le_password.setPlaceholderText("Enter password")
    
            # Create QLabel
            lb_username = QLabel("Username: ")
            lb_password = QLabel("Password: ")
    
            # Adding a layout
            self.setLayout(QVBoxLayout())
    
    
            # Adding widgets to layout
            self.layout().addWidget(lb_username)
            self.layout().addWidget(le_username)
    
    
            self.layout().addWidget(lb_password)
            self.layout().addWidget(le_password)
    
    
            #!! ReGex implementation !!
            # For more details about ReGex search on google: regex rules or something similar 
            reg_ex = QRegExp("[a-z-A-Z_]+")
            le_username_validator = QRegExpValidator(reg_ex, le_username)
            le_username.setValidator(le_username_validator)
            #!! ReGex implementation End !!
    
    
            #.......
            self.setMinimumWidth(200)
            self.setWindowTitle("ReGEX Validator in Python with Qt Framework")
    
    app = QApplication(sys.argv)
    dialog = main_window()
    dialog.show()
    sys.exit(app.exec_())
    

    I hope that this help you out to figure how to filter user input in a QLineEdit, or anywhere where you got an user input based on characters...

    0 讨论(0)
提交回复
热议问题