How to change form content dynamically in QGIS 3.6

QGIS can do that without any Python code as well.

The following excerpt is from the QField documentation.

Groups can be hidden based on an expression. This is useful when certain attributes are only required under certain conditions. As an example imagine mapping trees. Some of them might have a disease and you have a list of possible diseases. To not clutter the form with many fields, make a group and configure a visibility expression for a group “diseases”. Add a field “disease” with a checkbox. Only when the checkbox is checked, the list of diseases will be available to the user.

The following configuration interface shows up if using the drag and drop designer and double clicking a group.

enter image description here


The following works:

from PyQt5.QtWidgets import QLineEdit, QWidget

def my_form_open(dialog, layer, feature):
    geom = feature.geometry()
    control = dialog.findChild(QLineEdit, "id") #works with QWidget as well
    control.hide()

But note, that the label does not hide, which makes the dialog look little weird.

I tried to access and hide the label via

    label = dialog.findChild(QLabel, "id")
    label.hide()

but this does not work for some reason.

(If I figure this out I'll update my answer accordingly...)


In the QGIS-Function editor (QGIS 3.8) it`s possible to create an own function, e.g.:

from qgis.PyQt.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from qgis.PyQt.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtWidgets import QTableView, QApplication
import sys
from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def datenbank(uebergabe,feature, parent):
    db = QSqlDatabase.addDatabase("QOCISPATIAL")
    db.setPort(1521);
    db.setHostName("stadt-bbbbb")
    db.setDatabaseName("cccc")
    db.setUserName("ddddddd")
    db.setPassword("eeee")
    if not db.open():
        return("wrong")
    #else:
        #return("true")

    queryx = QSqlQuery(db)
    queryx = db.exec_('SELECT output_z from vvvvvv where ww_section.fid_aw_von='+str(uebergabe)+' or ww_section.fid_aw_bis='+str(uebergabe))

    result2 = []
    i=0
    html=""
    while queryx.next():
        #return("super")
        record = queryx.record()
        result2.append(record.value(0))
        html+="<input type=text id="+str(i)+" value="
        html+=str(result2[i])
        html+=">"
        html+="</br>"
        i=i+1
    db.close()
    return (html)

This will put out dynamically html-code (with values) within the QGIS-form.

Of course that function must be implemented via the drag-and-drop form editor as a html-element in the form, like:

<script>document.write(expression.evaluate("datenbank( \"FID\" )"));</script>