3

I am currently working on a processing script for QGIS. In the function def initAlgorithm() I am defining several parameters. One of the parameters is using QgsProcessingParameterEnum with a pre-defined list:

# Function to initialize the algorithm/tool
def initAlgorithm(self, config=None):
    self.addParameter(
        QgsProcessingParameterEnum(
            "CHOICE_LAYER", 'Title', options=['A', 'B'], defaultValue='A'
             )
        )

This works so far and I can select the values in the GUI. The problem is in the further processing of the selection. In the function processAlgorithm() I try to get the value from the GUI by using the following lines.

def processAlgorithm(self, parameters, context, feedback):
    # Get value from the GUI        
    choice = self.parameterAsString(parameters, "CHOICE_LAYER", context)
    print(f"{choice }")

This is also works, but returns the index position of the value from the choice list. So selecting "A" returns 0 and selecting "B" returns 1.

Is there a way to get the "real" value and not only the index?

I also tried self.parameterAsEnumString() but this only returns every time the value "A"...

1 Answer 1

7

Set usesStaticStrings=True when you create the parameter:

class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    # etc...

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterEnum(
                "CHOICE_LAYER", 'Title', options=['A', 'B'], defaultValue='A', 
                usesStaticStrings=True  #<----------- here
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        # Get value from the GUI        
        choice = self.parameterAsString(parameters, "CHOICE_LAYER", context)
        print(f"{choice}")
        # etc.....

enter image description here

Alternatively, you could create a list of the choices and assign it to an instance attribute then use the index to get the string value, e.g.

class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    # etc...

    def initAlgorithm(self, config=None):
        self._CHOICE_LAYER = ["A", "B"]  # <==== instance attribute
        self.addParameter(
            QgsProcessingParameterEnum(
                "CHOICE_LAYER", 'Title', options=self._CHOICE_LAYER, defaultValue=self._CHOICE_LAYER[0]
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        # Get value from the GUI        
        choice = self.parameterAsInt(parameters, "CHOICE_LAYER", context)  # <===== param as int

        print(f"{choice} {self._CHOICE_LAYER[choice]}")
        # etc.....

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.