I want to develop "Print lay out functionality", but in output system is giving me whole image, I want to print only selected polygon. Also it is not displaying label names on print image.

Please suggest some way.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time
l = iface.activeLayer()

for a in l.getFeatures():
     attrs = {16: 1}
     l.dataProvider().changeAttributeValues({a.id(): attrs})
     img = QImage(QSize(1280, 1024), QImage.Format_ARGB32_Premultiplied)
     # set image's background color
     color = QColor(255, 255, 255)
     # create painter
     p = QPainter()
     render = QgsMapRenderer()
     palyr = QgsPalLayerSettings()
     lst = [l.id()]
     # set extent
     rect = QgsRectangle(render.fullExtent())
     render.setOutputSize(img.size(), img.logicalDpiX())
     # save image
     img.save("C:/example/Ashwin/%s.jpg" % a['CHALTA_NO'],"jpg")
     attrs = {16: 0}
     l.dataProvider().changeAttributeValues({a.id(): attrs})

enter image description here

  • I note that you used rect = QgsRectangle(render.fullExtent()), this uses the entire area. You could use the extent of selection
    – luca76
    Dec 17, 2015 at 9:37
  • when i am use rect = QgsRectangle(render.extent ()), it has giving me blank image. Dec 17, 2015 at 9:48
  • Is your QGIS updated to last version?
    – luca76
    Dec 17, 2015 at 10:06

1 Answer 1


Hint: for each feature, use the QgsFeature().geometry().boundingBox() to achieve the rectangle. In your case, is a.geometry().boundingBox() and it returns a QgsRectangle() object

rect = a.geometry().boundingBox()
  • Thanks for the help friend. I got my solution .Now the only issue is that in image I am not getting the labels, I have on polygon. Please help in that too Please see above attached screenshots here I need labels Dec 17, 2015 at 10:17
  • Is your QGIS updated? Last version is 2.12.1
    – luca76
    Dec 17, 2015 at 13:21
  • I have updated QGIS it's version 2.12.1-Lyon but it was making same polygon image it can not show length of polygon line and polygon Sr. No on label. for show label on image required any special code or not. Dec 18, 2015 at 5:49
  • Sorry for my huge late in response. I think that your code isn't correct. Have you seen the example from: gis.stackexchange.com/questions/84723/…
    – luca76
    Dec 21, 2015 at 13:59

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.