I am trying to develop a standalone PyQGIS application.
The map display does not pose any problems, but I do not know how to add a legend to the canvas.
To complement Luigi's answer, this is how you can use the Layer Tree View for adding a legend and/or a ToC to your application.
After you create your canvas in your standalone PyQGIS application, you need to create a QgsLayerTreeView. For that, you need a model, and for the model you need the layer tree root. Additionally, you need to use a QgsLayerTreeMapCanvasBridge to keep both map and tree in sync. All this is done with the following code snippet (taken from this Martin Dobias' post):
self.root = QgsProject.instance().layerTreeRoot() self.bridge = QgsLayerTreeMapCanvasBridge(self.root, self.canvas) self.model = QgsLayerTreeModel(self.root) self.model.setFlag(QgsLayerTreeModel.AllowNodeReorder) self.model.setFlag(QgsLayerTreeModel.AllowNodeRename) self.model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility) self.model.setFlag(QgsLayerTreeModel.ShowLegend) self.view = QgsLayerTreeView() self.view.setModel(self.model)
Now, you might want to embed the view into a dock widget inside your application. To do so, you can write the following code right below the previous code:
self.LegendDock = QDockWidget( "Layers", self ) self.LegendDock.setObjectName( "layers" ) self.LegendDock.setAllowedAreas( Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea ) self.LegendDock.setWidget( self.view ) self.LegendDock.setContentsMargins ( 9, 9, 9, 9 ) self.addDockWidget( Qt.LeftDockWidgetArea, self.LegendDock )
When you run your application and load layers or alter any layer symbology, you should see changes reflected in your dock widget, this way:
I followed @kelly-thomas's first example from How to apply a graduated renderer in PyQGIS? for graduated symbols on Natural Earth Data.
Besides displaying your layers' symbology, the Layer Tree View allows you to rename layers, set layer visibility, and change layer order in the map canvas.
Note: Make sure you import the required modules from
PyQt4.QtGui (or simply do
from xxxx import * for all three).
Follow this guide Lutra consulting qgis-layer-tree-api-part-3