User Input Validation in PyQt5 and Python

后端 未结 2 1933
心在旅途
心在旅途 2021-01-18 20:09

This is a two part question about input validation with one specific and another more general component.

The specific:

While researching the

2条回答
  •  醉话见心
    2021-01-18 20:36

    You can set different validators for different QLineEdit objects.

    QRegExpValidator has two constructors:

    QRegExpValidator(parent: QObject = None)
    QRegExpValidator(QRegExp, parent: QObject = None)
    

    so, you should change your code to:

    reg_ex = QRegExp("[0-9]+.?[0-9]{,2}")
    input_validator = QRegExpValidator(reg_ex, self.le_input)
    self.le_input.setValidator(input_validator)
    

    Once you set validator for QLineEdit, there is no need to use

    self.le_input.textChanged.connect(self.validate_input)
    

    Just delete it. And that should work fine.

    If you want to find documentation about PyQt5, you can simple use this in your console:

    pydoc3 PyQt5.QtGui.QRegExpValidator
    

    But pydoc can only show you little information, so you should use C++ version documation as well.

    Finally, an example about this:

    from PyQt5.Qt import QApplication
    from PyQt5.QtCore import QRegExp
    from PyQt5.QtGui import QRegExpValidator
    from PyQt5.QtWidgets import QWidget, QLineEdit
    
    import sys
    
    class MyWidget(QWidget):
        def __init__(self, parent=None):
            super(QWidget, self).__init__(parent)
            self.le_input = QLineEdit(self)
    
            reg_ex = QRegExp("[0-9]+.?[0-9]{,2}")
            input_validator = QRegExpValidator(reg_ex, self.le_input)
            self.le_input.setValidator(input_validator)
    
    if __name__ == '__main__':
        a = QApplication(sys.argv)
    
        w = MyWidget()
        w.show()
    
        a.exec()
    

提交回复
热议问题