1

How to set map canvas extent / view? I've tried with setExtent(Qrect(..)) but does not work.

mc = iface.mapCanvas()
rect = QgsRectangle()
rect.setXMaximum = 5
rect.setXMinimum = 2
rect.setYMaximum = 10
rect.setYMinimum = 3
mc.setExtent(rect)    
4
  • 2
    Your code works for me, maybe try to set an extent of a layer as rect, to see if it really works or not. Like this layer = iface.activeLayer() ; rect = layer.extent() ; iface.mapCanvas().setExtent(rect); and add a iface.mapCanvas().refresh() at the end of your code to refresh the resolution.
    – JULESG
    Jul 27 '21 at 13:14
  • Your code work. The the layer fit with the canvas area. But with my code no, the object become very small and out of canvas view.
    – user188858
    Jul 27 '21 at 14:02
  • What CRS are you using in your project ?
    – JULESG
    Jul 27 '21 at 14:48
  • I'm using EPSG:4326
    – user188858
    Jul 27 '21 at 15:04
0

Solved!

mc=iface.mapCanvas()
layer = iface.activeLayer()
geocella=layers[0]
features= geocella.getFeatures()
basepath =  "C:/Users/user/Desktop/export_maps_QGIS/OUT"

i = 0
for ftr in features:
    name = ftr['name']
    print("Name:")
    print(name)
    bb = ftr.geometry().boundingBox()
    xmax = bb.xMaximum()
    xmin = bb.xMinimum()
    ymax = bb.yMaximum()
    ymin = bb.yMinimum()
    rect = QgsRectangle(xmin, ymin, xmax, ymax)
    rect.setXMaximum = xmax
    rect.setxMinimum = xmin
    rect.setyMaximum = ymax
    rect.setyMinimum = ymin
    
    iface.mapCanvas().setExtent(rect)

    iface.mapCanvas().refresh()
    
    mc.setExtent(rect)
    settings = iface.mapCanvas().mapSettings()
    settings.setOutputSize(QSize(1000, 1000))
    settings.setExtent(rect)
    settings.setFlag(QgsMapSettings.DrawLabeling, False)
    settings.setFlag(QgsMapSettings.Antialiasing, True)

    job = QgsMapRendererSequentialJob(settings)
    job.start()
    job.waitForFinished()
    image = job.renderedImage()

    filepath = os.path.join(basepath, "out" + str(i) + ".tif")
    image.save(filepath)
    i = i + 1

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.