如何将日期从变量或文本设置到 QDateEdit?

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

示例代码如下:

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

我想将该日期设置为 QtWidgets.QDateEdit()。 但它将默认日期设置为 1-jan-2000

我认为这可能是因为您的日期是字符串格式。那么你可以使用 widget_date.setDisplayFormat("%d-%b-%Y")

您混淆了概念,setDisplayFormat() 确定了文本在小部件中的显示格式,并且没有任何内容干预字符串到 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_())