下面是示例代码:
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
下面是示例代码:
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
您混淆了概念,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_())
我认为这可能是因为您的日期是字符串格式。那你能用吗widget_date.setDisplayFormat("%d-%b-%Y")