7

I want to rewrite a projekt with new layers while owerwriting all old layers. I found the function removeAllMapLayers in the qgis.core api

But when i try:

project = QgsProject.instance()
project.removeAllMapLayers()

Where I am in a project with some layers. After trying the code I get this error:

Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'QgsProject' object has no attribute 'removeAllMapLayers'

Is there any other way to empty all layer in a project? I want to write to the same project when it's empty.

1
  • It works and clears all. Unfortunatley i also want to be able to clear projects I am not in but that isn't how my question is frased. Commented Jun 1, 2017 at 11:48

1 Answer 1

7

You could use the QgsMapLayerRegistry::removeAllMapLayers() method to remove all layers in your project:

QgsMapLayerRegistry.instance().removeAllMapLayers()
3
  • Is there any way to do it through the QgsProject Class? Commented Jun 1, 2017 at 11:49
  • 2
    @VilyaSeeFour - Atleast in QGIS 2.18, removeAllMapLayers() no longer seems to be available in the QgsProject Class. You could use QgsProject.instance().clear() which resets your project to a completely blank state. Or iterate all layers in your project using a for loop and then remove them using QgsProject.instance().removeMapLayers() :)
    – Joseph
    Commented Jun 1, 2017 at 11:55
  • 1
    use QgsProject.instance().clear() ,qgis.org/api/2.18/… in QGIS3 you have QgsProject.instance().removeAllMapLayers () ,qgis.org/api/…
    – Fran Raga
    Commented Jun 1, 2017 at 12:02

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.