Search code examples
pythonpython-3.xpyqt5qdateedit

How to set date in to QDateEdit from Variable or Text?


Below is the example code:

date = "1-Jan-2020"
widget_date = QtWidgets.QDateEdit()
widget_date .setDisplayFormat("d-MMM-yyyy")
widget_date .setDate(QDate.fromString(date))

I want to set that date to QtWidgets.QDateEdit(). But it is setting up the default date as 1-jan-2000


Solution

  • You are confusing concepts, setDisplayFormat() establishes the format of how the text will be displayed in the widget and nothing intervenes with the conversion of the string to QDate:

    from PyQt5 import QtCore, QtWidgets
    
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
    
        date_str = "1-Jan-2020"
        # convert str to QDate
        qdate = QtCore.QDate.fromString(date_str, "d-MMM-yyyy")
    
        widget_date = QtWidgets.QDateEdit()
        # Set the format of how the QDate will be displayed in the widget
        widget_date.setDisplayFormat("d-MMM-yyyy")
    
        widget_date.setDate(qdate)
        
        widget_date.show()
        
        sys.exit(app.exec_())