0

I'm 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()
canvas.setExtent(zoomRectangle)
canvas.refresh()

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]
couche_parcelles.selectByIds(elemts)
canvas.zoomToSelected(couche_parcelles)
canvas.refresh()

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

0

After many search and trials&errors, here's the solution if it may help anybody :

project = QgsProject.instance()
couche_parcelles = project.mapLayersByName('(Layer's name)')[0]
canvas = qgis.utils.iface.mapCanvas()
canvas.setSelectionColor(QColor.fromRgb(255,255,0))

#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]
couche_parcelles.selectByIds(ids)
canvas.zoomToSelected(couche_parcelles)
canvas.zoomScale(1500)

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.