2

I have two layers that I want to remove using PyQGis as part of a larger script. The first layer I can removed using:

QgsMapLayerRegistry.instance().removeMapLayer( shp.id() )

However, it seems that the second layer (the Joined layer) cannot be removed in the same way as I get the following error:

QgsMapLayerRegistry.instance().removeMapLayer( result.id() )

Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: JoinAttributes instance has no attribute 'id'

Does anyone happen to know a way to remove the Joined layer with PyQGIS?

  • what kind of object is your "result" and where does it come from ? hard to answer without seeing a bit more of your code. – snaileater Jan 24 '18 at 18:01
  • My result is the Joined layer. It is a shapefile that comes from joining a .csv with a previously made "base" shapefile. – Daniel Mutton Jan 24 '18 at 18:01
  • could you show the line generating this "result" ? – snaileater Jan 24 '18 at 18:04
  • Of course, result = processing.runandload('qgis:joinattributestable', shp, csv, shpField, csvField, None). The shp and csv are the variables where the shapefile and csv are stores. They are csv = QgsVectorLayer(csv_location, '2003day303', 'delimitedtext') and shp = QgsVectorLayer(shp_location, 'Alberta Zones test', 'ogr') respectively. – Daniel Mutton Jan 24 '18 at 18:06
  • the shpField and csvField represent the unique ID in the shapefile and csv allowing for the join to happen – Daniel Mutton Jan 24 '18 at 18:09
2

U used the toolbox algorithm "qgis:joinattributestable".

This algorithm creates a new table named Joined layer (i don't know whether the algorithm let u choose its name ...)

Result is not a reference to any QgsVectorLayer but is a JoinAttributes instance which enables you to retrieve some information about the algorithm you just launched.

So result.id generates an error since id is not an attribute of this class.

RemoveAllMapLayers looks really like an odd solution to me ... better use something like :

jl = QgsMapLayerRegistry.instance().mapLayersByName("Joined layer")[0]
QgsMapLayerRegistry.instance().removeMapLayer(jl.id())
|improve this answer|||||
2

After working on the problem for a little while longer I was able to find an answer, although not an ideal one.

What I ended up doing was using

QgsMapLayerRegistry.instance().removeAllMapLayers()

to remove all the map layers, and then afterwards re-adding the ones I need.

While this does get the job done, it probably isn't the most elegant or efficient solution. If anyone knows a better way please post it.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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