【问题标题】:QIntValidator and QDoubleValidator min and max value not workingQIntValidator 和 QDoubleValidator 最小值和最大值不起作用
【发布时间】:2022-08-19 04:29:02
【问题描述】:

如您所知,QIntValidator 和 QDoubleValidator 正在阻止用户键入字母字符。这些验证器还具有底部和顶部边界,以防止用户在边界下方或上方插入数字,但正如其文档所述,这些边界工作得很好。例如,如果您像这样添加 QIntValidator:

self.setValidator(QIntValidator(0,10))

用户可以键入比 10 大得多的数字 99。而 10 只是定义用户可以插入 2 个单位的数字。通过查看文档,您可以发现这些验证器具有 validate() 方法,您可以覆盖此方法并将行为更改为用户不能输入更多的数字 10!

    标签: python qt pyqt


    【解决方案1】:

    您可以像下面这样覆盖这些类并检查数字是否不在边界内,然后在 res 元组的索引处添加 0,这意味着无效:

    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
    

    在你的小部件类中:

    self.setValidator(IntValidator(0,10))
    

    【讨论】:

      猜你喜欢
      • 2015-04-08
      • 1970-01-01
      • 2022-08-08
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多