为什么 QRegExpValidator 总是返回 2

我QRegExpValidator一直认为我的输入是Acceptable- 它不应该是。在 gui.py 中有一个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_())

2无论我尝试什么,输出总是如此。我希望我输入任何内容,如果它是 3 位数字,则该函数返回 True(或可接受)。


智慧大石
浏览 76回答 1
1回答

波斯汪

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_positionclass 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python