[Qgis-user] Python script to iterate through attributes and then refresh the canvas - doesn't show any map....

Frank van Baar frank at van-baar.com
Tue Nov 4 00:14:57 PST 2014


Hi,

Am completely stuck with a QGIS project in Python and tried everything but nothing seems to work. The python script does work as such BUT the canvas never shows the map and therefor the exported maps are empty…. 

What I’m trying to achieve:
*	Create a Python script that iterates through a series of ca. 2500 polygons based on attribute value, zoom to layer extend and save the canvas for each attribute as an image file.
*	I then use the image files in other documents

The issue is that while manually I get the canvas to reload and display the map, this doesn’t happen when running the python script. Have tried couple of ways: 
1.	Don’t load the project each time and just change the filter
2.	Add sleep timers to give the canvas time to refresh etc.
3.	Tried different QGIS versions (2.2, 2.4 & 2.6 on Win 64x)

But all to no avail…. Hope somebody’s got a great idea how to solve it.

Regards,

Frank

Python code:

# File location & specifications 

PROJECTPATH = 'C:/Users/Frank/Documents /Targetting/Kaarten/'
PROJECTFILE = 'C:/Users/Frank/Documents /Targetting/TargettingkaartV26qgs.qgs'
EXTSNAPSHOTS = '.jpg'
EXTSNAPSHOTS2 = '.png'
SUFFIX = '65Plus_v1'

last_id = 1

while last_id < 5:

	# Clear map canvas
	QgsMapLayerRegistry.instance().removeAllMapLayers()
	qgis.utils.iface.mapCanvas().refresh()
	
	# Open QGIS project
	QgsProject.instance().setFileName(PROJECTFILE)
	QgsProject.instance().read()
	qgis.utils.iface.mapCanvas().refresh()

	time.sleep(30)	

	canvas = qgis.utils.iface.mapCanvas()
	acl = canvas.layer(0)
	qgis.utils.iface.mapCanvas().layer(0).selectAll()

	selection = 'RijNo = ' + str(last_id) 
	
	acl.setSubsetString( selection )
	acl.triggerRepaint
	canvas.layer(1).triggerRepaint	

	time.sleep(5)	

	qgis.utils.iface.setActiveLayer(acl)

	# Zoom in and out to refresh potential issues with OpenLayer
	canvas.zoomByFactor(3)
	canvas.zoomByFactor(0.5)
	qgis.utils.iface.zoomToActiveLayer()

	qgis.utils.iface.mapCanvas().refresh()
	
	time.sleep(10)

	# Save project

	p=QgsProject.instance()
	p.setFileName(PROJECTFILE)
	p.write()

	# Save content of map canvas as image

	p = str(last_id) + 'kaart_' 

	qgis.utils.iface.mapCanvas().saveAsImage(PROJECTPATH+ p + SUFFIX + EXTSNAPSHOTS)

	last_id = last_id +1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20141104/8063935e/attachment.html>


More information about the Qgis-user mailing list