pythonpyqtpyqt5qlineeditqvalidator

Why does QRegExpValidator always return 2


My QRegExpValidator always thinks my input is Acceptable - which it should not be. In the gui.py there is a QLineEdit object named `

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_())

Output is always 2 no matter what I try. I want that I input whatever, and if it is a 3 digit number the function returns True (or Acceptable). I tried to follow this path explained here, what am I missing?


Solution

  • It seems that the OP doesn't understand how a QValidator works alongside a QLineEdit.

    The logic is that the QValidator is set to QLineEdit using the method setValidator where the connection is already made so that every time the text of the QLineEdit is changed, the "validate" method is invoked, which returns the state, the new position and the new text (if necessary to correct it).

    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)

    On the other hand, since "tmp" is a QValidator then tmp.Acceptable is equivalent to QValidator.Acceptable and when printing it, the numerical value of that enum is obtained.

    If you want to analyze the value of the validator state then you have the following options: