I have a code which is adding raster layeror group of raster layers, its working fine.

I want to know if there is a way to add layer or group of the layers always on the top of the legend Interface?

root = self.iface.legendInterface()
if status: # True
    group = root.addGroup("Group")
    layer = self.iface.addRasterLayer(urlWithParams, "new_layer", "wms")

else: # False
    self.iface.addRasterLayer(urlWithParams, "new_layer", "wms")

Believe it or not, somebody wrote a plugin just for that!!! :)

Have a look at the New layers to the top plugin. You can check it first as a user and then examine the code and borrow a couple of lines that you probably need for your Python code, namely:

def changeLayerAdditionMode( self, layers ):          
    QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0 )

QgsMapLayerRegistry.instance().layersAdded.connect( self.changeLayerAdditionMode )
  • tnx for advice but QgsProject class is not available in QGis 2.x – ncica Mar 26 at 18:34
  • QgsProject exists in QGIS v2.x (see api docs v2.0). I created the plugin specifically for QGIS 2. – Germán Carrillo Mar 26 at 21:41
  • Thnak you, I test it, its really nice solution! :) @Germán Carrillo – ncica Mar 27 at 8:43

I was searching for unique solution that will work in QGIS 2.x and QGIS 3.x:

add layer or group of layers always on the top of the legendInterface / Insert the layer or group of layers at the top of the ToC.

How QgsProject class is not available in QGIS 2.x, here is the solution I was looking for:

        # QGis 3.x
        root = QgsProject.instance().layerTreeRoot()

        # QGis 2.x
        root = self.iface.layerTreeCanvasBridge().rootGroup()

    # the rest of the code is the same for QGis version 2.x and 3.x
    raster_layer = QgsRasterLayer(urlWithParams, "new_layer", "wms")
    QgsMapLayerRegistry.instance().addMapLayer(raster_layer, False)

    # Insert group with layer on the top of the legendInterface
    layer = QgsLayerTreeLayer(raster_layer)
    group = root.insertGroup(0, "new_group")
    group.insertChildNode(0, layer)

    # insert layer on the top of the legendInterface
    root.insertLayer(0, raster_layer)

code is tested with QGis 2.18 Las Pamas and QGis 3.4 Madeira

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.