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
    You added pyqgis-3 tag but you use pyqgis-2. Which version of QGIS do you use? – Kadir Şahbaz Jun 9 at 12:00
  • @KadirŞahbaz using QGIS 3.8.Thanks for ur reply. I have changed the import now. – Codee Jun 10 at 6:42
  • "whatever the zoom level I have chosen". What does it mean? When you export a map as image, the map is normally saved as in map canvas. – Kadir Şahbaz Jun 10 at 8:26
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

| 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.