6

This question already has an answer here:

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[0] + '.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[0]) or (n2 == Nom[0]) or (n3 == Nom[0]) or (n4 == Nom[0]) or (n5 == Nom[0]) :
        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[0] + '.tif'
mnam2 ='C:/Users/User/.qgis2/Test/Output/' + Nom[0] + '.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)enter image description here

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.

if i rerun the script and i select another village, say "Maratea", this is what i'll find as Maratea.png enter image description here

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

marked as duplicate by Germán Carrillo, whyzar, Mapperz Feb 2 '17 at 20:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • To test, are you getting the desired selected features if you comment out the save image statements? – artwork21 Oct 21 '15 at 12:45
  • Thank you for your answer; Yes, but i see a correct map also if i save images; only saved images show "old" map, not the one with new selection. I'll try to give some more details in a new answer. – Marcello U. Oct 22 '15 at 7:40
  • Have you looked at the Atlas feature of QGIS? This should give you all you need from within the QGIS map composer. – Matthias Kuhn Oct 23 '15 at 9:35
0

I don't understand your problem.

1) You create a text file with the selected features id

layer = iface.activeLayer()
# you select all the features with nom in one of the 5 fields
selection = [f.id() for f in layer.getFeatures() if nom in [f['Comune_1'],f['Comune_2'],f['Comune_3'],f['Comune_4'],f['Comune_5']]]
# then you write in a text file the link field of the selected features
with open(newfile, 'w') as outfile:
    for f in layer.getFeatures():
        if f.id() in selection:
            # the default format is unicode
            outfile.write('%s\n' % (f['link']))

2) After you save the canvas showing the selected features

# select the features
layer.setSelectedFeatures(selection)
canvas.zoomToSelected()
# save the files
canvas.saveAsImage(mnam,None,'TIF')
canvas.saveAsImage(mnam2,None,"PNG")

And it works without problem.

  • Thank you for your answer @gene, i'll try to give some more details in a new answer. – Marcello U. Oct 22 '15 at 7:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.