Search code examples
pythonpyqtqlineedit

QLineEdit Accepts Only Character in PyQt4


I have written a method that validate characters in the lineEdit:

 def is_validate(self):
    regex = QtCore.QRegExp("[a-z-A-Z_]+")
    txtDepartment_validator = QtGui.QRegExpValidator(regex, self.txtDepartment)
    self.txtDepartment.setValidator(txtDepartment_validator)
    return True

and use it another method like below

def control_information(self):
    if(self.is_validate()):
        //Database operations
    else:
        QtGui.QMessageBox.text("Please enter valid characters")

But when I enter numbers or special character it accepts and save to database. What is wrong?


Solution

  • The validator is there to replace a method like is_validate. You don't need this method.
    The issue is that you set the validator after the user has typed, so it's already too late.

    You should set the validator once, when you create the line edit:

    self.line=QtGui.QLineEdit()
    regex=QtCore.QRegExp("[a-z-A-Z_]+")
    validator = QtGui.QRegExpValidator(regex)
    self.line.setValidator(validator)
    

    Then, it's impossible for the user to type any special characters in the line edit. Every time the user types, the validator checks if the character is allowed. It it's not allowed, it is not added to the line edit. No need for is_validate any more.