Related to the following question but looking for a PyQGIS method:
QGIS Layer Order Panel – add layers at top of layer order
The following is a simple setup containing a group with three layers.
The code I use adds a new layer at the end of this group:
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
In the Layer Order Panel, the newly added layer is at the end.
Is it possible to move this to the top without moving the layer in the Layers Panel?
Best Answer
You can set layer order in the
Layer Order Panel
"manually" usingQgsLayerTreeCanvasBridge.setCustomLayerOrder()
method, which receives an ordered list of layer ids. For instance (assuming you just loadedvlayer
):To automatically move newly added layers to the top of
Layer Order Panel
, you could use thelegendLayersAdded
SIGNAL (this signal is appropriate because it's emitted after theLayer Order Panel
gets the new layer) fromQgsMapLayerRegistry
and reorder layers in this way:NOTE: Since you're loading your
vlayer
callingQgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
, thatFalse
parameter prevents thelegendLayersAdded
SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer).