0

My plugin has arrow button that I can use to click through the features of a layer and it will jump to that feature. For a Point layer this works great, the user can zoom to the amount they like and when they click the arrows it will jump to that feature and keep the same zoom level they already had. For a polygon layer, though, it will zoom in to where the polyon takes up the hole map canvas. Is there any way to jump to the feature and keep the same zoom level? here is my code for the arrow buttons:

def right_arrow_poly(self):
    if self.poly_features and self.current_selection_poly < len(self.poly_features):
        self.current_selection_poly += 1
        self.AttributeNumberPolyBox.setText(str(self.current_selection_poly))
        self.poly_layer.selectByIds([self.current_selection_poly])
        box = self.poly_layer.boundingBoxOfSelected()
        iface.mapCanvas().setExtent(box)
        iface.mapCanvas().refresh()
        self.poly_layer.removeSelection()

def left_arrow_poly(self):
    if self.poly_features and self.current_selection_poly > 1:
        self.current_selection_poly -= 1
        self.poly_layer.selectByIds([self.current_selection_poly])
        box = self.poly_layer.boundingBoxOfSelected()
        iface.mapCanvas().setExtent(box)
        iface.mapCanvas().refresh()
        self.AttributeNumberPolyBox.setText(str(self.current_selection_poly))
        self.poly_layer.removeSelection()
1
  • 1
    Instead of changing the extent based on a feature, you can use the setCenter method from the QgsMapCanvas class. It uses a point as center, maybe with the centroid of the feature it can work.
    – JULESG
    Commented May 4, 2022 at 14:44

1 Answer 1

1

I created a quick script with the setCenter method from the QgsMapCanvas class. It allows you to change the extent of the canvas without changing zoom level. It works with Polygons, Lines and Points.

Here is the snippet:

layer = iface.activeLayer()
feature_number = 0
feature = layer.getFeature(feature_number)
centroid = feature.geometry().centroid().asPoint()
iface.mapCanvas().setCenter(centroid)
iface.mapCanvas().refresh()
1
  • That works perfectly. Thank you!
    – tbob
    Commented May 4, 2022 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.