How to display a picture in QGIS custom form?

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!


The solution which does not require python is

In QtDesigner

  1. Add a new QWidget (or any other widget which serves as a container) and in the properties set the objectName to match the field's name. (I.e. If the field name is photo call it photo)
  2. Put a new QLabel or QWebView inside the container. If there are multiple QLabels inside you can specify the correct one with the objectName PhotoLabel.

In QGIS

  1. Configure the widget in the layer properties and set "Photo" as type