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?
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.layerY.dataProvider().addAttributes(layerX.fields())
?[field.type() for field in layerX.fields()]