6.3 QValidator文本内容限定

一、QValidator文本内容限定

1.概念

*这里通过一个类QValidator来实现自动判断和限定文本框的内容,保证内容的正确性。

setPlaceholderText()
placeholderText()

文本内容限定(18-150):
QValidator.Acceptable    #接受状态
QValidator.Intermediate  #容错状态
QValidator.Invalid       #无效状态

2.代码

from PyQt5.Qt import *
import sys

#创建子类
class Validator(QValidator) :
    def validate(self, num, pos) :
        print(num, pos)
        try :
            if 18 <= int(num) <= 150 :  #在正确的范围内,就返回结果
                return (QValidator.Acceptable, num, pos) #元组(容错状态,数值,光标的位置)
            elif 1 <= int(num) <= 14 :  #在输入为正确值之前,容错
                return (QValidator.Intermediate, num, pos)
            else :
                return (QValidator.Invalid, num, pos)#其他范围输入结果
        except :
            if len(num) == 0 :  #如果字符长度为0,返回容错
                return (QValidator.Intermediate, num, pos)
            return (QValidator.Invalid, num, pos) #其他无效

    #如果光标移动到其他的位置,对于输入框内的字符自动补全为18
    def fixup(self, v_str) :
        try :
            if int(v_str) < 18 : #<18 都返回18
                return '18'
        except :                # 空字符串 也返回18
            return '18'


class My_int(QIntValidator) :
    def fixup(self, v_str) :
        print('XXX', v_str)
        try :
            if int(v_str) < 18 :
                return '18'
        except :
            return '18'


class Window(QWidget) :
    def __init__(self) :
        super().__init__()
        self.setWindowTitle("QLineEdit-验证器 - PyQt5中文网")
        self.resize(600, 500)
        self.func_list()

    def func_list(self) :
        self.func()

    def func(self) :
        led = QLineEdit(self)
        led.move(150, 150)

        led1 = QLineEdit(self)
        led1.move(150, 220)

        validator = Validator()  # 这个抽象类需要子类化
        led.setValidator(validator)  #在调用




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

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

3.实现效果

posted @   Trouvaille_fighting  阅读(661)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示

目录导航