Saturday, 25 July 2015

pyqgis - How to display a picture in QGIS custom form?


I'd like to integrate an UI file as a form in QGIS 2.8. The UI file is created in QT Designer. One of the attributes in the attribute table is a filepath to an image. I'd like to display the picture in the form instead of the filepath. I created lineEdits for each attribute and named them properly, so everything works well, except for the picture.


I load all the layers from my Qgis plugin and I set "Photo" as an EditType for that attribute in the script (You can find it also in layer Properties/Fields). So when I choose "Autogenerate" form, the picture is displayed correctly.


Could anyone give me a hint how could I make the form work correctly?



Answer



After hours of trying I found a solution. It was inspired by this post: http://nathanw.net/2011/09/05/qgis-tips-custom-feature-forms-with-python-logic/


It's not possible to link the attribute from the table with UI file directly. To display a photo in a custom form, the user needs an addtitional python script. Let's call it startForm.py . Its content is as follows:



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

fotoField = None
myDialog = None
layerField=None
objectField=None

def formOpen(dialog,layerid,featureid):
global myDialog

myDialog = dialog
global nameField, layerField, objectField
attr=featureid.attributes()
fotoField = dialog.findChild(QLabel,"Foto")
fotoPath=attr[5] ##the file path to the image is stored right here
fotoField.setPixmap(QPixmap(fotoPath))
layerField=dialog.findChild(QLabel,"label_2")
objectField=dialog.findChild(QLabel,"label_3")
layerField.setText(layerid.name())
objectField.setText(str(featureid.id()))


The script displays a picture in the form, as well as it changes the layer name and the feature id. I load all my layers from a plugin window and I add those 2 lines to the code, so that each layer is already linked with the form:


##A piece of my plugin code; section: insert layers
alayer=iface.activeLayer()
editForm=self.plugin_dir+"\prForma.ui"
alayer.setEditForm(editForm)
alayer.setEditFormInit("startForm.formOpen")

In this case, the UI file and the startForm.py should be stored in the plugin directory.


The result:



enter image description here


Good luck!


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...