I want to iterate over line features to change color of each feature to the color I choose. So my file has 7 features, I want am writing the code below, but it does not seem to work.

line_feats = [f for f in line_layer.getFeatures()]
clr = ["blue","red","green","yellow","magenta","cyan","black","red"]
for l in line_feats:
    iface.mapCanvas().setSelectionColor( QColor(clr[l.id()]))

I have tried printing l.id() and it goes from 0 to 7, so indexing is not the issue. The thing is, it does not change the color individually, rather it changes for the entire file.


1 Answer 1


It seems what you want to do is not a "selection" but a "symbology". Because for selection, there is only a single color available for the whole QGIS project. You can find the selection color in QGIS Project settings, "General" tab.

You want to do a Categorized Rendering, which is in the Layer Properties, "Symbology" tab. To do that from PyQGIS, using feature ID as you have mentionned :

color = ["blue","red","green","yellow","magenta","cyan","black","red"]

categories = []
for i, value in enumerate(color):
    symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.LineGeometry)
    category = QgsRendererCategory(str(i), symbol, value)

renderer = QgsCategorizedSymbolRenderer('$id', categories)

Open the layer properties, "Symbology" tab after this script to check the result.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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