为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 QRegExpValidator 总是返回 2

为什么 QRegExpValidator 总是返回 2

智慧大石 2023-06-06 16:15:07
我QRegExpValidator一直认为我的输入是Acceptable- 它不应该是。在 gui.py 中有一个QLineEdit名为`from gui import Ui_Dialogfrom PyQt5.QtWidgets import QDialog, QApplicationfrom PyQt5 import QtCorefrom PyQt5.QtGui import QRegExpValidatorfrom PyQt5.QtCore import QRegExpimport sysclass 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(或可接受)。
查看完整描述

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)


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信