0

I'm trying to add multiple fields to a geopackage layer and set their aliases at the same time. It is working on a temp layer but not on the geopackage, why?

lyr = iface.activeLayer()
p = lyr.dataProvider()
fl =    [['grtr_spr_t',QVariant.Int,'test'], #name, type, alias
        ['grtr_spr_g',QVariant.Int, 'test2'],
        ['grtr_spr_l',QVariant.Int, 'test3']]

fieldlist = [QgsField(f[0], f[1]) for f in fl] #Create a list of QgsFields

for e, data in enumerate(fl):
    fieldlist[e].setAlias(data[2]) #Set the aliases of them

#[f.alias() for f in fieldlist]
#['test', 'test2', 'test3'] #They are set

p.addAttributes(fieldlist)
lyr.updateFields()

enter image description here

7
  • At least the method is supported also for GeoPackage layers because it is possible to set the alias manually from the UI as in gis.stackexchange.com/questions/315979/….
    – user30184
    Commented Mar 17, 2022 at 10:19
  • Yes I have also managed to set it manually. Maybe my QGIS or geopackage is broken
    – Bera
    Commented Mar 17, 2022 at 10:20
  • If you can set alias to the same geopackage manually then how could it be broken? And as far as I understand the alias is not even stored into GeoPackage data file.
    – user30184
    Commented Mar 17, 2022 at 10:26
  • Is the code working for you on a gpkg?
    – Bera
    Commented Mar 17, 2022 at 11:11
  • 1
    No, it does not. But I can add an alias by continuing with lyr.setFieldAlias(1,'test') and then I see lyr.attributeAliases() {'fid': '', 'grtr_spr_t': 'test'}. "test" shows also when I open the attribute table from TOC.
    – user30184
    Commented Mar 17, 2022 at 11:42

1 Answer 1

3

I got it to work with:

layer = QgsProject.instance().mapLayersByName('startpunkt')[0]
p = layer.dataProvider()

fieldlist =     [["grtrsprt", "P", QVariant.Int],
                 ["grtrsprg", "S", QVariant.Int],
                 ["grtrsprl", "D", QVariant.Int],
                 ["grtrgrpt", "P", QVariant.Int],
                 ["grtrgrpg", "S", QVariant.Int],
                 ["grtrgrpl", "D", QVariant.Int]]

#Add the fields
newfieldlist = [QgsField(f[0], f[2]) for f in fieldlist]
p.addAttributes(faltlista)
layer.updateFields()

#Set the aliases
fieldindexes = [[layer.fields().indexFromName(f[0]), f[1]] for f in fieldlist] #List of lists of field index and alias
[layer.setFieldAlias(i[0], i[1]) for i in fieldindexes]

enter image description here

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.