PyQt5-组件控件-setValidator验证过滤器控件基本使用(三)

样式一
样式二
直接上代码:

import re
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QLineEdit
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QPushButton, QMessageBox


class NumericTextBox(QLineEdit):
    def __init__(self, *args):
        super(NumericTextBox, self).__init__()
        __regExp = QtCore.QRegExp('^(?!0)\d{1,6}\.\d{1,2}$')
        self.setValidator(QtGui.QRegExpValidator(__regExp, self))
        self.textChanged.connect(self.onValueChanged)

    def setPositiveAndNegativeInterval(self):
        regExp = QtCore.QRegExp('^(\-?)\d{1,6}\.\d{1,2}$')
        self.setValidator(QtGui.QRegExpValidator(regExp, self))

    def onValueChanged(self):
        pass
        # try:
        #     text = self.text()
        #     if text.__len__() > 1 or text[-1] != ".":
        #         self.setText(str((float(text))))
        # except Exception:
        #     print(Exception)

    def getIntValue(self):
        return int(self.text())

    def getFloatValue(self):
        return float(self.text())



class testNumericTextBox(QWidget):
    def __init__(self):
        super(testNumericTextBox, self).__init__()
        self.initUI()

    def initUI(self):
        self.box = QHBoxLayout()
        # 创建文本框
        regExp1 = QtCore.QRegExp('^\d{1,6}\.\d{1,2}$')
        self.text1 = QLineEdit()
        # 表单布局添加名称及控件
        self.box.addWidget(self.text1)
        self.btn = QPushButton("确认")
        self.box.addWidget(self.btn)

        # 设置文本框的默认浮现文本
        self.text1.setPlaceholderText("可输入范围0-10000")
        # 设置校验
        self.text1.setValidator(QtGui.QRegExpValidator(regExp1, self))
        self.setLayout(self.box)
        self.btn.clicked.connect(self.setUsefulRange)

    def setUsefulRange(self):
        text = self.text1.text()
        if text == '':
            print("数值为空")
            QMessageBox.information(self, "提示信息", "数值为空")
        else:
            if re.match('.+\.$', text) or re.match('^0\d0$', text):
                print("格式不正确:{}".format(text))
                # isClearButtonEnabled()
                QMessageBox.information(self, "提示信息", "格式不正确:{}".format(text))
            elif float(text) <= 100000:
                print("数值确认:{}".format(text))
                # isClearButtonEnabled()
                QMessageBox.information(self, "提示信息", "数值确认:{}".format(text))
            else:
                print("数值超出范围0-100000:{}".format(text))
                # isClearButtonEnabled()
                QMessageBox.information(self, "提示信息", "数值超出范围0-100000:{}".format(text))
                # raise Exception("Only input positive number")


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

两种方法实现,可自行参考使用

你可能感兴趣的:(python,PyQt-控件开发与实战,组件控件)