3

I would like to run a loop with PyQGIS, it should wait for the user to press a key either SpaceBar or Escape to continue.

canvas = qgis.utils.iface.mapCanvas()
aLayer = canvas.currentLayer()

feat = QgsFeature()
iter = aLayer.getFeatures()

while iter.nextFeature(feat):
    aLayer.removeSelection()
    aLayer.select(feat.id())
    qgis.utils.iface.actionZoomToSelected().trigger()

    <wait for user input>

How can I do that?

  • This probably helps you: stackoverflow.com/questions/7255463/… – Martin Feb 5 '15 at 8:04
  • Do you want it to abort iteration or continue to the next feature? If you want it to abort, it will only zoom to the first feature. – gsherman Feb 5 '15 at 16:02
  • I would like to continue to the next feature, until the user presses esc/spacebar... – Pugazh Feb 9 '15 at 8:04
  • I have not tried your code gcarrillo, will let you know soon... – Pugazh Feb 20 '15 at 14:00
  • Ok, let me know if you face any problem. – Germán Carrillo Mar 3 '15 at 3:34
5

If I got you right, you can follow this workflow to iterate through features by pressing the space bar:

  1. Open QGIS, load your layer(s), and save your project.

  2. Download the script iterate_features.py and save it in the same folder as your QGIS project.

  3. Open the QGIS Python console (Plugins->Python console), type the following line, and then press Enter:

    import iterate_features
    
  4. Now click anywhere on your map or ToC.

You should now be able to select and zoom in to the next feature by pressing the space bar or to finish the iteration by pressing Escape.

It should work on the active layer in the ToC, each time you change the active layer, the iterator is restarted.

  • I know that this is an old answer, and that posting "Thanks!" is frowned upon by the Mrs Jessups of the world, but yours is a very nice script, so THANKS. I've tried to implement something similar, iterating automatically through features every 1500msec from when 'Go' was clicked until ESC is pressed (I prefer mindless iterative screen-watching)... auto-iterating worked well, however I couldn't work out how to get the ESC keypress to interrupt QTimer (which I was using to drive the auto-iterator). I'll get there eventually. Thanks again. – GT. Feb 16 '17 at 7:49
  • Great that the script was useful for you. Thanks for your message! I think you could try to connect the ESC key press with something like if self.timer.isActive(): self.timer.stop() – Germán Carrillo Feb 16 '17 at 13:33

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.