Working on a QGIS plugin, I am struggling to save/load date and time values. Users can enter dates via QDateEdit
widget and times via QTimeEdit
widget. Values are then stored the following:
s = QgsSettings()
# Date
self.Isochrones_Date_setting = self.dlg.Isochrones_Date.date()
s.setValue("otp_plugin/Isochrones_Date", self.Isochrones_Date_setting)
# Time
self.Isochrones_Time_setting = self.dlg.Isochrones_Time.time()
s.setValue("otp_plugin/Isochrones_Time", self.Isochrones_Time_setting)
and shall be read by:
s = QgsSettings()
# Date
self.Isochrones_Date_setting = s.value("otp_plugin/Isochrones_Date", QtCore.QDateTime.currentDateTime())
self.dlg.Isochrones_Date.setDateTime(self.Isochrones_Date_setting)
# Time
self.Isochrones_Time_setting = s.value("otp_plugin/Isochrones_Time", '14:00:00')
self.dlg.Isochrones_Time.setDateTime(self.Isochrones_Time_setting)
However, loading saved values or getting default values fails. With this code I am getting the error
TypeError: setDateTime(self, Union[QDateTime, datetime.datetime]):
argument 1 has unexpected type 'QDate'
What is the correct syntax, if not .setDateTime()
? Or do I need to convert QDate to some other date before? If so, how?
Best Answer
Basically you have to use
.setDate()
forQDateEdit
and.setTime()
forQTimeEdit
, not.setDateTime()
and convert strings toQTime
viaQTime.fromString()
or toQDate
viaQDate.fromString()
.But: in this case it is a little more complicated, because
QtCore.QDateTime.currentDateTime())
is inQDateTime-Format
. So in this case,QDateEdit
, has to be set using.setDateTime()
but the stored setting fromQDateEdit
is inQDate-Format
, so.setDate()
has to be used. The simplest way to combine both possibilities, is to just use atry/except
statement: it will always pick the stored one, if available, and only the standard one if no stored is available.So the code would look like: