Skip to content

Instantly share code, notes, and snippets.

@slarosa
Last active November 25, 2020 19:36
Show Gist options
  • Save slarosa/653e6d759cf0d82c2a24dcc499b094e0 to your computer and use it in GitHub Desktop.
Save slarosa/653e6d759cf0d82c2a24dcc499b094e0 to your computer and use it in GitHub Desktop.
'''
QGIS macro to enable selection on referenced geometry layer from
referencing geometryless table in a Project with Relations.
How it works:
1. Enable macros for the QGIS Project
2. Paste this code in Project->Macro
3. Save the Project.
Note: The QGIS project must have relationship between tables.
See https://goo.gl/w4NMZJ on how to create one-to-many relations.
'''
from qgis.PyQt.QtCore import QSettings
from qgis.utils import iface, reloadProjectMacros
from qgis.core import QgsFeatureRequest, QgsProject
from functools import partial
def openProject():
def selectionChanged(rl, fts):
referencingLayer = rl.referencingLayer()
referencedLayer = rl.referencedLayer()
ids = []
request = QgsFeatureRequest().setFilterFids(fts)
for f in referencingLayer.getFeatures(request):
ids.append(rl.getReferencedFeature(f).id())
referencedLayer.selectByIds(ids)
iface.setActiveLayer(referencedLayer)
rM = QgsProject.instance().relationManager()
rls = rM.relations()
for rlid, rl in rls.iteritems():
referencingLayer = rl.referencingLayer()
referencingLayer.selectionChanged.connect(partial(selectionChanged, rl))
def saveProject():
s = QSettings()
s.setValue("qgis/enableMacros", 3)
reloadProjectMacros()
def closeProject():
pass
Copy link

ghost commented Apr 17, 2017

I tried "to replace reloadProjectMacros() with pass", but problem is the same.
This is message on Log panel (Python):
evalString()) error!
Command:
str(sys.path)
Error:
SystemError: NULL object passed to Py_BuildValue

Peraphs qgis-python module is'nt good !? ... Should I try to reinstall it?

@slarosa
Copy link
Author

slarosa commented Apr 18, 2017

@nformica, I managed to test the macro on Ubuntu-16.04 (64bit) QGIS 2.18.6 and has worked fine for me. So, the error you are getting could be a local problem.
Also, you could test if the following code work fine for you in python console:

from qgis.utils import reloadProjectMacros
reloadProjectMacros()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment