2

Follow-up to this question, after input considering this other question:

To figure out which feature in a QGis vector layer, styled with a categorized renderer, is currently visible (i.e. enabled), I need to

a) Get the value of each category, e.g. with

print [cat.value() for cat in layer.rendererV2().categories()]

--> [u'', u'1', u'9']

b) Get the status of the checkbox, e.g. with

ltl = QgsProject.instance().layerTreeRoot().findLayer( layer.id() )
ltm = iface.layerTreeView().model()
legendNodes = ltm.layerLegendNodes( ltl )
print [node.data(Qt.CheckStateRole) for node in legendNodes]

--> [2, 0, 2]

So far, so good. Can I rely on the order of those two being the same or do I have to do some sort of cross-checking (and if so, any ideas how? The symbol instances that I can access through both paths don't seem to match...)

2

Instead of the value,, you could match the legend name with its checkstate:

legend_names = [node.data(Qt.DisplayRole) for node in legendNodes]
legend_state = [node.data(Qt.CheckStateRole) for node in legendNodes]

[a for b in zip(legend_names,legend_state) for a in b]

Example:

Example

Code used:

from PyQt4.QtCore import Qt

layer = iface.activeLayer()
ltl = QgsProject.instance().layerTreeRoot().findLayer( layer.id() )
ltm = iface.layerTreeView().model()
legendNodes = ltm.layerLegendNodes( ltl )

legend_names = [node.data(Qt.DisplayRole) for node in legendNodes]
legend_state = [node.data(Qt.CheckStateRole) for node in legendNodes]

[a for b in zip(legend_names,legend_state) for a in b]
| improve this answer | |
  • 2
    Good suggestion! Still, I'd rather not do this association via strings, especially since the labels might be the same for two categories. – LuWi Aug 2 '17 at 12:04
  • 1
    @LuWi - Good point! I think you may be right in that the order of the legend nodes are read sequentially (i.e. the values and the checkbox state seem to match). – Joseph Aug 3 '17 at 9:24

Your Answer

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

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