1 """验证器""" 2 import sys 3 from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QFormLayout 4 from PyQt5.QtGui import QIntValidator, QDoubleValidator, QRegExpValidator 5 from PyQt5.QtCore import QRegExp 6 7 8 class lineEditDemo(QWidget): 9 def __init__(self): 10 super().__init__() 11 self.setWindowTitle("QLineEdit例子") 12 13 flo = QFormLayout() 14 pIntLineEdit = QLineEdit() 15 pDoubleLineEdit = QLineEdit() 16 pValidatorLineEdit = QLineEdit() 17 18 19 flo.addRow("整型", pIntLineEdit) 20 flo.addRow("浮点型", pDoubleLineEdit) 21 flo.addRow("字母和数字", pValidatorLineEdit) 22 23 pIntLineEdit.setPlaceholderText("整型") 24 pDoubleLineEdit.setPlaceholderText("浮点型") 25 pValidatorLineEdit.setPlaceholderText("字母和数字") 26 27 # 整形,范围:[1,99] 28 pIntValidator = QIntValidator(self) 29 pIntValidator.setRange(1, 99) 30 31 # 浮点型范围[-360, 360],精度小数点后两位 32 pDoubleValidator = QDoubleValidator(self) 33 pDoubleValidator.setRange(-360, 360) 34 pDoubleValidator.setNotation(QDoubleValidator.StandardNotation) 35 pDoubleValidator.setDecimals(2) 36 37 # 字母和数字 38 reg = QRegExp("[a-zA-Z0-9]+ $") 39 pValidator = QRegExpValidator(self) 40 pValidator.setRegExp(reg) 41 42 # 设置验证器 43 pIntLineEdit.setValidator(pIntValidator) 44 pDoubleLineEdit.setValidator(pDoubleValidator) 45 pValidatorLineEdit.setValidator(pValidator) 46 47 48 self.setLayout(flo) 49 50 if __name__ == '__main__': 51 app = QApplication(sys.argv) 52 win = lineEditDemo() 53 win.show() 54 sys.exit(app.exec_())