QLineEdit Accepts Only Character in PyQt4
Asked Answered
F

2

7

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?

Fountain answered 21/12, 2015 at 15:48 Comment(0)
C
7

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.

Centrifugate answered 21/12, 2015 at 16:1 Comment(0)
B
4

if you want your text line in python to accept only numbers (int) you can change it like this :

    regex = QRegExp("[0-9_]+")
    validator = QRegExpValidator(regex)
    self.tb3.setValidator(validator)
Bicyclic answered 23/4, 2017 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.