I am using QGIS 3.4.4.

I am trying to zoom on a specific place of my map using PyQGIS

In order to do so I've defined the layer I wanted to get the features :

couche_parcelles = QgsProject.instance().mapLayersByName('Parcelles')[0]

Then I defined the extent of my layer in order to zoom :

ext = couche_parcelles.extent()
xmin = ext.xMinimum()
xmax = ext.xMaximum()
ymin = ext.yMinimum()
ymax = ext.yMaximum()
zoomRectangle = QgsRectangle(xmin,ymin,xmax,ymax)

Then I created the canvas in order to have a reference to my layer :

canvas = qgis.utils.iface.mapCanvas()

Then I get the Id's I need to get the zoom on the specific point I'm aiming at :

identifiants_parcelles = [x['Idu'] for x in couche_parcelles.getFeatures()]

Finally, I write the block which is supposed to make me zoom on my section :

expr = "\"Id\"=36773"
selection = QgsExpression(expr)
vecteur = couche_parcelles.getFeatures(QgsFeatureRequest(selection))
elemts = [x for x in vecteur]

It did work once without the need to specify the extent of my layer but then I've had the same error : Cannot zoom to selected feature(s): No extend could be determined

and yet I did determine my extent here so I don't understand why QGIS doesn't perform the zoom on the Id I'm giving him


This is the solution that I used:

project = QgsProject.instance()
couche_parcelles = project.mapLayersByName("(Layer's name)")[0]
canvas = qgis.utils.iface.mapCanvas()

#select according to the "cadastre" unique id called "Idu"
expr = "\"Idu\"='(number of the selection)'"
selection = QgsExpression(expr)
it = couche_parcelles.getFeatures(QgsFeatureRequest(selection))

ids = [i.id() for i in it]
| improve this answer | |

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.