问题描述
我的_foo
始终认为我的输入是QRegExpValidator
-不应输入。在gui.py中,有一个名为{
Acceptable
对象
QLineEdit
无论我尝试什么,输出始终为from gui import Ui_Dialog
from PyQt5.QtWidgets import QDialog,QApplication
from PyQt5 import QtCore
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtCore import QRegExp
import sys
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)
print(tmp.Acceptable)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
。我希望输入任何内容,如果它是3位数字,则该函数返回True(或Acceptable)。
我试图按照here的解释走这条路,我想念什么?
解决方法
OP似乎不了解QValidator与QLineEdit一起工作的方式。
逻辑是使用已建立连接的setValidator方法将QValidator设置为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_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_position = tmp.validate( self.ui.number.text(),self.ui.number.cursorPosition() ) print(state)