I am very new to GIS in general and even more to QGis. I have a pretty simple task which is to import all shapefiles in one folder, style them and finally export them.
I have wrote python code that does it one by one just well from the console but when I try to launch it from a pyton class, I do not obtain the shapefile layer printed as I did from the console. Only the elements such as the legend, label appear and a big "Map will be printed here" !
I guess it is because I'm not dealing explicitly with the shapefile I just imported but I didn't find examples doing so on the documentation...
Here is my class so far :
from glob import glob from os import path from qgis.core import * from qgis.gui import * from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtXml import * import PyQt4 class Loader: def __init__(self, iface): """Initialize using the qgis.utils.iface object passed from the console. """ self.iface = iface def load_shapefiles(self, shp_path): """Load all shapefiles found in shp_path""" print "Loading shapes from %s" % path.join(shp_path, "*.shp") shps = glob(path.join(shp_path, "*.shp")) for shp in shps: (shpdir, shpfile) = path.split(shp) layer = self.iface.addVectorLayer(shp, shpfile, 'ogr' ) layer.loadNamedStyle('C:\FOLDER\USER\shape\\shapestyle.qml') #Create composition mapRenderer = self.iface.mapCanvas().mapRenderer() c = QgsComposition(mapRenderer) c.add x, y = 0, 0 w, h = c.paperWidth(), c.paperHeight() composerMap = QgsComposerMap(c, x,y,w,h) c.addItem(composerMap) composerLabel = QgsComposerLabel(c) composerLabel.setText("Hello world") composerLabel.adjustSizeToText() c.addItem(composerLabel) legend = QgsComposerLegend(c) legend.model().setLayerSet(mapRenderer.layerSet()) c.addItem(legend) item = QgsComposerScaleBar(c) item.setStyle('Numeric') # optionally modify the style item.setComposerMap(composerMap) item.applyDefaultSize() c.addItem(item) composerLabel.setItemPosition(20,10, 100, 30) dpi = c.printResolution() dpmm = dpi / 25.4 width = int(dpmm * c.paperWidth()) height = int(dpmm * c.paperHeight()) # create output image and initialize it image = PyQt4.QtGui.QImage(PyQt4.QtCore.QSize(width, height), PyQt4.QtGui.QImage.Format_ARGB32) image.setDotsPerMeterX(dpmm * 1000) image.setDotsPerMeterY(dpmm * 1000) color = PyQt4.QtGui.QColor(155, 155, 155) image.fill(color.rgb()) # render the composition imagePainter = QPainter(image) sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight()) targetArea = QRectF(0, 0, width, height) c.render(imagePainter, targetArea, sourceArea) imagePainter.end() image.save("C:\FOLDER\USER\\outfromscript.png", "png")