3

I have created a standalone application to display the vector layer using PyQGIS code given below. Now I want to download the map which shows on the window with whatever the zoom level I have chosen.

from qgis.gui import *
from qgis.PyQt.QtWidgets import QAction, QMainWindow
from qgis.PyQt.QtCore import Qt

class MyWnd(QMainWindow):
  def __init__(self, layer):
    QMainWindow.__init__(self)

    self.canvas = QgsMapCanvas()
    self.canvas.setCanvasColor(Qt.white)

    self.canvas.setExtent(layer.extent())
    self.canvas.setLayers([layer])

    self.setCentralWidget(self.canvas)

    self.actionZoomIn = QAction("Zoom in", self)
    self.actionZoomOut = QAction("Zoom out", self)
    self.actionPan = QAction("Pan", self)

    self.actionZoomIn.setCheckable(True)
    self.actionZoomOut.setCheckable(True)
    self.actionPan.setCheckable(True)

    self.actionZoomIn.triggered.connect(self.zoomIn)
    self.actionZoomOut.triggered.connect(self.zoomOut)
    self.actionPan.triggered.connect(self.pan)

    self.toolbar = self.addToolBar("Canvas actions")
    self.toolbar.addAction(self.actionZoomIn)
    self.toolbar.addAction(self.actionZoomOut)
    self.toolbar.addAction(self.actionPan)

    # create the map tools
    self.toolPan = QgsMapToolPan(self.canvas)
    self.toolPan.setAction(self.actionPan)
    self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
    self.toolZoomIn.setAction(self.actionZoomIn)
    self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
    self.toolZoomOut.setAction(self.actionZoomOut)

    self.pan()

  def zoomIn(self):
    self.canvas.setMapTool(self.toolZoomIn)

  def zoomOut(self):
    self.canvas.setMapTool(self.toolZoomOut)

  def pan(self):
    self.canvas.setMapTool(self.toolPan)

w = MyWnd(iface.activeLayer())
w.show()

No idea how to provide a download option within this window.

1
  • @KadirŞahbaz using QGIS 3.8.Thanks for ur reply. I have changed the import now.
    – Codee
    Jun 10, 2020 at 6:42

1 Answer 1

4

Add the following lines to save the map as image. This is a minimal solution.

Add these lines to __init__ method:

self.actionSaveAsImage = QAction("Save As Image", self)
self.actionSaveAsImage.triggered.connect(self.saveAsImage)
self.toolbar.addAction(self.actionSaveAsImage)

And add this as a new method to the class: (change image path)

def saveAsImage(self):
  self.canvas.saveAsImage("/path/to/image.png")

enter image description here

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.