1

I work on PyScripter, i managed to display a vector layer from Postgresql with a symbology.
But I have a difficulty to display a legend.

def main():

def init():

# appel de l'application et initialisation a = QgsApplication(sys.argv, True) QgsApplication.setPrefixPath("C:/OSGeo4W/apps/qgis", True) QgsApplication.initQgis() return a

def show_shape(app):

# definition a connection
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "stat", "postgres", "admin")
uri.setDataSource("public", "com", "the_geom", ' ', "gid")
uri.uri()

# création d'une fenêtre et chargement d'une couche
carte = QgsMapCanvas()
layer=QgsVectorLayer(uri.uri(), 'com', 'postgres')
if not layer.isValid():
   print "Layer failed to load!"

# add layer to the registry
QgsMapLayerRegistry.instance().addMapLayer(layer)
carte.setExtent(layer.extent())

# affichage de la couche dans une fenêtre
carte.setLayerSet( [ QgsMapCanvasLayer(layer) ] )
carte.show()

#personnaliser la symbologie
myTargetField = 'code'
myRangeList = []
myOpacity = 1

# Make our first symbol and range...
myMin = 0.0
myMax = 100.0
myLabel = '0.0-200'
myColour = QtGui.QColor('white')#ffee00
mySymbol1 = QgsSymbolV2.defaultSymbol(layer.geometryType())
mySymbol1.setColor(myColour)
mySymbol1.setAlpha(myOpacity)
myRange1 = QgsRendererRangeV2(myMin,myMax,mySymbol1,myLabel)
myRangeList.append(myRange1)

#now make two symbol and range...
myMin = 100.1
myMax = 102
myLabel = '200.1-500'
myColour = QtGui.QColor('yellow')#00eeff
mySymbol2 = QgsSymbolV2.defaultSymbol(layer.geometryType())
mySymbol2.setColor(myColour)
mySymbol2.setAlpha(myOpacity)
myRange2 = QgsRendererRangeV2(myMin,myMax,mySymbol2,myLabel)
myRangeList.append(myRange2)

myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
myRenderer.setClassAttribute(myTargetField)

layer.setRendererV2(myRenderer)
QgsMapLayerRegistry.instance().addMapLayer(layer)
print "fine"

app.exec_()

app = init() show_shape(app)

if name == "main": main()

1

Not sure if I got you right, but you can add a legend widget to your PyQGIS application following How to add a legend to a canvas in a standalone PyQGIS application?

Besides displaying your layers' symbology, it allows you to rename layers, set layer visibility, and change layer order in the map canvas.

  • I'll try with this example, and I remind you soon – Nora 27 May 13 '15 at 7:53
  • @Nora27 So, did it work for you? – Germán Carrillo Jul 14 '15 at 19:49
  • Unfortunately no, I did not understand how can I rephrase the code. I tried many – Nora 27 Sep 13 '15 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.