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?

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Sep 21, 2021 at 10:12
0

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.

answered Sep 21, 2021 at 11:39
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.