Python 为什么QRegExpValidator总是返回2
我的Python 为什么QRegExpValidator总是返回2,python,pyqt,pyqt5,qlineedit,qvalidator,Python,Pyqt,Pyqt5,Qlineedit,Qvalidator,我的QRegExpValidator总是认为我的输入是可接受的——这是不应该的。在gui.py中有一个名为` 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 A
QRegExpValidator
总是认为我的输入是可接受的
——这是不应该的。在gui.py中有一个名为`
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_())
无论我尝试什么,输出总是2
。我希望输入任何内容,如果是3位数字,函数将返回True(或可接受)。
我试着按照这条路径解释,我遗漏了什么?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()
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)
- 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() 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)
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)