3

I'm writing Python script in QGIS 2.18 to alert the user when multiple layers with different projections are added to the canvas. My codes are shown below.

from qgis.gui import QgsMessageBar

input_layers = []
layers = iface.legendInterface().layers()
for layer in layers:
  if layer.type() == QgsMapLayer.RasterLayer:
     input_layers.append(layer)

pcs_list = []
for input in input_layers:
  pcs_list.append(input)
  pcs_str = list(set([pcs.crs().authid() for pcs in pcs_list]))

text = "You have multiple layers with different CRS in this project: " + str(pcs_str).translate(None, "[]u")

if len(pcs_str) >1:
    iface.messageBar().pushMessage("Alert",text, level=QgsMessageBar.WARNING,duration=20)
else:
  pass 

This works fine when I run the script via the Python console. However I'd like this alert to pop-up automatically when new layers (with different projections) are added to the layers panel. I'm aware that layer objects in the layers panel can be accessed through the the layer tree root. Is there any method to monitor changes in the layer tree root?

1
  • Most welcome, glad it helped! Will post the comment as an answer for the convenience of others :)
    – Joseph
    Dec 11, 2017 at 14:54

1 Answer 1

2

You could put your code into a function which can then be called by the QgsMapLayerRegistry::layersAdded signal using:

QgsMapLayerRegistry.instance().legendLayersAdded.connect(myF‌​unc)
3
  • It works fine. However, I notice that it gives me multiple alerts as well. If i run the alert() function individually it shows up only once.
    – Wonka
    Dec 11, 2017 at 15:06
  • 1
    @Wonka - Maybe more layers are being added in one go? You could add iface.messageBar().clearWidgets() before iface.messageBar().pushMessage(...) so that all previous messages are removed.
    – Joseph
    Dec 11, 2017 at 15:11
  • 1
    Brilliant! It doesn't show multiple message bars anymore. Thank you once again.
    – Wonka
    Dec 12, 2017 at 8:41

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.