1 回答
TA贡献1811条经验 获得超4个赞
OP 似乎不了解 QValidator 如何与 QLineEdit 一起工作。
逻辑是 QValidator 使用方法 setValidator 设置为 QLineEdit,其中已经建立连接,以便每次更改 QLineEdit 的文本时,调用“validate”方法,返回状态、新位置和新文本(如果需要更正)。
class AppWindow(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
regex = QRegExp("^[0-9]{3}$")
validator = QRegExpValidator(regex, self.ui.number)
self.ui.number.setValidator(validator)
另一方面,由于“tmp”是一个 QValidator,那么 tmp.Acceptable 等同于 QValidator.Acceptable,当打印它时,会获得该枚举的数值。
如果你想分析验证器状态的值,那么你有以下选项:
覆盖验证(最推荐):
class RegExpValidator(QRegExpValidator):
def validate(self, text, position):
state, new_text, new_position = super().validate(text, position)
print(state)
return state, new_text, new_position
class AppWindow(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
regex = QRegExp("^[0-9]{3}$")
validator = RegExpValidator(regex, self.ui.number)
self.ui.number.setValidator(validator)
调用验证方法:
class AppWindow(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
self.ui.number.textChanged[str].connect(self.validate_number)
def validate_number(self):
regex = QRegExp("^[0-9]{3}$")
tmp = QRegExpValidator(regex, self.ui.number)
state, new_text, new_position = tmp.validate(
self.ui.number.text(), self.ui.number.cursorPosition()
)
print(state)
添加回答
举报