13

Is it possible to change the color while adding a vector layer?

I have a vector layer with water areas and want to load it with a blue color style. The layer is added with:

QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)

Can I change the color after or while loading?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Martin
  • 2,908
  • 4
  • 22
  • 44

2 Answers2

12

You can use something like this:

symbols = self.vlayer.rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QColor.fromRgb(50,50,250))
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Sassá
  • 498
  • 3
  • 12
7

Finally with this code the change of a layer color is working for me:

QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)       
symbols = self.vrlayer.rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QtGui.QColor.fromRgb(50,50,250))
qgis.utils.iface.mapCanvas().refresh() 
qgis.utils.iface.legendInterface().refreshLayerSymbology(self.vlayer)

You have to reload the MapCanvas and the layers panel aswell.

Martin
  • 2,908
  • 4
  • 22
  • 44
  • What module do you need to load to get access to rendererV2()? – user2627043 Sep 05 '20 at 02:54
  • @user2627043 and those trying to reuse old examples: Like many answers here, this one is outdated. As of today, color can be changed by: vlayer.renderer().symbol().setColor(QColor.fromRgb(50,50,250)). See also this answer. – mins Mar 01 '22 at 09:43