5

I want to dissolve my layer by using this script and it is successful, however I want my dissolved layer to be temporary, and my input as any active layer. Can someone help me?

from qgis import processing

inlayer = r'C:\Users\CMCA\OneDrive - Boskalis\Documents\Trial PyQGIS\Tobe_Dissolved01.shp'
outlayer = r'C:\Users\CMCA\OneDrive - Boskalis\Documents\Trial PyQGIS\dissolve.shp'

processing.run("native:dissolve", {'INPUT':inlayer, 'FIELD':[], 'OUTPUT':outlayer})
iface.addVectorLayer(outlayer, '', 'ogr')
3

2 Answers 2

9

In more recent versions of QGIS, do not forget to include the 'SEPARATE_DISJOINT' argument, see the Changelog for QGIS 3.26 for more details.

So, your code may look like this:

from qgis import processing
from qgis.core import QgsProject

layer = QgsProject.instance().mapLayersByName('Tobe_Dissolved01')[0]

params = {
    'FIELD' : [],
    'INPUT' : layer,
    'OUTPUT' : 'memory:dissolve',
    'SEPARATE_DISJOINT' : False
}

dissolved = processing.run("native:dissolve", params)['OUTPUT']

QgsProject.instance().addMapLayer(dissolved)
7

Use 'TEMPORARY_OUTPUT' value for 'OUTPUT' parameter. Use the following lines:

processing.runAndLoadResults("native:dissolve",
                             {'INPUT':inlayer, 
                              'FIELD':[],
                              'OUTPUT': 'TEMPORARY_OUTPUT'})

If you use runAndLoadResults, you won't need to use iface.addVectorLayer.

9
  • Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 6, in <module> TypeError: QgisInterface.addVectorLayer(): argument 1 has unexpected type 'QgsVectorLayer' I got an error like this ?
    – PyCher
    Jan 9, 2023 at 9:48
  • Ok. I've edited the answer. Please check. Jan 9, 2023 at 9:55
  • oh .. Thank you sooo much it works! , but if it is not soo much trouble I'd like to understand what is the difference between runAndLoadResults and iface.addVectorLayer.?
    – PyCher
    Jan 9, 2023 at 11:06
  • how about my input layer ? how can I make it select any layer?
    – PyCher
    Jan 9, 2023 at 11:10
  • Can i make the dissolve output layer into a variable again?
    – PyCher
    Jan 11, 2023 at 7:21

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.