The following example assumes that you have loaded a point vector layer:
uri = "E:/Geodata/NaturalEarth/vector_v4/natural_earth_vector.gpkg_v4.1.0/packages/natural_earth_vector.gpkg|layername=ne_110m_populated_places_simple" vlayer = iface.addVectorLayer(uri, "places", "ogr")
By default, QGIS displays points as randomly colored circles. Let’s see how we can alter the symbology!
First, let’s make the circles bigger:
Don’t forget to call triggerRepaint()! Otherwise you won’t see the changes taking effect.
Nice! Let’s take one step back and examine the code:
vlayer.renderer() gives us access to the vector layers renderer object. There are different types of renderers. As a QGIS user you know them as Single Symbol (QgsSingleSymbolRenderer), Categorized (QgsCategorizedSymbolRenderer), Graduated (QgsGraduatedSymbolRenderer), and so on.
By default, vector layers are assigned single symbol renderers. These renderers have a single symbol that we can access using the symbol() function.
Now that we have access to the symbol, we can change its size using the setSize() function, providing it a numeric value for the desired size.
Similarly, we can change the symbol’s color using setColor():
The setColor() function expects a QColor object as its parameter. This is why we create a new QColor object using QColor(“blue”). (There are many other ways to create a QColor object which you can find in the official Qt documentation.)
Finally, let’s get rid of those boring circles and have stars instead:
Note how we are not calling symbol().setShape() but symbol().symbolLayer(0).setShape()! This is because each symbol can consist of multiple symbol layers but by default it has only one. We can access this first (and only) symbol layer using symbolLayer(0). The symbol layer is the right place to change the shape of the marker using setShape(). Available shapes (based on QgsSimpleMarkerSymbolLayerBase) include: Arrow, ArrowHead, ArrowHeadFilled, Circle, Cross, Cross2, CrossFill, DiagonalHalfSquare, Diamond, EquilateralTriangle, HalfSquare, Hexagon, LeftHalfTriangle, Line, Pentagon, QuarterCircle, QuarterSquare, RightHalfTriangle, SemiCircle, Square, Star, ThirdCircle, and Triangle.
Finally, you might have noticed that the symbol in the layer list (right next to the layer name) has not been updated. To fix this, we need to call the correct refresh function:
The refreshLayerSymbology() function needs to know which layer’s symbology should be refreshed. That’s why we need to provide it with our vector layer’s id.
These are the basics of vector styling using a single symbol renderer with a symbol consisting of one symbol layer.
For more styling options check Advanced point layer styling.
PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!