3

I'm writing a plugin in QGIS3 which produces a vector file from a thresholded raster (i.e. polygons all have a value of 1 or 0). So far so good. I'd now like to load it in QGIS and display the results so that the 1 values in the vector are displayed (as a filled color) and the 0 values aren't displayed at all. This should just be a display of a categorized vector but I can't figure out the best approach in QGIS3.

Can anyone point me in the right direction, please? I don't have any code to share on this point. I got as far as

processing.run("gdal:polygonize", {'INPUT': self.threshold_raster_obj, 'BAND':1, 'FIELD':'DN','EIGHT_CONNECTEDNESS':False,'OUTPUT': self.out_vectorFilename})
current_layer = self.iface.addVectorLayer(self.out_vectorFilename, "Polygonize_result", "ogr")

i.e. I can polygonize my raster, save it and load it into the main window but I've no idea where to start with the display options. I've looked at some of the examples but I've not been able to understand the right approach for polygons. Unfortunately some things are not intuitive for novices like myself.

0

1 Answer 1

5

I've included some code with comments to show how to categorise a layer with the most basic properties which hopefully should get you started:

#current_layer = iface.activeLayer()

# Create dictionary to store
# 'attribute value' : ('symbol colour', 'legend name')
land_class = {
    '0': ('#0f0', 'Transparent polygons'),
    '1': ('#f00', 'Filled polygons')
}
# Create list to store symbology properties
categories = []
# Iterate through the dictionary
for classes, (color, label) in land_class.items():
    # Automatically set symbols based on layer's geometry
    symbol = QgsSymbol.defaultSymbol(current_layer.geometryType())
    # Set colour
    symbol.setColor(QColor(color))
    # Set symbol with value = 0 to be transparent
    if classes == '0':
        symbol.setOpacity(0)
    # Set the renderer properties
    category = QgsRendererCategory(classes, symbol, label)
    categories.append(category)

# Field name
expression = 'DN'
# Set the categorized renderer
renderer = QgsCategorizedSymbolRenderer(expression, categories)
current_layer.setRenderer(renderer)
# Refresh layer
current_layer.triggerRepaint()
2
  • 1
    Thank you so much. That really helps. I find the core documentation hard to navigate as you have to seem to have to know what the class is that you need. I'm getting better but it's not easy for novices to get to grips with. THanks again.
    – SJJ
    Apr 15, 2019 at 10:09
  • @SJJ - Most welcome, glad it helped. What I normally do is google "qgis api " followed by the term I'm searching for. Usually it works :)
    – Joseph
    Apr 15, 2019 at 10:13

Your Answer

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

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