1

Imagine that the lines that i have drawn is simple pipeline network, represented by some simple lines in a vector layer.

How can i define a script that changes the color of only specific lines to "red"?

I tried to write a script from google sources but i failed dramatically. I managed to change the color of the all the lines but i need to specify the "red" color. So far my script is this, but its not working:

enter image description here

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface

def change_color():
    active_layer = iface.activeLayer()
    """renderer = active_layer.rendererV2()"""

    renderer = QgsCategorizedSymbolRendererV2()
    active_layer.setRendererV2(renderer)
    symbol = QgsSymbolV2.defaultSymbol(active_layer.geometryType())
    symbol.setColor(QColor(Qt.red))
    active_layer.setCacheImage(None)
    iface.mapCanvas().refresh()
    iface.legendInterface().refreshLayerSymbology(active_layer)

change_color()

This is what i am looking for but with a script not manually enter image description here

3
  • Welcome to GIS SE! As a new user be sure to take the Tour. Please always include code as text rather than pictures so that it is available for searches and testing by visitors to our site. – PolyGeo Mar 3 '15 at 0:39
  • When i tried to copy paste the copy from the Notepad++ it seemed ok and intended properly, but on the preview below it wasnt properly intended so i posted a picture. Anyway, this code is not working so.. – Stelios M Mar 3 '15 at 0:46
  • You just need to format it by highlighting your code and clicking the {} button. – PolyGeo Mar 3 '15 at 0:49
3

You are almost there. You need this:

cat = QgsRendererCategoryV2(1, symbol, "1")
renderer.addCategory(cat)

A full example

renderer = QgsCategorizedSymbolRendererV2("id")
active_layer.setRendererV2(renderer)
symbol = QgsSymbolV2.defaultSymbol(active_layer.geometryType())
symbol.setColor(QColor(Qt.red))
cat = QgsRendererCategoryV2(1, symbol, "1")
renderer.addCategory(cat)
4
  • maybe i didn't explain briefly what i am asking. Please see the new pic on my initial post – Stelios M Mar 3 '15 at 1:08
  • That is what the code will do, just change the 1 to what ever value the line is. – Nathan W Mar 3 '15 at 1:09
  • Well, it does make the line-1 red but it deleted the rest. The other categories are gone. Sorry for the spam but i need this for an uni project – Stelios M Mar 3 '15 at 1:15
  • It will, you will need a category for all the other numbers. Or use the rule based renderer – Nathan W Mar 3 '15 at 1:27

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.