Reputation: 117
Problem to combine a setInputMask and setValidator IPv4 Address into a QlineEdit
I have a QLineEdit to set my IPv4 address. In the first time, I set my QLineEdit with setInputMask to have " . . . " In the second time, I'm using a Ip Validator to check if it's a IP address
The problem is when I'm using separately, it's working but together, I can't edit my QLineEdit...
self.lineEdit_IP = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_IP.setGeometry(120,0,160,30)
self.lineEdit_IP.setStyleSheet("background-color: rgb(255, 255, 255);")
self.lineEdit_IP.setAlignment(QtCore.Qt.AlignHCenter)
self.lineEdit_IP.setInputMask("000.000.000.000")
#Set IP Validator
regexp = QtCore.QRegExp('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){0,3}$')
validator = QtGui.QRegExpValidator(regexp)
self.lineEdit_IP.setValidator(validator)
Upvotes: 2
Views: 3159
Reputation: 319
Setting up a mask for QLine changes it's contents from empty to specified symbols. In your case "empty" QLine actually looks like "...". That's why regex failed. You could use your own overridden validator:
class IP4Validator(Qt.QValidator):
def __init__(self, parent=None):
super(IP4Validator, self).__init__(parent)
def validate(self, address, pos):
if not address:
return Qt.QValidator.Acceptable, pos
octets = address.split(".")
size = len(octets)
if size > 4:
return Qt.QValidator.Invalid, pos
emptyOctet = False
for octet in octets:
if not octet or octet == "___" or octet == " ": # check for mask symbols
emptyOctet = True
continue
try:
value = int(str(octet).strip(' _')) # strip mask symbols
except:
return Qt.QValidator.Intermediate, pos
if value < 0 or value > 255:
return Qt.QValidator.Invalid, pos
if size < 4 or emptyOctet:
return Qt.QValidator.Intermediate, pos
return Qt.QValidator.Acceptable, pos
and use it like this
validator = IP4Validator()
self.ipAddrLineEdit.setValidator(validator)
with masks like "000.000.000.000;_" or "000.000.000.000; " <--with whitespace at the end
Upvotes: 2