2

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user3030327
  • 411
  • 1
  • 7
  • 19

2 Answers2

4

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

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

Arpit
  • 394
  • 1
  • 11