5

I'm trying to automate a procedure which involves a Dissolve. I've got the layer stored as a variable (layer_shp) and am trying to dissolve it through Python, as such:

dissolve_process = processing.run("gdal:dissolve", layer_shp, "", "memory") layer_dissolve_shp = dissolve_process["OUTPUT"] layer_dissolve_shp.commitChanges() QgsProject.instance().addMapLayer(layer_dissolve_shp) 

This is giving us the following errors:

After the dissolve_process = processing.run("gdal:dissolve", layer_shp, "", "memory"):

Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "C:/PROGRA~1/QGIS3~1.4/apps/qgis-ltr/./python/plugins\processing\tools\general.py", line 105, in run return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context) File "C:/PROGRA~1/QGIS3~1.4/apps/qgis-ltr/./python/plugins\processing\core\Processing.py", line 130, in runAlgorithm context = dataobjects.createContext(feedback) File "C:/PROGRA~1/QGIS3~1.4/apps/qgis-ltr/./python/plugins\processing\tools\dataobjects.py", line 72, in createContext context.setFeedback(feedback) TypeError: QgsProcessingContext.setFeedback(): argument 1 has unexpected type 'str' 

Then, of course, when I try and commit changes:

AttributeError: 'str' object has no attribute 'commitChanges' 

Think this should be quite an easy one but I'm not finding much about doing a dissolve. This isn't dissolving on a field, and I'm wanting it dissolved to memory and then adding into the project. This is QGIS 3.4.5

EDIT - this is the code I ended up using:

layer_dissolve_shp = processing.run("native:dissolve", {'INPUT':'Spray_SHP','FIELD':[],'OUTPUT':'memory:'})["OUTPUT"] QgsProject.instance().addMapLayer(layer_dissolve_shp) 

The layer exists as a memory layer on the QGIS layers list as "Spray_SHP" (note - this is not a shapefile - we're doing everything in memory and not saving to disk). This will just get that layer and dissolve it to layer_dissolve_shp, then add it as 'output'.

1
  • 1
    How have you defined layer_shp - from the error it looks as if its a string not a layer object? Commented Mar 17, 2020 at 6:57

1 Answer 1

5

From om your first error message, it seems like layer_shp is a string, not a layer. You need to get hold of the layer - in different ways depending if it is a file name or a layer name.

Your next problem is that dissolve_process["OUTPUT"] is not a layer, but the layer's id. You need to get hold of the layer from the project:

layer=QgsProject.instance().mapLayer(output['OUTPUT']) 

I did this in a plugin: https://github.com/sickel/altitudecorrector/blob/d5565/altitudecorrector.py#L314

(And pulled out a lot of hair before I understood what was going on...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.