Antoni4040 Antoni4040 - 1 month ago 10
Python Question

PyQt: QDateComboBox setDate using string?

How can I set the date of a QDateComboBox using a string that some times can also be empty?

Answer

Assuming you're talking about QDateEdit, you will need to create a QDate object from the string so that it can be passed to the setDate function.

The QDate class has a static fromString function that can create a QDate from a string, but you will have to know the format of the date in the string for it to work properly.

By default, QDate.fromString assumes dates will be in the following format:

ddd MMM d yyyy (ShortDayName ShortMonthName ShortDayNumber LongYearNumber)
e.g. Thu Dec 6 2012

However, you can specify a format as the second argument to fromString by passing either a standard DateFormat, or a custom format string.

If QDate can't parse the date-string, an invalid QDate object will be returned (you can check this with date.isValid()).

An empty string will produce an invalid date object, but if you pass one to QDateEdit.setDate, it will be ignored (i.e. the date won't change).