I'm using a plugin that creates scratch layers with the same name each time I start it.

It's not an issue on a session basis, proj.mapLayersByName('scratch_layer_name')[-1] works fine to get the latest one...

The issue comes when I save the project, if scratch layers are saved, the next time, when a new scratch layer (still with the same name) is added, the last index [-1] seems to point to previous (empty) layers?

Maybe I could delete the empty layers and refresh the project:

while proj.mapLayersByName('scratch_layer_name')[-1].featureCount() == 0:
    delete = proj().mapLayersByName('scratch_layer_name')[-1]

But with this code the empty layers are still there and I don't get any error message, so I suppose the loop condition is not correct?

What could be done to prevent this, considering that the scratch layers are easily saved 'by mistake' with the project?

(Win 10 Pro, QGIS 3.22)

  • How do you save the scratch layers? Apr 16, 2022 at 21:51
  • I just save the project. If I don't manually remove the layers before, they are saved (without the features), automatically. Edited OP to add the system, version, Win 10 Pro, QGIS 3.22.
    – S.E.
    Apr 17, 2022 at 7:57

1 Answer 1


Before your plugin creates the scratch layers you can remove existing layers with no features from the project. This code is from from the Remove Empty Layers plugin:

toBeRemoved = []
for key, layer in QgsProject.instance().mapLayers().items():
   if layer.type() == QgsMapLayer.VectorLayer:
       if layer.featureCount() == 0:
           toBeRemoved.append( layer.id() )

if toBeRemoved:
    QgsProject.instance().removeMapLayers( toBeRemoved )

You can do a further check with the name to avoid accidentally removing layers not created by your plugin.

  • 1
    Works perfectly, thanks !
    – S.E.
    Apr 17, 2022 at 20:40

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.