Jan 15, 2010

QDoubleValidator

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)
myLineEdit.setValidator(aValidator)

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

3 comments:

  1. Thanks - you save me some hours :) Here is my version with fixed identation a default values: https://gist.github.com/4473639

    ReplyDelete
  2. Thanks a lot !!! i just have to fix this bug on my old applications and the users will be happy !

    ReplyDelete

So, what did you think?