Adding a custom widget to a QGIS Processing script

You can write python script in Processing to write your own algorithm.

If you already know how to write Processing scripts, then you also know that you can add many parameter types

But if you want to add another parameter type? How to add for example a DateTime like parameter with a pop-up calendar button?

In the following example I just took the template script and added the parameter: it is up to you to take that DateTime value and make whatever you want!

Let's proceed by steps:

  1. Create a new script with the dedicated button:

    Processing script template

  2. Some imports before to start creating the widget:

    from processing.gui.wrappers import WidgetWrapper
    from qgis.PyQt.QtWidgets import QDateTimeEdit
    from qgis.PyQt.QtCore import QCoreApplication, QDate
    from qgis.core import (QgsProcessing,
  3. We have to create a class that must inherit from the WidgetWrapper class. Within this class we will specify all the widget settings, like the pop-up button, the default date, etc:

    class DateTimeWidget(WidgetWrapper):
        QDateTimeEdit widget with calendar pop up
        def createWidget(self):
            self._combo = QDateTimeEdit()
            today = QDate.currentDate()
            return self._combo
        def value(self):
            date_chosen = self._combo.dateTime()
            return date_chosen.toString(Qt.ISODate)

    the class has two methods: the first one, createWidget, creates the widget, the second one, velue, returns the value of the widget, in this case the datetime value

  4. Within the method initAlgorithm of the main algorithm class, we must tell Processing how to build the UI with the widget:

      class myAlgorithm(QgsProcessingAlgorithm):
          DATEINI = 'DATEINI'
        def initAlgorithm(self, config=None):
            param = QgsProcessingParameterString(self.DATEINI, 'Initial Date')
                'widget_wrapper': {
                    'class': DateTimeWidget}})
  5. Last step, within the processAlgorithm method we should retrieve the widget value and create a variable with the results to make whatever we want to do:

      mydate = self.parameterAsString(

And here we go:

Processing script UI

Happy Processing coding!

Previous Post Next Post