PyQGIS – Adding All Fields of One Layer to Another

fields-attributeslayerspyqgis

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?

Best Answer

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.

Related Question