1

My QGIS ToC contains layer groups and some layers that do not belong to any group.

I would like to create a text file containing the name of those layers that do not belong to any group.

Is there an automated way to do it?

2
  • Could you please expand a bit your question? What would you like the txt file to contain? Jan 25, 2015 at 12:30
  • my excuses,I work with many layers (100+) some of them I grouped together. Those that I could not group someone else need to have a look at. For this reason I would like the txt file to contain the names of those layers I did not group. Basically just a list. I could do this manually but hope there is another way to do so.
    – kwai
    Jan 25, 2015 at 13:06

1 Answer 1

5

You can do that from the QGIS Python console. Follow this workflow:

  1. Open the QGIS Python console

  2. Adjust the following line to match the path of your text file and copy the whole line to the QGIS Python console:

    textFilePath = '/tmp/non_grouped_layers.txt'
    

    As you can see, in the example above, I want to create a text file named 'non_grouped_layers.txt' in the folder /tmp/, I'm on a GNU/Linux machine.

  3. Press Enter.

  4. Copy the following code snippet to your QGIS Python console and, after that, press Enter a couple of times:

    # Get a reference of the layer tree
    root = QgsProject.instance().layerTreeRoot()
    tree = root.children()
    
    # Get names of non-grouped layers
    nonGrouped = []
    for node in tree:
        if isinstance( node, QgsLayerTreeLayer ):
            nonGrouped.append( node.layerName() )
    
    #Save the nonGrouped list as text file
    f = open( textFilePath, 'wt')
    f.write( '\n'.join( nonGrouped ) )
    f.close()
    

You should now have your text file with the list of non-grouped layers.


In the screenshot you can see my QGIS ToC arrangement and the text file I get from running the code snippet.

enter image description here

If you face troubles, tell me.

2
  • On trying this in QGIS3 console I get the following error -is there some difference in running this line? f = open( textFilePath, 'wt') Traceback (most recent call last): File "C:\OSGEO4~1\apps\Python37\lib\codeop.py", line 133, in call codeob = compile(source, filename, symbol, self.flags, 1) File "<input>", line 4 f = open( textFilePath, 'wt') ^
    – GeorgeC
    Feb 16, 2019 at 12:05
  • 1
    node.layerName() has changed in QGIS 3, it should be now node.name(). Other than that, everything should work. Just tested it and it runs smoothly. Feb 16, 2019 at 13:44

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.