Jan 15, 2010


QDoubleValidator is strange in that it seems to allow data that exceeds its specified range. Actually, it passes with the state 'intermediate', as opposed to 'valid' or 'invalid'. This may seem like a bug, and has been addressed in the C++ language here. Below is my PyQt implementation. It is done by subclassing QDoubleValidator, and making it more strict. (Finally it worked! =P)

class MyDoubleValidator(Qt.QDoubleValidator):
def __init__(self, bottom, top, decimals, parent = None):
Qt.QDoubleValidator.__init__(self, bottom, top, decimals, parent)

def validate(self, input, pos):
state, pos = Qt.QDoubleValidator.validate(self, input, pos)
if input.isEmpty() or input == '.':
return Qt.QValidator.Intermediate, pos
if state != Qt.QValidator.Acceptable:
return Qt.QValidator.Invalid, pos
return Qt.QValidator.Acceptable, pos

You then need to initialize an instance of this class and assign it to the widget, e.g. a lineEdit. E.g:

min = 0
max = 1000
no_decimals = 10
aValidator = MyDoubleValidator(min, max, no_decimals, myLineEdit)

Extra tags:
QDoubleValidator, bug, outside range, not working, QValidator, State