PyQt5 QLine setInputMask+setValidator IP地址

2024-04-26 10:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

将setInputMask和setValidator IPv4地址合并到QlineEdit时出现问题

我有一个QLineEdit来设置我的IPv4地址。 第一次,我用setInputMask将QLineEdit设置为“…” 第二次,我使用Ip验证器来检查它是否是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)

Tags: selfip编辑地址validatoripv4regexpqtcore
1条回答
网友
1楼 · 发布于 2024-04-26 10:20:27

为QLine设置掩码会将其内容从空符号更改为指定符号。你的“看起来像是空的。这就是regex失败的原因。 您可以使用自己的重写验证器:

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

像这样使用它

^{pr2}$

使用诸如“000.000.000.000;”或“000.000.000.000;”<;这样的掩码结尾有空格

相关问题 更多 >