0

I am creating a QGIS map of events for which I have the date (year) and also rather long event names. I would like to show only the dates in the actual map and display the names in a legend. I am also using the dates to colour the points by category (see screenshot below), so "legend" shows me the dates as default values.

Instead of adding the new values manually in each row, I would like to use a function to automatically add the values from my "name" attribute column.

Is that possible?

I could not find what I was looking for in the QGIS-3 documentation.

enter image description here

0

1 Answer 1

1

You can make the change automatically by running in Python QGIS console the following code after selecting your layer

# Tested with categorised style using file https://github.com/nvkelso/natural-earth-vector/raw/master/geojson/ne_50m_admin_0_countries.geojson
# with column adm0_a3 for field
# Then, run the following
layer = iface.activeLayer()

fieldcolname = 'adm0_a3' # For your case, replace it with 'From'

for index, category in enumerate(layer.renderer().categories()):
    identifier = category.value()
    expr = QgsExpression(""""{}"='{}'""".format(fieldcolname, identifier))
    filtered = layer.getFeatures(QgsFeatureRequest(expr))
    if (filtered):
        results = [f for f in filtered]
        if len(results) == 1:
            feature = results[0]
            # Line below is where you could make change
            # to fit the label formatting you want
            # (by default it should be fine)
            columnContent = "{}: {}".format(feature[fieldcolname], feature['name'])
            layer.renderer().updateCategoryLabel(index, columnContent)
        else:
            print(results, category.value(), category.label())
    else:
        print("No result for filter")

# To refresh left part of the tree
# Can be unwanted for your situation
iface.layerTreeView().refreshLayerSymbology(layer.id())
0

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.