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.实现效果


浙公网安备 33010602011771号