3

In QGIS 3.4, I am building a model for importing and preparing multiple data by merging shapes and joining tables.

I am almost finished with the model, but I haven't found a useful tool for deleting certain columns of an attribute table in the graphical modeler.

So I am right now stuck in writing myself a tool for this purpose and unfortunately, I am not that experienced in writing code.

I need to delete the following indexes - always the same ones:

[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,22,23,24,25,27,28,29,41,42,44,45]

My code snippet:

layer = qgis.utils.iface.activeLayer()

layer_provider.deleteAttributes([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,22,23,24,25,27,28,29,41,42,44,45])
layer.updateFields()

I tried to make a dropdown menu using an existing code from @J.Monticolo. It did not work, as expected.

from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterFeatureSink
import processing


class MyModel2(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterVectorLayer('inputlayer1', 'input_layer_1', types=[QgsProcessing.TypeVector], defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Output_layer', 'output_layer', optional=True, type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
        results = {}
        outputs = {}

        layer=QgsVectorLayer('input_layer_1')
        with edit(layer)
            layer.deleteAttributes([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,22,23,24,25,27,28,29,41,42,44,45])
        
        return results

    def name(self):
        return 'delete_table'

    def displayName(self):
        return 'delete_table'

    def group(self):
        return ''

    def groupId(self):
        return ''

    def createInstance(self):
        return MyModel2()
1

1 Answer 1

1

Try this snippet:

from qgis.core import QgsVectorLayer

layer = QgsVectorLayer(r'C:\Test\Cities.shp')

with edit(layer):
    layer.deleteAttributes([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,22,23,24,25,27,28,29,41,42,44,45])
0

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.