我正在尝试使用QValidator
后代(实际上是在PyQt5中,但这没关系)来验证一系列行编辑。
一个小摘录是:
class IPv4(QWidget):
def __init__(self):
super(IPv4, self).__init__()
uic.loadUi('ipv4.ui', self)
self.address.inputMask = ''
rx = QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
self.address.setValidator(QRegularExpressionValidator(rx, self.address))
self.netmask.setValidator(QRegularExpressionValidator(rx, self.netmask))
self.gateway.setValidator(QRegularExpressionValidator(rx, self.gateway))
self.broadcast.setValidator(QRegularExpressionValidator(rx, self.broadcast))
self.dns1.setValidator(QRegularExpressionValidator(rx, self.dns1))
self.dns2.setValidator(QRegularExpressionValidator(rx, self.dns2))
self.on_dhcp_clicked(self.dhcp.isChecked())
这与广告一样工作,但是用户没有得到任何反馈,因为尝试输入“错误”字符只会丢弃它们。
除了挂接到QLineEdit.textChanged
信号并“手动”进行验证(即:没有设置验证器,否则没有其他任何方法可提供反馈),否则发生错误{{1 }}不会改变,也不会发出信号。首选的反馈是更改行编辑的边框颜色。
这在某种程度上破坏了验证器本身的目的。看来我缺少了一些东西,因为我看不到如何触发来自text
的反馈。
处理此问题的“标准方法”是什么?
答案 0 :(得分:2)
通过在子类中重新实现validate方法,可以使用自定义信号来指示验证状态更改。下面是演示此方法的脚本。 (请注意,validate
的签名在PyQt中是不同的,因为它不会像C ++中那样对参数进行突变。)
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class RegExpValidator(QtGui.QRegularExpressionValidator):
validationChanged = QtCore.pyqtSignal(QtGui.QValidator.State)
def validate(self, input, pos):
state, input, pos = super().validate(input, pos)
self.validationChanged.emit(state)
return state, input, pos
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
regexp = QtCore.QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
validator = RegExpValidator(regexp, self)
validator.validationChanged.connect(self.handleValidationChange)
self.edit = QtWidgets.QLineEdit()
self.edit.setValidator(validator)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.edit)
def handleValidationChange(self, state):
if state == QtGui.QValidator.Invalid:
colour = 'red'
elif state == QtGui.QValidator.Intermediate:
colour = 'gold'
elif state == QtGui.QValidator.Acceptable:
colour = 'lime'
self.edit.setStyleSheet('border: 3px solid %s' % colour)
QtCore.QTimer.singleShot(1000, lambda: self.edit.setStyleSheet(''))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
答案 1 :(得分:1)
如果要验证QLineEdit文本是否有效,则必须使用hasAcceptableInput()
方法:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
rx = QtCore.QRegularExpression(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
self.le = QtWidgets.QLineEdit()
self.le.setValidator(QtGui.QRegularExpressionValidator(rx, self.le))
self.le.textChanged.connect(self.on_textChanged)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.le)
@QtCore.pyqtSlot()
def on_textChanged(self):
le = self.sender()
if isinstance(le, QtWidgets.QLineEdit):
le.setStyleSheet(
"border: 5px solid {color}".format(
color="green" if le.hasAcceptableInput() else "red"
)
)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
答案 2 :(得分:0)
我接受@ekhumoro的回答本质上是正确的,但是从长远来看,我还将发布当前的测试代码,该代码易于维护(IMHO!)。
from __future__ import annotations
import typing
from PyQt5 import QtCore, QtGui, QtWidgets
class MyValidator(QtGui.QRegularExpressionValidator):
def validate(self, text: str, pos: int) -> typing.Tuple[QtGui.QValidator.State, str, int]:
state, text, pos = super(MyValidator, self).validate(text, pos)
selector = {
QtGui.QValidator.Invalid: 'invalid',
QtGui.QValidator.Intermediate: 'intermediate',
QtGui.QValidator.Acceptable: 'acceptable'
}[state]
if selector == 'invalid':
sel = self.parent().property('selector')
def restore():
self.parent().setProperty('selector', sel)
self.parent().setStyleSheet('/**/')
QtCore.QTimer.singleShot(1000, restore)
self.parent().setProperty('selector', selector)
self.parent().setStyleSheet('/**/')
return state, text, pos
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.le = QtWidgets.QLineEdit()
regexp = QtCore.QRegularExpression(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
self.le.setValidator(MyValidator(regexp, self.le))
self.le.setProperty('selector', 'none')
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.le)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyleSheet('''\
*[selector="invalid"] {border-radius: 3px; border: 1px solid red;}
*[selector="intermediate"] {border-radius: 3px; border: 1px solid gold;}
*[selector="acceptable"] {border-radius: 3px; border: 1px solid green;}
''')
w = Widget()
w.show()
sys.exit(app.exec_())
此代码有两个(nitpick)问题;但这是另一个问题;)