1

I'm currently updating some python code from QGIS 2.18 to QGIS 3.4

in 2.18 i used the following code :

#First off I created a virtual layer using an sql query here

vlayer = QgsVectorLayer( "?query=...., "virtual" )

# Then I assign the properties of the polyline layer here

props = { 'width' : '3', 'color' : '255,0,0' } 
sl = QgsSymbolLayerV2Registry.instance().symbolLayerMetadata("SimpleLine").createSymbolLayer(props)
s = QgsLineSymbolV2([sl]) vlayer.setRendererV2( QgsSingleSymbolRendererV2( s ) )

I know there have been a number of changes in QGIS 3 for exempleQgsSymbolLineSymbolV has become QgsLineSymboland setRendererV2 which becomes setRenderer. So, with the help of this blog this GitHubthe API and the most recent doc on the QGIS site, I've put the script below together...

layer = QgsProject.instance().mapLayersByName("t_alpha")[0]

single_symbol_renderer = layer.renderer()

symbol = single_symbol_renderer.symbol()

symbol.setColor(QColor.fromRgb(255, 0, 0))
symbol.setWidth(3)


layer.triggerRepaint()

qgis.utils.iface.layerTreeView().refreshLayerSymbology(layer.id())

But this returns an error:

AttributeError: 'QgsCategorizedSymbolRenderer' object has no attribute 'symbol'

I've dug through the doc and otherwise tried to remodulate the code a bit but I'm a bit stuck (i'm still learning Python).

  • 1
    Your code works if the initial style uses simple symbology. If it was categorised then that error would appear. You should probably set which style you want to use and then apply the relevant settings. The documentation should help. – Joseph Jan 31 at 13:08
  • @Joseph Thanks, that helps - i was trying to modify a layer which had a categorised style! Ok I'll dive back into the doc - so i need to modfiy the layers style setting first (i.e. catagorised to simple) and then apply the above script? – lhowarth Jan 31 at 15:44
  • Yes or you could modify it via your script if you add the logic. I think the example code in the docs I linked to shows how you can apply a simple symbology to your layer without you having to manually change it. – Joseph Jan 31 at 15:50
1

In QGIS 3.4.x is:

layer = QgsProject.instance().mapLayersByName("t_alpha")[0]
layer.renderer().symbol().setWidth(0.7)
layer.triggerRepaint()
0

In QGIS 3+:
For single symbology renderer: renderer = QgsSingleSymbolRenderer(symbol) iface.activeLayer().setRenderer(renderer) iface.activeLayer().triggerRepaint()

For categorized symbology: create categories with QgsRendererCategory doc
create renderer with QgsCategorizedSymbolRenderer and the categories doc
and iface.activeLayer().setRenderer(renderer) iface.activeLayer().triggerRepaint()

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.