1

I want to open the attribute dialog programmatically for a selected feature. I need to achieve the same effect as if the user clicks on the "object identify" action ( CTRL + SHIFT + I). I searched the QGIS API docs for QGIS 3.2 but I was unable to find a solution.

I found the classes QgsAttributeFormInterface and QgsMapToolIdentifyFeature, but I was not able to use them in a useful way. I also tried to trigger the action from the toolbar, but I guess I need some kind of click event with x,y coordinates for this to work.

Does anyone know if you can open the attribute dialog from a plugin programmatically?

Andi

  • Welcome to GIS SE. Please take the tour to learn about our focused Q&A format. For questions involving code, please include your code (formatted with the { } button) and indicate where you are having trouble! – Andy Oct 22 '18 at 18:06
1

The code snippets below provide some basic examples of accessing the feature attribute dialog using the pyqgis api. These work in the Python console (tested in QGIS 3.2.2) but I’m sure you could adapt them to make them work in a plugin.

This first snippet just directly opens the feature attribute form for a specified feature. This works by casting QgsFeatureIterator items to a list then using list indexing to access a feature and calling the openFeatureForm() method, passing a layer and feature object as arguments.

layer = iface.activeLayer()
features = layer.getFeatures()
feature_list = list(f for f in features)
feat = feature_list[0]
iface.openFeatureForm(layer, feat, True)

The second code snippet below makes use of the Identify Features map tool and it’s featureIdentified signal when the user clicks on a feature in the active layer to open the attribute form for that feature. It also changes the cursor style to emulate the native identify features tool.

from qgis.gui import QgsMapToolIdentifyFeature
from PyQt5.QtGui import QCursor

def onFeatureIdentified(feat):
    iface.openFeatureForm(layer, feat, True)

mapTool = None
canvas = iface.mapCanvas()
layer = iface.activeLayer()
mapTool = QgsMapToolIdentifyFeature(canvas)
mapTool.setLayer(layer)
cursor = QCursor()
cursor.setShape(Qt.WhatsThisCursor)
mapTool.setCursor(cursor)
canvas.setMapTool(mapTool)
mapTool.featureIdentified.connect(onFeatureIdentified)

Credit to @Fransisco Raga in this related question.

  • Thank you, the first solution worked perfectly fine for me. Somehow I have not found this method in the API docs. I guess I always searched for a AttributeDialog or similar stuff. – TheGrudge Oct 23 '18 at 11:05
  • You're welcome. Glad it worked for you. – Ben W Oct 23 '18 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.