4

i'm developping a plugin (under QGis 2.8.1) for traffic assignment where I want to show the results of my simulation at each time step. Right now I'm using Time Manager plugin but it gets very slow when my layer has hundreds of thousands of attributes. In my case I know exactly what feature IDs I want to show at each time step so I thought it would be easy to make it faster. Then I tried 2 solutions:

Here is what I tried: at each time step of my loop I set the ordered list of indexes of attributes to show (they are always ordered in my case) indexes = list(j for j in range(index_start, index_end)) then I tried 2 solutions:

  1. Use of

    my_layer.setSubsetString("fid>=indexes[0] AND fid<=indexes[-1]")
    
  2. Use of

    request = QgsFeatureRequest().setFilterFids(indexes)
    my_layer.getFeatures(request)
    

I use self.iface.mapCanvas().refresh() to refresh the view Solution 1 works as it refresh the view with the right filtered features but it is even slower than using a SQL expression not based on the indexes. Solution 2 is fast but the display of the layer doesn't change. Any idea why?

  • Welcome to GIS:SE @Daniel! For solution 2, have you tried adding my_layer.triggerRepaint() at the end? – Joseph May 10 '16 at 15:10
  • Solution 2 doesn't work because 'my_layer.getFeatures(request)' is a QgsFeatureIterator object (see my answer). – xunilk May 17 '16 at 17:39
1

Solution 2 doesn't work because 'my_layer.getFeatures(request)' is a QgsFeatureIterator object. You have to create, for example, a memory layer with the features "into" this object. In my case, I used the next shapefile, with 8 features, for selecting the features with indexes 1, 5 and 7.

enter image description here

The complete code is:

layer = iface.activeLayer()

request = QgsFeatureRequest().setFilterFids([1, 5, 7])

iter = layer.getFeatures(request)

print iter #to corroborate that it is a QgsFeatureIterator object

epsg = layer.crs().postgisSrid()

uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri, 
                           'request',
                           'memory')

prov = mem_layer.dataProvider()

feats = [ feat for feat in iter ]

for i, feat in enumerate(feats):
    feat.setAttributes([i])

prov.addFeatures(feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

When I run the code at the Python Console of PyQGIS I got:

enter image description here

Features in green color corresponding to request.

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.