PyQGIS – Making a Feature Form for Standalone Application

pyqgispyqtqgisstandalone

In QGIS, there is a method named openFeatureForm defined in QgisInterface class. It opens a form that shows value of attributes for a given feature.

layer = iface.activeLayer()
feature = layer.getFeature(0)

iface.openFeatureForm(layer, feature)

This method doesn't work in a standalone PyQGIS application. Because iface is predefined variable that refers QGIS interface.

How can I make a form like that showing the attribute values of a given feature? I also would prefer to filter the attributes.

Best Answer

The following script generates a simple form. You can use it in your standalone PyQGIS application to display attributes for a given feature. You can also specify fields to be displayed (or not to be displayed).


from qgis.PyQt.QtWidgets import *

class FeatureForm(QWidget):
    
    def __init__(self, layer, feature, only=None, exclude=None):                
        super(FeatureForm, self).__init__()
        field_names = layer.fields().names()

        # 'only' parameter is primary. If given, 'exclude' is skipped 
        if only:
            field_names = [f for f in field_names if f in only]
        elif exclude:
            field_names = [f for f in field_names if f not in exclude]
        
        v_layout = QVBoxLayout()
        f_layout = QFormLayout()
        
        for field_name in field_names:
            text_field = QLineEdit()
            text_field.setReadOnly(True)
            text_field.setText(str(feature[field_name]))
            f_layout.addRow(QLabel(field_name), text_field)
        
            self.setLayout(f_layout)

# Sample `layer` and `feature`:
layer = QgsVectorLayer('file_path.shp', "layer_name", "ogr")
feature = layer.getFeature(0) 

Without only and exclude:

form = FeatureForm(layer, feature)
form.show()

enter image description here


With only parameter: Just Type and Area are displayed

form = FeatureForm(layer, feature, only=["Type", "Area"])
form.show()

enter image description here


With exclude parameter: All fields are displayed except of Type and Area

form = FeatureForm(layer, feature, exclude=["Type", "Area"])
form.show()

enter image description here

Related Question