2

I am working with a non-geometric table in QGIS and I'm trying to streamline the process of adding new entries to this table by creating a custom button in the QGIS toolbar. My goal is for this button to switch the "Addresses" layer to edit mode and open the attribute form for adding a new feature, all without the need for any geometry since it's an attribute-only table.

Here's what I have tried so far:

from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QIcon

def add_address():
    layer_name = "Adressen"
    layer = QgsProject.instance().mapLayersByName(layer_name)[0]

    if not layer.isEditable():
        layer.startEditing()

    # This is where I'm stuck. 
    # I need to open the attribute form for a new entry in a non-geometric layer.

# Create an action for the toolbar
action = QAction(QIcon(""), "Add Address", iface.mainWindow())
action.triggered.connect(add_address)

# Add the action to the toolbar
iface.addToolBarIcon(action)

When I click the button, I want it to open the attribute form for a new record in my "Addresses" table. I understand that iface.actionAddFeature().trigger() won't work for non-geometric layers since it's designed for layers with geometry.

Can you guide me on how to open the attribute form for a new entry in a table without associated geometry?

1
  • 1
    iface.actionAddFeature().trigger() does trigger the addition of a new "record" to a geometry-less table fine for me. Commented Nov 3, 2023 at 16:16

1 Answer 1

1

Hope this helps:

from qgis.core import QgsVectorLayerUtils

layer=iface.activeLayer()
print(layer.name(), layer.isSpatial())
if not layer.isEditable():
    layer.startEditing()
feat = QgsVectorLayerUtils.createFeature(layer)#init with default values!
iface.openFeatureForm(layer, feat)

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.