1

I try to add all the fields of layer X to layer Y. This is my code:

layerX = QgsProject.instance().mapLayersByName("layername1")    
layerY = QgsProject.instance().mapLayersByName("layername2") 

#read field name and type of layerX
fields = [ field.name() for field in layerX.fields() ] #list of all fields
fieldtype = [ field.typeName() for field in layerX.fields() ] #list of all fieldtypes

#add fields to layerY
i = 0
for f in fields:

####### Not part of my question from here....
#it's only about breaking (because I don't take field[0] which is the ID) and changing "Integer" to "Int"
      
    i = i + 1
    laenge = len(fields)
    if i == laenge: 
        break
    feldname = fields[i]
    if fieldtype[i] == "Integer":
        feldtyp = "Int"
    else:
        feldtyp = fieldtype[i]
####### Not part of my question .... to here

    qvaria = "QVariant."+feldtyp
    layerY.dataProvider().addAttributes([QgsField(feldname, QVariant.String)])  #WORKS
    layerY.dataProvider().addAttributes([QgsField(feldname, qvaria)])  #DOES NOT WORK 

It works perfectly if I type QVariant.String or QVariant.Int in the last function. If I autogenerate the same statement (using qvaria instead of QVariant.String), it returns the following error:

QgsField(): arguments did not match any overloaded call: #overload 1: argument 2 has unexpected type 'str' #overload 2: argument 1 has unexpected type 'str'

Do you know how I can make my script run? Is there an easier way to add all the fields from one to another layer?

8
  • 1
    qvaria is a vairable containing a string, QVariant.String is a type constant that QPygis understands - they are very different so it will never work this way.
    – Ian Turton
    Commented Sep 21, 2021 at 10:20
  • Why not layerY.dataProvider().addAttributes(layerX.fields()) ? Commented Sep 21, 2021 at 10:36
  • @J.Monticolo: I don't know. When I enter this code, it says "False". Maybe I have to make sure, it doesn't want to generate an other ID?
    – Motti
    Commented Sep 21, 2021 at 10:46
  • @IanTurton: Thanks for the clarification. I just hoped that it would read the string and since it is exactly the same as if I enter it manually, it would work?
    – Motti
    Commented Sep 21, 2021 at 10:48
  • If you want types : [field.type() for field in layerX.fields()] Commented Sep 21, 2021 at 10:49

1 Answer 1

0
layerX = QgsProject.instance().mapLayersByName("layername1")    
layerY = QgsProject.instance().mapLayersByName("layername2") 
layerY.dataProvider().addAttributes([field for field in layerX.fields() if field.name() not in ["fid"]])

No iteration needed.

1
  • 2
    Don't forget layerY.updateFields() in the end. Commented Sep 21, 2021 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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