QGIS 3.24.0. I am adding a field to my attribute table using PyQGIS and populating the rows with a URL. The layer in question is a GeoPackage Point layer.
The attribute is added to the dataProvider and is populated as intended, but the field does not show in the attribute table until I click the Reload the table button.
How do I reload the table using PyQGIS?
I have tried lyr.dataProvider().reloadData()
and lyr.dataProvider().forceReload()
(found in a comment in this answer). But the underlying data in the provider is correct and these have no effect on the attribute table.
p = QgsProject.instance()
lyr = QgsVectorLayer(r'path_to_my_gpkg\data.gpkg|layername=query_point', 'query_point')
# get the features
feats = list(lyr.getFeatures())
# create the field if it does not yet exist
field_name = 'url'
if field_name not in lyr.fields().names():
lyr.dataProvider().addAttributes([QgsField(field_name, QVariant.String)])
lyr.updateFields()
# lyr.commitChanges() # no effect
# lyr.dataProvider().forceReload() # no effect
# get the field index of the new field
fields = lyr.fields()
idx = fields.indexFromName(field_name)
for f in feats:
url = 'my/pseudo/url'
lyr.startEditing()
# update the feature attribute at the index of the new field
lyr.changeAttributeValue(f.id(), idx, url)
# lyr.updateFeature(f) # no effect
lyr.commitChanges()
# lyr.dataProvider().reloadData() # no effect
After some experimentation:
Adding iface.showAttributeTable(lyr)
to the last line of the script opens a new instance of the attribute table with the field showing. Despite this, an attribute table opened via right-clicking the layer name still only shows 2 fields until it is reloaded using the button.