PyQt5实现QLineEdit正则表达式输入验证器_python

来源:脚本之家  责任编辑:小易  

本文主要介绍了QLineEdit正则表达式输入验证器,分享给大家,具体如下:

from PyQt5 import QtWidgets, QtCore, QtGui, Qt
import re

############## QLineEdit正则表达式输入验证器
class LineEditRegExpValidator(QtGui.QValidator):

  '''
  # 默认为科学计数法输入验证器

  用法
  SciNotValidator = LineEditRegExpValidator() # 创建一个QLineEdit正则表达式输入验证器的类,默认为科学计数法输入验证器

  self.LineEdit1.setValidator(SciNotValidator) # 设置验证器(启用)
  self.LineEdit1.installEventFilter(SciNotValidator) # QLineEdit清空内容且游标失焦时,自动填充上一次的字符串内容

  self.LineEdit2.setValidator(SciNotValidator)
  self.LineEdit2.installEventFilter(SciNotValidator)

  self.LineEdit3.setValidator(SciNotValidator)
  self.LineEdit3.installEventFilter(SciNotValidator)

  Validator.validate() is abstract and must be overriddenValidator.validate() is abstract and must be overridden
  '''

  def __init__(
    self, 

    # 编辑状态框输入结束允许的字符串
    fullPatterns=[
      r"[+|-]?[0-9]+\.?[0-9]*(?:[Ee][+|-]?[0-9]+)?", 
      r'[+|-]{0,1}nan', r'[+|-]{0,1}inf'
      ], 
    
    # 编辑状态框输入尚未结束允许的字符串
    partialPatterns=[
      r'[+|-]?[0-9]+\.?[0-9]*(?:[Ee][+|-]?)?', 
      r'-', 
      r'\+', 
      r'[+|-]{0,1}nan', 
      r'[+|-]{0,1}na', 
      r'[+|-]{0,1}n', 
      r'[+|-]{0,1}inf', 
      r'[+|-]{0,1}in', 
      r'[+|-]{0,1}i'
      ],
    
    fixupString='1.0'
    ):

    super(LineEditRegExpValidator, self).__init__()
    self.fullPatterns = fullPatterns
    self.partialPatterns = partialPatterns
    self.fixupString = fixupString
  

  # 实时监听文本框的改变
  # 可能是键盘单个字符'n'输入, 也有可能是粘贴多个字符'nan'输入
  def validate(self, string, pos) -> QtGui.QValidator.State: # string为编辑状态框中可见的字符串+输入字符/字符串

    # 编辑过程结束,若返回True,将编辑状态框中的字符串填入LineEdit,若返回Flase则自动调用self.fixup方法,将fixup方法返回的字符串填入LineEdit
    if self.acceptable_check(string):
      #print(f'QtGui.QValidator.Acceptable:{QtGui.QValidator.Acceptable}')
      return QtGui.QValidator.Acceptable, string, pos # QtGui.QValidator.Acceptable = 2; 
    

    # 编辑过程中允许出现的字符串
    if self.intermediate_check(string):
      #print(f'QtGui.QValidator.Intermediate:{QtGui.QValidator.Intermediate}')
      return QtGui.QValidator.Intermediate, string, pos # QtGui.QValidator.State = 1;
    # 编辑过程中不允许出现的字符串(本次输入的单个字符或字符串无效)
    else:
      #print(f'QtGui.QValidator.Invalid:{QtGui.QValidator.Invalid}')
      return QtGui.QValidator.Invalid, string, pos


  # 编辑状态框验证通过, 编辑状态框单个字输入符成功
  def acceptable_check(self, string) -> bool:
    True_ = 0
    for fullPattern in self.fullPatterns:
      if re.fullmatch(fullPattern, string):
        True_ += 1
      else:
        continue
    if True_ != 0:
      return True
    else:
      return False

  # 输入还未结束允许的字符串
  def intermediate_check(self, string): #-> bool;  string为编辑状态框中可见的字符串
    """
    Checks if string makes a valid partial float, keeping in mind locale dependent decimal separators.
    """
    if string == '':
      return True
    for partialPattern in self.partialPatterns:
      if re.fullmatch(partialPattern, string):
        return True
      else:
        pass

  # 
  def eventFilter(self, lineEdit, event): # -> bool
    # FocusIn event
    # 每当fous in时,更新LineEditRegExpValidator的fixupString
    # 输入验证器
    '''
    SciNotValidator = LineEditRegExpValidator()

    self.LineEdit1.setValidator(SciNotValidator)
    self.LineEdit1.installEventFilter(SciNotValidator)
    '''

    if event.type() == QtCore.QEvent.FocusIn:
      # do custom stuff
      # print('focus in')

      # self.lineEdit_zhuansu.installEventFilter(SciNotValidator), 在本类中,widget是self.lineEdit,执行函数self.lineEdit.text(), 其它类不一定有text()方法

      #lineEdit.selectAll()
      QtCore.QTimer.singleShot(0, lineEdit.selectAll) # 0ms
      self.fixupString = lineEdit.text()

      #print(self.fixupString)
      # return False so that the lineEdit will also handle the event
      # otherwise it won't focus out
      return False
    else:
      # we don't care about other events
      return False

  # 重写QValidator的fixup(str)方法。可以在切换焦点后,直接修改不合规则的字符串。参数str是经过validate()方法验证后的字符串;
  def fixup(self, string) -> str:
    """
    Fixes up input text to create a valid float. Puts an empty string on failure.
    """
    print(string)

    True_ = 0
    for fullPattern in self.fullPatterns:
      if re.fullmatch(fullPattern, string):
        True_ += 1
      else:
        continue
    if True_ != 0:
      return string
    else:
      return self.fixupString


# listWidget、tableWidget输入数据检查
class LineEditDelegate_Regx(QtWidgets.QStyledItemDelegate):
 # 科学计数法正则表达式
  regx = r"-?\ *[0-9]+\.?[0-9]*(?:[Ee]\ *-?\ *[0-9]+)?" #
  """
  -?    optionally matches a negative sign (zero or one negative signs)
  \ *    matches any number of spaces (to allow for formatting variations like - 2.3 or -2.3)
  [0-9]+  matches one or more digits
  \.?    optionally matches a period (zero or one periods)
  [0-9]*  matches any number of digits, including zero
  (?: ... ) groups an expression, but without forming a "capturing group" (look it up)
  [Ee]   matches either "e" or "E"
  \ *    matches any number of spaces (to allow for formats like 2.3E5 or 2.3E 5)
  -?    optionally matches a negative sign
  \ *    matches any number of spaces
  [0-9]+  matches one or more digits
  ?     makes the entire non-capturing group optional (to allow for the presence or absence of the exponent - 3000 or 3E3

  https://stackoverflow.com/questions/18152597/extract-scientific-number-from-string
  """

  """
  用法:
  def __init__(self, parent=None):
    super(NewClassName, self).__init__(parent)
    self.setupUi(self)

    delegate = LineEditDelegate_Regx(regx=None)
    self.listWidget_ShuZhiLieBiao.setItemDelegate(delegate)
    self.tableWidget.setItemDelegate(delegate)
  """
  def __init__(self, regx=None, parent=None):
    super(LineEditDelegate_Regx, self).__init__(parent)
    if regx == None:
      pass
    else:
      self.regx = regx

  # 方法重写
  def createEditor(self, parent, option, index): # self, parent, option, index四个参数均不能少
    editor_qlineedit = QtWidgets.QLineEdit(parent)
    #SciNotValidator = QtGui.QRegExpValidator(QtCore.QRegExp(self.regx))
    SciNotValidator = LineEditRegExpValidator()
    editor_qlineedit.setValidator(SciNotValidator)
    return editor_qlineedit # LineEditDelegate_Regx(regx=None, parent=None), QStyledItemDelegate(parent: QObject = None)

"""
# LineEdit输入数据检查
def LineEditInputChecking(lineEdit, regx=None):
  '''
  用法:
  LineEditInputChecking(lineEdit=self.lineEdit_zhuansu)
  '''
  if regx == None:
    regx = r"-?\ *[0-9]+\.?[0-9]*(?:[Ee]\ *-?\ *[0-9]+)?"
  reg_ex = QtCore.QRegExp(regx)
  input_validator = QtGui.QRegExpValidator(reg_ex, lineEdit)
  lineEdit.setValidator(input_validator)
"""

参考:

https://stackoverflow.com/questions/39202697/qt-qlineedit-input-validation

https://stackoverflow.com/questions/15829782/how-to-restrict-user-input-in-qlineedit-in-pyqt

到此这篇关于PyQt5实现QLineEdit正则表达式输入验证器的文章就介绍到这了,更多相关PyQt5 QLineEdit验证器内容请搜索真格学网以前的文章或继续浏览下面的相关文章希望大家以后多多支持真格学网!

您可能感兴趣的文章:PyQt5 QLineEdit输入的子网字符串校验QRegExp实现PyQt5 文本输入框自动补全QLineEdit的实现示例python GUI库图形界面开发之PyQt5单行文本框控件QLineEdit详细使用方法与实例PyQt5实现QLineEdit添加clicked信号的方法在pyqt5中QLineEdit里面的内容回车发送的实例

  • 本文相关:
  • python字典的基本用法实例分析【创建、增加、获取、修改、删除】
  • 基于python3.7.1无法导入numpy的解决方式
  • 如何运行带参数的python脚本
  • python 3.8新特征之asyncio repl
  • python3标准库glob文件名模式匹配的问题
  • python回调函数中使用多线程的方法
  • python使用mysqldb连接数据库操作方法示例详解
  • 使用python标准库中的wave模块绘制乐谱的简单教程
  • python 除法保留两位小数点的方法
  • 跟老齐学python之一个免费的实验室
  • pyqt5如何做正则表达式验证软件
  • PyQt5 lineEdit 控件输入内容直接写在程序里怎么实现?
  • python PyQt4中如何获得QTextEdit的内容获得QLineE...
  • python 判断正则表达式
  • 用python正则表达式怎么从短信中提取验证码
  • Python 有关PyQt5的问题
  • 可以用pyqt的python代码实现类似手机便签记事的功能吗
  • python安装PyQt检测是否成功时弹出这样的窗口是什...
  • 用pyqt5,怎样从c++的QWebChannel示例改写成python...
  • pyqt5 从下拉列选后一一添加到lineedit?
  • 网站首页网页制作脚本下载服务器操作系统网站运营平面设计媒体动画电脑基础硬件教程网络安全vbsdos/bathtahtcpythonperl游戏相关vba远程脚本coldfusionruby专题autoitseraphzonepowershelllinux shellluagolangerlang其它首页pyqt5 qlineedit输入的子网字符串校验qregexp实现pyqt5 文本输入框自动补全qlineedit的实现示例python gui库图形界面开发之pyqt5单行文本框控件qlineedit详细使用方法与实例pyqt5实现qlineedit添加clicked信号的方法在pyqt5中qlineedit里面的内容回车发送的实例python字典的基本用法实例分析【创建、增加、获取、修改、删除】基于python3.7.1无法导入numpy的解决方式如何运行带参数的python脚本python 3.8新特征之asyncio replpython3标准库glob文件名模式匹配的问题python回调函数中使用多线程的方法python使用mysqldb连接数据库操作方法示例详解使用python标准库中的wave模块绘制乐谱的简单教程python 除法保留两位小数点的方法跟老齐学python之一个免费的实验室python入门教程 超详细1小时学会pycharm 2020最新永久激活码(附python 列表(list)操作方法详解python 元组(tuple)操作详解python 字典(dictionary)操作详解python strip()函数 介绍pycharm 使用心得(一)安装和首pycharm 2020年最新激活码(亲测python 中文乱码问题深入分析python中使用xlrd、xlwt操作excepyqt5高级界面控件之qtablewidget的具体使python实现cnn的多通道输入实例python入门教程 超详细1小时学会pythonpython用于url解码和中文解析的小脚本(pypython append、extend与insert的区别对python _取log的几种方式小结详解scrapy redis入门实战python处理菜单消息操作示例【基于win32upython gui库图形界面开发之pyqt5线程类qpython异常处理之try finally不报错的原因
    免责声明 - 关于我们 - 联系我们 - 广告联系 - 友情链接 - 帮助中心 - 频道导航
    Copyright © 2017 www.zgxue.com All Rights Reserved