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)
添加回答
舉報