I'm a beginner to Qgis and Python; i need a script (don't need it to be a plugin) to get maps of selected features from a layer satisfying certain conditions; Here is my code:
from qgis.gui import * from PyQt4.QtCore import * from PyQt4.QtGui import * import time fnam ='C:/Users/User/.qgis2/Test/Output/' canvas = qgis.utils.iface.mapCanvas() #print canvas.size() Nom =QInputDialog.getText(None,"Value", "Enter text",0) fnam2 = fnam + Nom + '.txt' #print fnam2 outfile = open (fnam2, 'w') layer = iface.activeLayer() layer.setSelectedFeatures() #provider =layer.dataProvider() selection= for f in layer.getFeatures(): n1 = f['Comune_1'] n2 = f['Comune_2'] n3 = f['Comune_3'] n4 = f['Comune_4'] n5 = f['Comune_5'] if (n1 == Nom) or (n2 == Nom) or (n3 == Nom) or (n4 == Nom) or (n5 == Nom) : selection.append(f.id()) line = '%s\n' % (f['link']) unicode_line = line.encode('utf-8') outfile.write(unicode_line) layer.setSelectedFeatures(selection) #provider.select() outfile.close() mnam ='C:/Users/User/.qgis2/Test/Output/' + Nom + '.tif' mnam2 ='C:/Users/User/.qgis2/Test/Output/' + Nom + '.png' #print mnam canvas.zoomToSelected() canvas.refresh() canvas.update() canvas.saveAsImage(mnam,None,'tif') #time.sleep(3) canvas.saveAsImage(mnam2,None,"PNG") #print 'Finished'
My problem is that saved image(s) show the map at the moment i press "run" button in Python console, not the actual map based on the last selection; i tried to insert a time.sleep() call to delay saving, hoping it could help waiting rendering to complete before saving, but it doesn't work; i also tried recursing the whole process with a for loop, neither working; any tips on what am i doing wrong?
I'll try to explain in a better way:
in this project i have two layers/shapefiles: one shows villages in my region with their boundaries; the second one shows the arrangment of orthophotos in a 1:5000 scale of the territory (img1)
now professionals or village administrators may ask for orthophotos of a specific village;
running my script i wish:
- have a list of orthophotos of that specific village (this works fine with txt file i create);
- give a map showing the arrangement of requested orthophotos as a complementary aid.
Now, if i run the script selecting, say, "Potenza", i eventually can see in Qgis the updated map with desired selection, but saved images show the whole region:(I mean "Potenza.png" is identical to above image while it should be like the one below);
only now i noticed there are selections, so the problem seems to be in zoomToSelected command.
(tif images are identical to png);
(When i'll have a working script selected "rectangles" will show image name, and i won't use inputdialog but i'll get village names from the first shapefile and run it only once for all villages).