0

I have a kind of "vector catalog" in a GPKG. It's different rectangles with an attribute called "name of the layer".

In the same GPKG, I have all the different layers.

I'm trying to build an action in my vector catalog, so when I click on the rectangle I want, it loads the corresponding layer in QGIS.

I found some questions about loading raster, but I wasn't able to do something like that for vectors.

Is it possible?

1 Answer 1

2

You can find below solution to do the job

The full code is the following

from qgis.core import (
    QgsVectorLayer
)
# Change to your own GPKG path
path_to_gpkg = "path/to/your/own.gpkg"
# Replace [%layer_name%] with [%yourcolumnwithgpkglayername%]
gpkg_layer = path_to_gpkg + "|layername=[%layer_name%]"
vlayer = QgsVectorLayer(gpkg_layer, "[%layer_name%]", "ogr")
if not vlayer.isValid():
    print("Layer failed to load!")
else:
    QgsProject.instance().addMapLayer(vlayer)

Ive made a screen capture to illustrate the action

enter image description here

2
  • I have done what you said, but I have a warning: "2021-03-30T15:28:30 WARNING Impossible de trouver la couche [%nom du layer%].()" which means QGIS can't find the layer... Are you sure of this line: gpkg_layer = path_to_gpkg + "|layername=[%layer_name%]" ? Cause I think it handle it as a string, not as an attribute!
    – katagena
    Commented Mar 30, 2021 at 13:32
  • I found the error... I can't use an attribute with "special" name (I had some space)!
    – katagena
    Commented Mar 30, 2021 at 13:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.