最近学习pyqt5,浮点数,整型数据验证器解决办法

一、浮点数数据验证器解决办法

pyqt5 提供了double类型输入验证器,QDoubleValidator() ,

这里有个坑,虽然定义了doubleValidator.setRange (-100, 100, 2),但是在QLineEdit中可以输入的范围却可以超过-100-100之间的范围。所以针对这个问题,解决办法如下,供各位参考。

实现功能:

(1)可以设定任意范围的浮点数数据验证器

(2)当输入数据超过数据范围时,则取范围最大值,如输入数据小于范围时,去最小值

(3)如果输入数据如“100.”,则显示100。如果过输入数据仅为“-”,则取最小值

代码如下。

import sys
from PyQt5.Qt import *

class FloatRangeValidator(QDoubleValidator):
    def __init__(self, bottom, top, parent=None):
        super().__init__()
        self.bottom = bottom
        self.top = top

    def validate(self, input, pos):
        """
        文本框设置了验证后,当内容发生改变时调用该方法
        :param input: 文本框内容
        :param pos: 光标位置
        :return: 返回验证状态
                 QValidator.Acceptable:验证通过
                 QValidator.Intermediate:暂不验证,文本框失去焦点时调用fixup()方法进行验证
                 QValidator.Invalid:验证不通过
        """
        print(input, pos)
        try:
            if input == "-":
                return (QValidator.Intermediate, input, pos)
            if self.bottom <= float(input) <= self.top:
                print("在区间范围内:", float(input))
                if input[-1] != ".":
                    return (QValidator.Acceptable, input, pos)
                else:
                    return (QValidator.Intermediate, input, pos)
                # return (QValidator.Intermediate, input, pos)
            elif float(input) > self.top:
                print("超范围:", float(input))
                return (QValidator.Intermediate, input, pos)
            else:
                print("低于范围:", float(input))
                return (QValidator.Intermediate, input, pos)
        except Exception as ep:
            print("错误", ep)
            if len(input) == 0:
                print("长度为0")
                return (QValidator.Intermediate, input, pos)
            return (QValidator.Invalid, input, pos)

    def fixup(self, input: str):
        try:
            if float(input) > self.top:
                print("超过最大值:", float(input))
                return str(self.top)
            elif float(input) < self.bottom:
                return str(self.bottom)
            else:
                if input[-1] == ".":
                    return input[:-1]
        except:
            return str(self.bottom)

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        le = QLineEdit()
        le.setPlaceholderText("请输入-100-100之间的浮点数")
        le1 = QLineEdit(self)
        le.setParent(self)
        le.move(100,300)
        le1.move(100,400)
        floatValidator = FloatRangeValidator(-100, 100)
        le.setValidator(floatValidator)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

二 整型数据验证器代码

实现功能:

(1)可以设定任意范围的整型数据验证器

(2)当输入数据超过数据范围时,则取范围最大值,如输入数据小于范围时,去最小值

(3)如果过输入数据仅为“-”,则取默认值

import sys
from PyQt5.Qt import *

class IntRangeValidator(QIntValidator):
    def __init__(self, bottom, top,default_value, parent=None):
        super().__init__()
        self.bottom = bottom
        self.top = top
        self.default_value = default_value

    def validate(self, input, pos):
        """
        文本框设置了验证后,当内容发生改变时调用该方法
        :param input: 文本框内容
        :param pos: 光标位置
        :return: 返回验证状态
                 QValidator.Acceptable:验证通过
                 QValidator.Intermediate:暂不验证,文本框失去焦点时调用fixup()方法进行验证
                 QValidator.Invalid:验证不通过
        """
        print(input, pos)
        try:
            if input == "-":
                print("---",input)
                return (QValidator.Intermediate, input, pos)
            if self.bottom <= int(input) <= self.top:
                print("在区间范围内:", int(input))
                return (QValidator.Acceptable, input, pos)
                # if input[-1] != ".":
                #     return (QValidator.Acceptable, input, pos)
                # else:
                #     return (QValidator.Intermediate, input, pos)
                # return (QValidator.Intermediate, input, pos)
            elif int(input) > self.top:
                print("超范围:", int(input))
                return (QValidator.Intermediate, input, pos)
            else:
                print("低于范围:", int(input))
                return (QValidator.Intermediate, input, pos)
        except Exception as ep:
            print("错误", ep)
            if len(input) == 0:
                print("长度为0")
                return (QValidator.Intermediate, input, pos)
            return (QValidator.Invalid, input, pos)

    def fixup(self, input: str):
        try:
            if int(input) > self.top:
                print("超过最大值:", int(input))
                return str(self.top)
            elif int(input) < self.bottom:
                return str(self.bottom)
            else:
                return input
        except:
            return str(self.default_value)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    window.resize(300,400)
    lineEdit1 = QLineEdit(window)
    validator1 = IntRangeValidator(-50,300,273)
    lineEdit1.setValidator(validator1)
    lineEdit2 = QLineEdit(window)
    lineEdit2.move(100,200)
    # window.


    window.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值