3

I have a project opened in Qgis "qgis_training.qgs" and I am trying to add a layer to it via python2.7.6 IDLE using the following code:

from qgis.core import *
from qgis.utils import iface
from PyQt4.QtCore import QFileInfo


# Get the project instance
project = QgsProject.instance()
# Print the current project file name (might be empty in case no projects have been loaded)
print project.fileName()

# Load another project
project.read(QFileInfo('/home/julierme/Desktop/qgis/projetos/qgis_training.qgs'))
print project.fileName()

bridge = QgsLayerTreeMapCanvasBridge( \
QgsProject.instance().layerTreeRoot(), canvas)

# Now you can safely load your project and see it in the canvas
project.read(QFileInfo('/home/julierme/Desktop/qgis/projetos/qgis_training.qgs'))


# Function addVectorLayer: Open and display a vector layer in QGIS  
layer = iface.addVectorLayer("/home/julierme/Desktop/amazonia_sar/amapa/SHP/mask_covmingrad.shp", "mask_covmingrad", "ogr")
if not layer.IsValid():
    print "Layer failed to load!"

# Save the project to the same
project.write()   

I am getting the error message below while running it:

Traceback (most recent call last):
  File "/home/julierme/pyqgis/scripts/script2.py", line 17, in <module>
    bridge = QgsLayerTreeMapCanvasBridge( \
NameError: name 'QgsLayerTreeMapCanvasBridge' is not defined

How can I solve this issue and achieve my goal?

1 Answer 1

1

QgsLayerTreeMapCanvasBridge is in the gui module so you need to:

from qgis.gui import QgsLayerTreeMapCanvasBridge

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.