Thursday, 7 December 2017

pyqgis - QGIS test rules with python


In QGIS 2.14 one can check if a rule gives results:



enter image description here


Is it possible to do this programmatically with python console? I would look for a way to iterate over all layers and there rules (nested rules!) and print those (layer_name:rule_name) which do not have results.



Answer



Perhaps this answer can fully solve your question.


Run this code snippet in the QGIS Python Console:


for layer in QgsMapLayerRegistry.instance().mapLayers().values(): # Iterate layers
if type(layer) == QgsVectorLayer and layer.hasGeometryType():
r = layer.rendererV2()
if r.type() == 'RuleRenderer':
for rule in r.rootRule().children(): # Iterate rules

if rule.filter(): # Filter out empty rules
request = QgsFeatureRequest( rule.filter() )
count = len( [f for f in layer.getFeatures( request )] )
print layer.name() + ' : ' + rule.label() + ' : ' + rule.filterExpression() + ' : ' + str(count)

The first for loop iterates layers, the second one iterates layer rules. First if clause ensures we use vector layers, the second one ensures we only use vector layers with a rule based style, and the last one filters out empty rules.


The result is a list with layer names, rule labels, rule expressions, and the corresponding count, like this:


my_point_layer : My Rule :  "my_code" = '1': 6
my_point_layer : My 2nd Rule : "my_code" IS NULL : 0
my_polygon_layer : My Polygon Rule : "area" > 100 : 2

my_polygon_layer : My 2nd Polygon Rule : "area <= 100 : 28

You could then use the count variable to filter only those with 0 features, which was your original purpose.


Hope this solves your question.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...