3

I have set up a graduate symbol renderer (QGIS cookbook - Graduated Symbol Renderer), and I am now trying to make it conditionally applied to some features only, depending on one (or more) attributes. For example, only trying to apply the render to features having X value and not display the other ones.

Is QgsRuleBasedRenderer to be used or should I go with creating a virtual layer with only the required features following my requirements?

from qgis.PyQt import QtGui

file = 'C:/Users/Administrator/Desktop/20200123_T00_QGIS.txt'
uri = "file:///" + file + "?delimiter=|%5Ct%7C&skipLines=27&skipEmptyFields=Yes&detectTypes=yes&xField=Longitude&yField=Latitude&crs=EPSG:4326&spatialIndex=no&subsetIndex=no&watchFile=no"

Hsep = QgsVectorLayer(uri, 'Hsep', "delimitedtext") 
QgsProject.instance().addMapLayer(Hsep)
layer = Hsep
targetField = 'H-sep'

rangeList =[]
opacity = 1

# define value ranges
minVal = 0.1
maxVal = 0.3
# range label
lab1 = '0.1 - 0.3'
# color (yellow)
rangeColor = QtGui.QColor('light green')
# create symbol and set properties
symbol1 = QgsSymbol.defaultSymbol(layer.geometryType())
symbol1.setColor(rangeColor)
symbol1.setOpacity(opacity)
symbol1.symbolLayer(0).setStrokeStyle(Qt.PenStyle(Qt.NoPen))
#create range and append to rangeList
range1 = QgsRendererRange(minVal, maxVal, symbol1, lab1)
rangeList.append(range1)

# define value ranges
minVal = 0.3
maxVal = 0.5
# range label
lab2 = '0.3 / 0.5'
# color (yellow)
rangeColor = QtGui.QColor('red')
# create symbol and set properties
symbol2 = QgsSymbol.defaultSymbol(layer.geometryType())
symbol2.setColor(rangeColor)
symbol2.setOpacity(opacity)
symbol2.symbolLayer(0).setStrokeStyle(Qt.PenStyle(Qt.NoPen))
#create range and append to rangeList
range2 = QgsRendererRange(minVal, maxVal, symbol2, lab2)
rangeList.append(range2)

# create the renderer
groupRenderer = QgsGraduatedSymbolRenderer('', rangeList)
groupRenderer.setMode(QgsGraduatedSymbolRenderer.EqualInterval)
groupRenderer.setClassAttribute(targetField)
# apply renderer to layer
layer.setRenderer(groupRenderer)

# add to QGIS interface
QgsProject.instance().addMapLayer(layer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.