【问题标题】:PyQt5 QLine setInputMask + setValidator IP addressPyQt5 QLine setInputMask + setValidator IP 地址
【发布时间】:2018-12-20 17:49:15
【问题描述】:

将 setInputMask 和 setValidator IPv4 地址组合到 QlineEdit 中的问题

我有一个 QLineEdit 来设置我的 IPv4 地址。 第一次,我用 setInputMask 将我的 QLineEdit 设置为“......” 第二次,我使用 Ip Validator 来检查它是否是 IP 地址

问题是当我单独使用时,它可以工作,但一起使用时,我无法编辑我的 QLineEdit...

self.lineEdit_IP = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_IP.setGeometry(120,0,160,30)
self.lineEdit_IP.setStyleSheet("background-color: rgb(255, 255, 255);")
self.lineEdit_IP.setAlignment(QtCore.Qt.AlignHCenter)
self.lineEdit_IP.setInputMask("000.000.000.000")
#Set IP Validator
regexp = QtCore.QRegExp('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){0,3}$')
validator = QtGui.QRegExpValidator(regexp)
self.lineEdit_IP.setValidator(validator)

【问题讨论】:

  • 尝试将self.lineEdit_IP.setInputMask ("000.000.000.000")更改为self.lineEdit_IP.setInputMask ("000.000.000.000;0")

标签: python pyqt pyqt5 qlineedit


【解决方案1】:

为 QLine 设置掩码会将其内容从空更改为指定符号。在您的情况下,“空”QLine 实际上看起来像“...”。这就是正则表达式失败的原因。 您可以使用自己的重写验证器:

class IP4Validator(Qt.QValidator):
    def __init__(self, parent=None):
        super(IP4Validator, self).__init__(parent)

    def validate(self, address, pos):
        if not address:
            return Qt.QValidator.Acceptable, pos
        octets = address.split(".")
        size = len(octets)
        if size > 4:
            return Qt.QValidator.Invalid, pos
        emptyOctet = False
        for octet in octets:
            if not octet or octet == "___" or octet == "   ": # check for mask symbols
                emptyOctet = True
                continue
            try:
                value = int(str(octet).strip(' _')) # strip mask symbols
            except:
                return Qt.QValidator.Intermediate, pos
            if value < 0 or value > 255:
                return Qt.QValidator.Invalid, pos
        if size < 4 or emptyOctet:
            return Qt.QValidator.Intermediate, pos
        return Qt.QValidator.Acceptable, pos

并像这样使用它

    validator = IP4Validator()
    self.ipAddrLineEdit.setValidator(validator)

带有像“000.000.000.000;_”或“000.000.000.000;”这样的掩码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2017-07-25
    • 2010-12-21
    相关资源
    最近更新 更多