Created
June 8, 2022 02:48
-
-
Save moosetraveller/064ab49ec3ec84658a1d15a47eb04136 to your computer and use it in GitHub Desktop.
Create DateTime widget for QGIS Processing Tool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from qgis.PyQt.QtCore import ( | |
QCoreApplication, | |
QDateTime, | |
) | |
from processing.gui.wrappers import WidgetWrapper | |
from qgis.gui import QgsDateTimeEdit | |
from qgis.core import ( | |
Qgis, | |
QgsMessageLog, | |
QgsProcessingParameterString, | |
QgsProcessingAlgorithm, | |
) | |
from PyQt5.QtCore import Qt | |
DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss" | |
class DateTimeWidget(WidgetWrapper): | |
""" QDateTimeEdit widget with calendar pop up """ | |
def createWidget(self): | |
self._combo = QgsDateTimeEdit() | |
self._combo.setCalendarPopup(True) | |
self._combo.setDisplayFormat(DATE_TIME_FORMAT) | |
today = QDateTime.currentDateTime() | |
self._combo.setDateTime(today) | |
return self._combo | |
def setValue(self, value): | |
self._combo.setDateTime(value) | |
def value(self): | |
date_chosen = self._combo.dateTime() | |
return date_chosen.toString(Qt.ISODate) | |
class DateTimeWidgetTest(QgsProcessingAlgorithm): | |
DATE_SELECTION = "DATE_SELECTION" | |
def __init__(self): | |
super().__init__() | |
def tr(self, string): | |
return QCoreApplication.translate("Processing", string) | |
def name(self): | |
return "PrintDateTime" | |
def displayName(self): | |
return "Prints a datetime string" | |
def group(self): | |
return "Example Scripts" | |
def groupId(self): | |
return "playground" | |
def createInstance(self): | |
return type(self)() | |
def initAlgorithm(self, config=None): | |
param = QgsProcessingParameterString( | |
self.DATE_SELECTION, | |
self.tr("Date Selection"), | |
defaultValue=QDateTime.currentDateTime().addDays(-31), | |
optional=False | |
) | |
param.setMetadata({'widget_wrapper': {"class": DateTimeWidget}}) | |
self.addParameter(param) | |
def processAlgorithm(self, parameters, context, feedback): | |
datetime = self.parameterAsDateTime(parameters, self.DATE_SELECTION, context); | |
QgsMessageLog.logMessage(str(datetime), level=Qgis.Info) | |
return {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment