[Qgis-user] Setting configuration of a field in a vector layer
Roland Berger
roland.berger at steinerpartner.com
Thu Aug 1 08:09:17 PDT 2024
Hi
I try to set the configuration for a vector layer with python.
Below is one of the many ways I tried to do it.
Now I'm of out of ideas (chatgpt, intellij ai assistent and google as
well) and would be thankful for a working example.
Thanks Roland
Code you can use in a Python Console Editor. First it creates a layer to
use for the test and then tries to set the field configuration.
# =================
# Setup Layer with field
# =================
# Create a vector layer
layer = QgsVectorLayer("Point?crs=EPSG:4326", "MyLayer", "memory")
if not layer.isValid():
print("Failed to create the layer!")
sys.exit(1)
# Add fields to the layer
layer_data_provider = layer.dataProvider()
layer_data_provider.addAttributes([QgsField("field1", QVariant.String)])
layer.updateFields()
# Add a feature to the layer
feature = QgsFeature(layer.fields())
feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0, 0)))
feature.setAttribute("field1", "value1")
layer_data_provider.addFeature(feature)
layer.updateExtents()
# Add the layer to the project
project = QgsProject.instance()
project.addMapLayer(layer)
# =================
# Try to set field configuration
# =================
layer.startEditing()
for field in layer.fields():
config_flags = field.configurationFlags()
config_flags |= Qgis.FieldConfigurationFlag.HideFromWfs
field.setConfigurationFlags(config_flags)
#layer.updateFields()
layer.commitChanges()
More information about the QGIS-User
mailing list