[GIS] Seeking purge function to remove layers from qgs file which are not present in Layers pane of QGIS

qgisqgis-plugins

I have some QGIS projects that I've been using for long time, adding and removing layers, updating reference to deleted or moved files etc.

Opening the qgs file with a text editor I see that it contains numerous references to different files, and this references are not showed on the Layer tree pane.

I have three different cases: references to existing file, references to missing files, references to database connections. I got aware of this when I opened my project on another machine, and QGIS reported a missing database connection to vector tables not present in the layer tree view.

Manually deleting references from the qgs file solved the problem, but I'm managing huge projects and it's near to impossible to manually check the project consistency. I've tried the "Remove empty layers" plugin, but the ones I'm trying to remove are not empty layers.

Is there any way to 'purge' qgis file?

Best Answer

Note: This code is no longer compatible with QGIS 3, see the answer below with a link to the Layer Board plugin instead https://gis.stackexchange.com/a/218719/9839

The layers in question are in the layer registry but not in the legend.

The following python script removes all layers which are loaded, but not shown in the legend.

Removing the layers:

registryLayers = QgsMapLayerRegistry.instance().mapLayers().keys()
legendLayers = [ layer.id() for layer in iface.legendInterface().layers() ]
layersToRemove = set( registryLayers ) - set( legendLayers )
QgsMapLayerRegistry.instance().removeMapLayers( list( layersToRemove ) )

It should be run from the python console inside QGIS. After applying it you can verify the operation by checking that the layers are gone from File (Project in 2.0) => Project Properties => Identifiable layers. Changes are not saved automatically

By adding the following line at the end, changes will also be saved automatically.

iface.actionSaveProject().trigger()

Please make a Backup copy of your Project file (.qgs) before overwriting your project file after applying this script.

For QGIS 1.8 the following line is required to be run initially:

iface = qgis.utils.iface
Related Question