0

As you know, QIntValidator and QDoubleValidator are preventing user type alphabetic charracters. Also these validators have bottom and top boundaries to prevent user insert a digit below or above the boundaries, BUT these boundaries are not working very well as its documents said. For instance if you add an QIntValidator like this:

self.setValidator(QIntValidator(0,10))

user can type number 99 which is very greater than 10. And that 10 is just define user can insert digits with 2 units. By looking at the documents and you can findout that these validators have validate() method which you can override this method and change the behavior to user couldn't type a number more 10!

1 Answers1

1

You can override these classes like below and check if the number is not in the boundary then add 0 at the index of the res tuple which means invalid:

class IntValidator(QIntValidator):

    def validate(self, a0: str, a1: int):
        """
        Overwrite this method to add better restriction
        when user type a value.
        It checks if the value user inserted is not in
        the boundaries, then prevent typing more than of
        the boundaries.
        """
        res = super().validate(a0, a1)
        try:
            if not self.bottom() <= int(a0) <= self.top():
                res = (0, a0, a1)
        except ValueError:
            return res
        return res

and in your widget class:

self.setValidator(IntValidator(0,10))
  • It should be noted that this will *only* work as long as the minimum is equal to 0 or less than the maximum/10, in any other case it will prevent the user to properly type values: for instance, if the range is 2-10, they won't be able to type 10 because the first typed character would be 1, which is outside the range. That's exactly the reason for which Qt numeric validators work like they do. – musicamante Aug 18 '22 at 22:31