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?

0

2 Answers 2

12

You can use something like this:

symbols = self.vlayer.rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QColor.fromRgb(50,50,250))
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.

2
  • What module do you need to load to get access to rendererV2()? Sep 5, 2020 at 2: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 1, 2022 at 9:43

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