Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
Cahit Yıldırım Avatar asked Dec 21 '15 15:12

Cahit Yıldırım


People also ask

How to set text in QLineEdit?

You can change the text with setText() or insert() . The text is retrieved with text() ; the displayed text (which may be different, see EchoMode ) is retrieved with displayText() . Text can be selected with setSelection() or selectAll() , and the selection can be cut() , copy() ied and paste() d.

What is QLineEdit in PyQt5?

QLineEdit : It allows the user to enter and edit a single line of plain text with a useful collection of editing functions, including undo and redo, cut and paste, and drag and drop. It is the basic widget in PyQt5 to receive keyboard input, input can be text, numbers or even symbol as well.

How to use QValidator?

To use a QValidator , create an instance of it then apply it to a QLineEdit using the setValidator method. The example below uses a QDoubleValidator to ensure that only text representing a valid double (i.e. a real number) can be input. Multiple widgets can share a single QValidator instance.


1 Answers

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.

like image 65
Mel Avatar answered Sep 23 '22 17:09

Mel