Search code examples
pythonpyqtpyqt5qlineeditqvalidator

PyQT5: How to use both QLineEdit: Validator and InputMask?


I want to use both InputMask and Validator to get date in the correct form. In the code below I am using InputMask to receive date in format DD.MM.YYYY. I do not know how to limit each part of it (DD, MM and YYYY) because now user can type 40.30.2020 and it is theoretically correct.

self.date = QLineEdit(self)
self.date.setInputMask("00.00.0000")

Solution

  • QDateTimeEdit Class

    The QDateTimeEdit class provides a widget for editing dates and times.

    import sys
    from PyQt5.QtCore import QDate 
    from PyQt5.QtWidgets import (QApplication, QWidget, QDateTimeEdit, 
                                 QFormLayout, QLabel)
    from PyQt5.QtGui import QFont
    
    class Demo(QWidget):
        def __init__(self):
            super(Demo, self).__init__()    
    
            self.datetime = QDateTimeEdit(QDate.currentDate())
    
            self.v_layout = QFormLayout(self)
            self.v_layout.addRow(QLabel('DD.MM.YYYY'), self.datetime)
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        app.setFont(QFont("Times", 12, QFont.Bold))
        demo = Demo()
        demo.show()
        sys.exit(app.exec_())
    

    enter image description here