2

I added 2 layers in qgis using python but only one layer is shown on canvas. After clicking (anywhere on the canvas) both layers are displayed.

layer =  QgsVectorLayer("Point?field=gid:integer","items","memory")

maplayer=QgsVectorLayer("IND_adm1.shp","IND_adm1.shp","ogr")

QgsMapLayerRegistry.instance().addMapLayers([maplayer,layer])
feature = QgsFeature()
feature.setGeometry( QgsGeometry.fromPoint(QgsPoint(X,Y)) )
feature.setAttributes(values)
layer.startEditing()
layer.addFeature(feature, True)
layer.commitChanges()
layers=[]
layers.append(maplayer)
layers.append(layer)
canvas = QgsMapCanvas()
canvas.setLayerSet([QgsMapCanvasLayer(layers[0])])
canvas.setLayerSet([QgsMapCanvasLayer(layers[1])])
canvas.refresh()
canvas.show()

when it run on qgis it will shows only second layer and when i click on canvas it shows both layer how could I avoided this one click and both layer should be displayed directly using python.

  • 1
    Can you please add some minimal code example that demonstrates your issue. – Matthias Kuhn Jan 22 '15 at 9:50
4

If you want to add a vector layer and you use the python console of qgis you can use:

vlayer1 = QgsVectorLayer('poly1.shp','l1', 'ogr')
vlayer2 = QgsVectorLayer('poly2.shp','l2', 'ogr')

#You can add a list of vector layers at the same time
QgsMapLayerRegistry.instance().addMapLayers([vlayer1, vlayer2])

#Probably you also need the refresh function to reload your map canvas
iface.mapCanvas().refresh()

At least in qgis 2.6 python console it is sufficient to execute the addMapLayers function without to refresh the canvas.

But like Matthias Kuhn said, a bit of code would be helpful.

  • i have add one layer from database and one from file path for me this solution is not working. database vector lyaer should be overlay on other one. – ashish Jan 23 '15 at 5:24
0

You have need to add layer.updateExtents() just after layer.commitChanges(). It is necessary if features are added or deleted to the layer as mentioned in the QGIS API Documentation!

Hope this helps!

  • It still require one click then only it shows both layer properly – ashish Jan 27 '15 at 5:15
  • its not working plz tell me any other solution – ashish Jan 27 '15 at 8:32

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.