2

So this is my code :

    from qgis import processing
    
    inlayDir = iface.activeLayer()
    
    Sp_Offset = 'E:/QGIS/General/20230117_Boundaries R8/PVD Hectares/PH_RPSOffset8-0_AEB.gpkg'
    Sp ='E:/QGIS/General/20230117_Boundaries R8/PVD Hectares/PH_RPS8-0_AEB.gpkg' 
    
    dissolved=processing.runAndLoadResults("native:dissolve",
                                 {'INPUT': inlayDir, 
                                  'FIELD':[],
                                  'OUTPUT': 'TEMPORARY_OUTPUT'})
                                  
    
    
    UN_Sp_Offset = processing.runAndLoadResults( "qgis:union",{
                            'INPUT' : Sp_Offset, 
                            'OUTPUT' : 'TEMPORARY_OUTPUT', 
                            'OVERLAY' : dissolved['OUTPUT'], 
                            'OVERLAY_FIELDS_PREFIX' : '' })
    
                            
    Clip = processing.runAndLoadResults("native:clip",
                                { 'INPUT':UN_Sp_Offset['OUTPUT'],
                                'OVERLAY' : dissolved['OUTPUT'],
                                'OUTPUT' : 'TEMPORARY_OUTPUT',
                                })
    
                                    
    
    # create an instance of QgsDistanceArea
    distance_area = QgsDistanceArea()
    
    # create the fields list
    fields = QgsFields()
    fields.append(QgsField('area', QVariant.Double))
    
    inlayDir = iface.activeLayer()
    
    fields.append(QgsField('perimeter', QVariant.Double))
    
    # start editing the vector layer
    with edit(clip):
        # add the fields
        for field in fields:
            vl.addAttribute(field)
            
        # loop into the features
        for feature in vl.getFeatures():
            geometry = feature.geometry()
            
            # update the feature with teh QgsDistanceArea calculation
            feature['area'] = distance_area.measureArea(geometry)
            feature['perimeter'] = distance_area.measurePerimeter(geometry)
            
            Clip.updateFeature(feature)

# add the layer to the map
project.addMapLayer(Clip)

and I want to add "Area and Perimeter" in another column in my attribute table next to my columns:

enter image description here

Error Message:

# Python Console
# Use iface to access QGIS API interface or type help(iface) for more info
# Security warning: typing commands from an untrusted source can harm your computer
exec(Path('C:/Users/CMCA/AppData/Local/Temp/tmp8h99ttbs.py').read_text())
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 15, in <module>
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in __enter__
    assert self.layer.startEditing()
AssertionError
exec(Path('C:/Users/CMCA/AppData/Local/Temp/tmpd0rbj1lv.py').read_text())
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 42, in <module>
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in __enter__
    assert self.layer.startEditing()
AssertionError
exec(Path('C:/Users/CMCA/AppData/Local/Temp/tmplsle_e88.py').read_text())
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 42, in <module>
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in __enter__
    assert self.layer.startEditing()
AssertionError
exec(Path('C:/Users/CMCA/AppData/Local/Temp/tmp2ubmh9vo.py').read_text())
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 42, in <module>
  File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in __enter__
    assert self.layer.startEditing()
AssertionError

Can someone help me with the coding?

1
  • you have called the layer at the beginning Clip with capital C while in with edit(clip) you entered clip without the capital letter.
    – matteo
    Commented Jan 30, 2023 at 8:53

1 Answer 1

2

If you want to use Processing algorithms you can concatenate many algorithms.

In you case:

from qgis import processing

clip = processing.run("native:clip",
                        { 'INPUT':union['OUTPUT'],
                        'OVERLAY' : dissolved['OUTPUT'],
                        'OUTPUT' : 'TEMPORARY_OUTPUT',
                        })['OUTPUT']

processing.runAndLoadResults(
    "qgis:exportaddgeometrycolumns", 
    {
        'INPUT':clip,
        'CALC_METHOD':0,
        'OUTPUT':'TEMPORARY_OUTPUT'
    }
)

Or you can use standard pyqgis code like the following:

clip = processing.run("native:clip",
                            { 'INPUT':union['OUTPUT'],
                            'OVERLAY' : dissolved['OUTPUT'],
                            'OUTPUT' : 'TEMPORARY_OUTPUT',
                            })['OUTPUT']

# get the project instance
project = QgsProject.instance()

# create an instance of QgsDistanceArea
distance_area = QgsDistanceArea()

# create the fields list
fields = QgsFields()
fields.append(QgsField('area', QVariant.Double))
fields.append(QgsField('perimeter', QVariant.Double))

# start editing the vector layer
with edit(clip)
    # add the fields
    for field in fields:
        vl.addAttribute(field)
        
    # loop into the features
    for feature in vl.getFeatures():
        geometry = feature.geometry()
        
        # update the feature with teh QgsDistanceArea calculation
        feature['area'] = distance_area.measureArea(geometry)
        feature['perimeter'] = distance_area.measurePerimeter(geometry)
        
        clip.updateFeature(feature)

# add the layer to the map
project.addMapLayer(clip)
4
  • I used the first option and it gave me an error? : 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 28, in <module> File
    – PyCher
    Commented Jan 27, 2023 at 3:43
  • "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\tools\general.py", line 151, in runAndLoadResults return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\core\Processing.py", line 181, in runAlgorithm raise QgsProcessingException(msg) _core.QgsProcessingException: Unable to execute algorithm Could not load source layer for INPUT: invalid value
    – PyCher
    Commented Jan 27, 2023 at 3:43
  • I cannot help without an entire debug. Is the stacktrace referring to the runAndLoadResults? Try to adjust the parameters of both processing with your paths
    – matteo
    Commented Jan 27, 2023 at 7:03
  • I edited my content , please see above
    – PyCher
    Commented Jan 28, 2023 at 0:32

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.