0

I am using QGIS V3.22.6.

I have imported a set of polygons digitised in Google Earth. They all have the same name but have different polygon colours.

I would like to rename these according to their colour, but am unable to work out how to select the polygon by colour.

8
  • 2
    Can you provide sample data? How many colors are there? You have saved color names in attributes?
    – Babel
    Mar 12 at 11:04
  • Very simple - I have about 300 elements with only 3 different colours (all either primary or secondary, so no variation allowance required.
    – Norman
    Mar 12 at 11:06
  • The colour names are not in the attribute table
    – Norman
    Mar 12 at 11:08
  • 1
    But where are the colors defined then?
    – Babel
    Mar 12 at 11:11
  • I don't know! I can't see that anywhere - sorry, I'm new to QGIS. I will upload a sample if you tell me how I can do that.
    – Norman
    Mar 12 at 11:12

1 Answer 1

7

You need a script to select same colored features because the kml layer uses "Embedded Symbols" and the attribute table doesn't include any information about colors or polygons with same color.

  • Open Python Editor (Ctrl+Alt+P then click middle icon)
  • Select the layer and run this script.
# get active layer
layer = iface.activeLayer()
# feature list
features = list(layer.getFeatures(QgsFeatureRequest().setFlags(QgsFeatureRequest.EmbeddedSymbols)))
# embedded symbols
symbols = [f.embeddedSymbol().clone() if f.embeddedSymbol() else None for f in features]
# colors of embedded symbols
colors = {f.id(): s.color().name() for f, s in zip(features, symbols)}

for color in set(colors.values()):
    # features with the same color
    feature_ids = [fid for fid, c in colors.items() if c == color]
    layer.selectByIds(feature_ids) # select the features
    
    # extract the selected features as temporary layer
    output = processing.run("native:saveselectedfeatures",
                            {'INPUT':layer,
                             'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]
                             
                             # set color and name for the output
    output.renderer().symbol().setColor(QColor(color))
    output.setName(color)
    
    # add the layer to the project
    QgsProject.instance().addMapLayer(output)

enter image description here

2
  • Excellent, thank you
    – Norman
    Mar 13 at 9:19
  • 3
    If you are satisfied with the solution, please consider upvoting by clicking on the arrows next to the score and/or marking it as the accepted answer by clicking on the checkmark ✓. This shows others that the question is solved and will remove it from the list of unanswered questions. Mar 13 at 9:37

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.