0

I have the following Python script for QGIS3, which is supposed to load spatial and non-spatial tables into a new project. Relationships are then to be set and certain links are to be created in the attribute form. Loading the tables works so far, but I cannot access the relationships (as much as if I drag the tables into QGIS by hand. By relationships I mean what is under: Project/Properties/Relations/AddRealation Here the tables are available when added manually, but unfortunately not after running the script.

Why is that?

SCRIPT:

from qgis.core import (
    QgsProject,
    QgsVectorLayer,
    QgsRasterLayer,
    QgsVectorLayerJoinInfo,
    QgsRelation
)

#DATAPATHES
uri = "dbname='XXX' host=XXX estimatedmetadata=true srid=4647 type=Point disableInvalidGeometryHandling='0'"

#OSM
osm_layer = QgsRasterLayer(r"type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png", "OpenStreetMap", "wms")

#DGM
dgm_layer = QgsRasterLayer(r"\\XXX\DGM1_NI_Hoehendaten.tif", "DGM1", "gdal")

#CREATING GROUPS
root = QgsProject.instance().layerTreeRoot()
basegroup = root.insertGroup(0, 'BaseMap')
zuogroup  = root.insertGroup(0, 'ZuordnungsTabellen')
refgroup  = root.insertGroup(0, 'ReferenzTabellen')
maingroup = root.insertGroup(0, 'HauptTabellen')

#MAINTABLE
IEK_EREIGNIS    = QgsVectorLayer(uri_ereignis + " table=\"dbo.IEK_EREIGNIS\" (eGeom)", "IEK_EREIGNIS", "mssql")
maingroup.addLayer(IEK_EREIGNIS)

#REFERENCETABLES
IEK_AKTIVITAETANZEICHEN = QgsVectorLayer(uri + "table=\"dbo.IEK_AKTIVITAETANZEICHEN\" ", "IEK_AKTIVITAETANZEICHEN", "mssql")

IEK_AKTIVITAETSART = QgsVectorLayer(uri + "table=\"dbo.IEK_AKTIVITAETSART\" ", "IEK_AKTIVITAETSART", "mssql")

IEK_ZUO_AKTIVITAETANZEICHEN_EREIGNIS = QgsVectorLayer(uri + "table=\"dbo.IEK_ZUO_AKTIVITAETANZEICHEN_EREIGNIS\" ", "IEK_ZUO_AKTIVITAETANZEICHEN_EREIGNIS", "mssql")


#TO GROUPS
#ReferenzTabellen
refgroup.addLayer(IEK_AKTIVITAETSART)
refgroup.addLayer(IEK_AKTIVITAETANZEICHEN)
zuogroup.addLayer(IEK_ZUO_AKTIVITAETANZEICHEN_EREIGNIS)
#BaseMaps
basegroup.addLayer(dgm_layer)
basegroup.addLayer(osm_layer)

#Zoom DGM1-Layer
iface.mapCanvas().setExtent(dgm_layer.extent())
iface.mapCanvas().refresh()

Now the Layers are loaded and visible, but not accessible in Project/Properties/Relations...

2
  • You are adding layers to the layer tree without adding them first to the project e.g. QgsProject.instance().addMapLayer(IEK_EREIGNIS, False), setting addToLegend argument to False, so you can then add to desired group with your existing code.
    – Ben W
    Commented Aug 1 at 12:31
  • 1
    thanks for the hint about adding it to the project...that worked, I wasn't aware that there was a difference between the project and the LayerTree. Thanks Commented Aug 2 at 13:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.