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

6.7k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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

I think it might be possible due to your date is in string format. So can u use widget_date.setDisplayFormat("%d-%b-%Y")