Checking QValidator Status

First off, sorry for my bad english.

I am trying to get an IP address from a user. I use QRegExpValidator to validate user input. The validator successfully blocks unwanted characters. But I want to know that this is the correct IP address when the user clicked the button. Of course, I can check the text manually, but it seems to be the best way using the QValidator state enumeration. QValidator.Acceptable is what I need to check. But I can’t understand how I can use it.

Here is what I need to use: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qvalidator.html#State-enum

And here is what I tried (abstracts from the main program):

from PyQt4 import QtCore, QtGui from functools import partial class Gui(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self) editLayout=QtGui.QFormLayout() edit=QtGui.QLineEdit() edit.setMinimumWidth(125) regex=QtCore.QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") validator=QtGui.QRegExpValidator(regex, edit) edit.setValidator(validator) editLayout.addRow("Enter Client IP:", edit) button=QtGui.QPushButton("Add Client") button.clicked.connect(partial(self.addClientButtonClicked, edit, validator)) layout=QtGui.QVBoxLayout() layout.addLayout(editLayout) layout.addWidget(button) self.setLayout(layout) def addClientButtonClicked(self, edit, validator): print("ip=", edit.text()) print(validator.State==QtGui.QValidator.Intermediate) app=QtGui.QApplication([]) g=Gui() g.show() app.exec_() 

Required Conclusion:

 ip= 192.168. False ip= 192.168.2.1 True 

But here is what I get:

 ip= 192.168. False ip= 192.168.2.1 False 

What is the correct way to check the status of QValidator?

+2
source share
1 answer

You are not doing the right thing here. Comparison:

 validator.State==QtGui.QValidator.Intermediate 

Compares an enum type with one of its values ​​- it will always be False !

Use validate instead:

 def addClientButtonClicked(self, edit, validator): print("ip=", edit.text()) print(validator.validate(edit.text(), 0)) 

Then the result for 192.168.2.1 is:

 ('ip=', PyQt4.QtCore.QString(u'192.168.2.1')) (2, 0) 

The first element of the tuple returned by validate is a state that you can compare with the various QValidator states:

 def addClientButtonClicked(self, edit, validator): state, pos = validator.validate(edit.text(), 0) print(state == QtGui.QValidator.Acceptable) 

True print for 192.168.2.1

+3
source

All Articles