DataPlotly icon indicating copy to clipboard operation
DataPlotly copied to clipboard

[feature] New custom function to get the colors from categories used

Open ghtmtt opened this issue 2 years ago • 4 comments

Adds a new custom function to the expression engine that can be used to get the colors of the category used. It works only for the Categorized renderer.

@Gustry @nyalldawson can I have your bless here? :)

ezgif com-gif-maker

ghtmtt avatar Jun 08 '22 14:06 ghtmtt

Sorry if I misunderstand, but if you allow the @symbol_color variable, it should do the job? Even if you are not in "categorize class"... or am I wrong? #233

katagen avatar Jun 10 '22 17:06 katagen

"@symbol_color" would be a good approach to use here, but you'd effectively have to re-create the QGIS c++ code which is used to calculate this. The way QGIS itself handles symbol_color is deep within the vector layer rendering/labeling code, and isn't exposed for reuse in PyQGIS.

The way @ghtmtt has calculated the symbol color is not too bad -- it could be generalized using layer.renderer().originalSymbolsForFeature( feature ) so that you don't need to manually handle all the different renderer types.

Depending on how far you want to go, you could either stick with the custom expression function approach, or instead inject a symbol expression context scope into the expression context used to evaluate the values via something like:

symbols = layer.renderer().originalSymbolsForFeature( feature )
symbol_scope = QgsExpressionContextUtils.updateSymbolScope( symbols[0], QgsExpressionContextScope() )
expression_context.appendScope( symbol_scope )

nyalldawson avatar Jun 13 '22 06:06 nyalldawson

@nyalldawson great to hear that my solution is fine :) if I use the following:

symbols = layer.renderer().originalSymbolsForFeature( feature )

I get this error:

TypeError: QgsFeatureRenderer.originalSymbolsForFeature(): not enough arguments

but if I add the missing argument QgsRenderContext as:

context = QgsRenderContext()
symbols = layer.renderer().originalSymbolsForFeature( feature, context)

the QGIS crashes. It happens both in the custom expression and also with a custom standard python script.

ghtmtt avatar Jun 13 '22 10:06 ghtmtt

@ghtmtt

You probably need to wrap that in startRender/stopRender calls:

context = QgsRenderContext()
renderer = layer.renderer()
renderer.startRender(context, layer.fields())
symbols = layer.renderer().originalSymbolsForFeature( feature, context)
renderer.stopRender(context)

nyalldawson avatar Jun 13 '22 23:06 nyalldawson