1

I developed a plugin for QGIS 3.x but I need to adjust it to work with QGIS 2.x too.

Here is code which is working nice with QGIS 3.x:

root = QgsProject.instance().layerTreeRoot() #QgsLayerTree
group_preview = root.findGroup("Preview")
if group_preview is not None:
     root.removeChildNode(group_preview)
group = root.insertGroup(0, "Group")
raster_layer = QgsRasterLayer(urlWithParams, "new_layer", "wms")

QgsProject.instance().addMapLayer(raster_layer, False)

group.insertLayer(0, raster_layer)

Someone knows what I should use instead of :

root = QgsProject.instance().layerTreeRoot() #QgsLayerTree

to get QgsLayerTree() in QGIS 2.x?

3
  • I think it was QgsMapLayerRegistry.instance(), but it's definitly not the same. Also you should take into account that in qgis2 we had Qt4, not Qt5. So the difficulty starts with importing the correct modules for each version of pyQt. You may find this usefull: gis.stackexchange.com/questions/260125/… or the other way round: new.opengis.ch/2018/04/13/…. At least it maybe easier to develop python2/pyQt4 and port to py3... Commented Mar 25, 2019 at 14:50
  • My advice: if there's any way to avoid it, don't go down this route. The changes are so extreme between v2 and v3 that you'll end up with an maintainable mess of code on your hands.
    – ndawson
    Commented Mar 26, 2019 at 6:15
  • I found solutio, I just post it, tnx for your advices, in the end it was not so comlicated :) @ndawson
    – ncica
    Commented Mar 26, 2019 at 12:28

1 Answer 1

1

If someone else will also need it, here is solution

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

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

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

QgsLayerTreeGroup Class Reference

https://qgis.org/api/2.6/classQgsLayerTreeGroup.html

the rest of the code is almost the same:

group_preview = root.findGroup("Preview")
if group_preview is not None:
    root.removeChildNode(group_preview)
group = root.insertGroup(0, "Group")
raster_layer = QgsRasterLayer(urlWithParams, "new_layer", "wms")

QgsMapLayerRegistry.instance().addMapLayer(raster_layer, False)

layer = QgsLayerTreeLayer(raster_layer)
group.insertChildNode(0, layer) 
# or
root.insertLayer(0, raster_layer )

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.