[GIS] How to add a delete button to feature forms

postgispyqgisqgisqt

I have created some formulars in QTDesigner for capturing and manipulating data in QGIS. The data is stored in a postgis-database.

It would be helpful to have a delete-button in this formulars to delete the open feature. At the moment my formulars only contain the 'OK' and 'Cancel' Button.

How can I add a 'Delete'-Button?


Here my code. It's based on the example in the refered post. The delete() function is the missing part. Can I use something like currentItem,..?

from PyQt4.QtCore import *  
from PyQt4.QtGui import *  

id_flaecheField = None  
id_fotoField = None  
myDialog = None  

def formOpen(dialog,layerid,featureid):  
   global myDialog  
   myDialog = dialog  
   id_fotoField = dialog.findChild(QComboBox,"id_foto")  
   id_flaecheField = dialog.findChild(QComboBox,"id_flaeche")
   buttonDelete= dialog.findChild(QPushButton,"pushButton")
   buttonDelete.clicked.connect(delete)

def delete():
# missing part of the delete function

Best Answer

You will need some python code to accomplish this. Have a look at this post which explains, how you add custom business-logic to your widgets.

You will have to save the layerid and the featureid which you get when the form is created and use these for your operation. Please note, that with this code, the layer has to be manually switched into edit mode. Connecting to the appropriate signals from QgsVectorLayer and toggling the button state accordingly is left as an exercise for the reader ;)

QGIS 2.0

from PyQt4.QtCore import *
from PyQt4.QtGui import *

id_flaecheField = None
id_fotoField = None

myDelToolFeature = None
myDelToolLayer = None

def formOpen(dialog,layer,feature):
    global myDelToolFeature
    global myDelToolLayer

    myDelToolFeature = feature
    myDelToolLayer = layer

    id_fotoField = dialog.findChild(QComboBox,"id_foto")
    id_flaecheField = dialog.findChild(QComboBox,"id_flaeche")
    buttonDelete= dialog.findChild(QPushButton,"pushButton")
    buttonDelete.clicked.connect(delete)

def delete():
    # Delete the feature
    myDelToolLayer.deleteFeature( myDelToolFeature.id() )

QGIS 1.8

from PyQt4.QtCore import *  
from PyQt4.QtGui import *  

from qgis.core import QgsMapLayerRegistry

id_flaecheField = None
id_fotoField = None

myDelToolFeatureId = None
myDelToolLayer = None

def formOpen(dialog,layerid,featureid):  
    global myDelToolFeatureId
    global myDelToolLayer

    myDelToolFeatureId = featureid
    myDelToolLayer = layerid

    id_fotoField = dialog.findChild(QComboBox,"id_foto")
    id_flaecheField = dialog.findChild(QComboBox,"id_flaeche")
    buttonDelete= dialog.findChild(QPushButton,"pushButton")
    buttonDelete.clicked.connect(delete)

def delete():
    # Get the layer from the registry
    layer = QgsMapLayerRegistry.instance().mapLayer( myDelToolLayer )
    # Delete the feature
    layer.deleteFeature( myDelToolFeatureId )