3

I have a set of different layers (and their respective shapefiles) with information of electric lines. All the layers have the same Fields in their Attribute Tables, but contain information about different features. I want to merge only the layers that I choose and save them into a new QgsVectorLayer (Or something similar).

To get all of the layers, I'm using this:

    lyrs = self.iface.legendInterface().layers()

And I want to get something like:

    new_layer=lyrs[1]+lyrs[3]
    new_layer.getFeatures() #Do something else from here, but is irrelevant to the question

(Obviously that last part won't work because "TypeError: unsupported operand type(s) for +: 'QgsVectorLayer' and 'QgsVectorLayer'", but that is the idea of what I need to get)

Some details:

1: I would prefer a method that does not create a new shapefile like "qgis:mergevectorlayers" (The method will be called multiple times, and it would create a lot of unnecesary shapefiles)

4

I guess a Memory Provider would suite your needs as

It does not store data on disk, allowing developers to use it as a fast backend for some temporary layers.

Based on your descriptions and the linked example from the cookbook I created some code. It is not fully tested and maybe you will have to tweak it a little:

lyrs = self.iface.legendInterface().layers()

fields = lyrs[1].pendingFields()

vl = QgsVectorLayer("LineString", "temporary_lines", "memory")
pr = vl.dataProvider()

for f in fields:
  pr.addAttributes([f])

vl.updateFields()

feats1 = lyr[1].getFeatures()
for feature in feats1:
  pr.addFeatures([feature])

feats3 = lyr[3].getFeatures()
for feature in feats3:
  pr.addFeatures([feature])

vl.updateExtents()

# Do something with it
  • Thank you ver much for your answer @bennos . I will accept it as soon as I can test it, but it looks like what I'm looking for. – PabloQG Nov 11 '15 at 1:43

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.