3
\$\begingroup\$

This class is similar to QDoubleValidator, but it improves slightly on the editing comfort. The comments mention "comma" but it's actually the decimal point of your locale (comma for me).

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            # When we're left of the comma, and comma is pressed,
            # remove the inserted comma and move right of the old comma.
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            # When we're right of the comma, and all decimal places are used already,
            # go into overwrite mode (by removing the old digit)
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)
\$\endgroup\$
2

1 Answer 1

3
\$\begingroup\$

I noticed your commenting style and decided it's worthy of it's own answer.

You admit the comma is not always a comma. So don't call it a comma. I went for separator, which is as neutral as it gets. If you think of something better, go for it.

Also, I think your comments would fit better as a docstring than as comments.

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        '''
        When we're left of the separator, and separator is pressed,
        remove the inserted separator and move right of the old separator.
        When we're right of the separator, and all decimal places are used already,
        go into overwrite mode (by removing the old digit)
        '''
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)
\$\endgroup\$
1
  • \$\begingroup\$ You're right about the "comma" topic (I noticed that myself. Just wasn't happy calling it a "decimal point" as called in the QLocale class), Docstring at the beginning of the function isn't what I wanted. I wanted the comments to explain the code that they preceed. \$\endgroup\$
    – Sebastian
    Commented Nov 10, 2015 at 0:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.