I'm still a newbie at Python and I'm having issues selecting and loading polygons intersecting others with PyQGIS.
I managed to use PyQGIS to achieve that operation with shapefiles stored in my laptop but I haven't found a solution to proceed the same treatment on shapefiles stored in PostGIS.
This is what I came to so far :
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtCore import QSettings
from PyQt4.QtCore import QSettings
from qgis.core import QgsVectorLayer, QgsDataSourceURI
import processing
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "name of my database", "my user name", "my password")
uri.setDataSource("database schema", "table name", "geom")
couche = "PM"
layer1 = QgsVectorLayer(uri.uri(), couche, "postgres")
if not layer1.isValid:
print ('Chargement de la couche: echec !')
else:
QgsMapLayerRegistry.instance().addMapLayer(layer1)
uri.setDataSource("database schema", "table name2", "geom")
couche = "batiments"
layer2 = QgsVectorLayer(uri.uri(), couche, "postgres" )
subset_layer2 = processing.runalg('qgis:extractbylocation', layer2,layer1,['intersects'],0.0,None)
uri.setDataSource("rbal", "parcelles", "geom")
couche = "parcelles"
layer3 = QgsVectorLayer(uri.uri(), couche, "postgres" )
subset_layer3 = processing.runalg('qgis:extractbylocation', layer3,layer1,['intersects'],0.0,None)
When I run the code I don't get any error but the treatment is loading forever without returning any results...
EDIT:
With that script I've managed to select all the polygons contained in layer2 that intersect layer1 but I do have to load layer2 to do so. Is there a way to select and load those intersecting polygons without loading the whole layer in the first place ?
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "name of my database", "my user name", "my password")
uri.setDataSource("database schema", "table name", "geom")
couche = "PM"
layer1 = QgsVectorLayer(uri.uri(), couche, "postgres")
if not layer1.isValid:
print ('Chargement de la couche: echec !')
else:
QgsMapLayerRegistry.instance().addMapLayer(layer1)
uri.setDataSource("database schema", "table name2", "geom")
couche = "batiments"
layer2 = QgsVectorLayer(uri.uri(), couche, "postgres" )
if not layer2.isValid:
print ('Chargement de la couche: echec !')
else:
QgsMapLayerRegistry.instance().addMapLayer(layer2)
feats_layer1 = layer1.getFeatures()
for feat in feats_layer1:
geom_layer1 = feat.geometry()
feats_layer2 = layer2.getFeatures()
for feature in feats_layer2:
if feature.geometry().intersects(geom_layer1):
layer2.select(feature.id())
qgis:extractbylocation
but it doesn't workuri = QgsDataSourceURI()
in QGIS 2.14 :/ But do you mean my script works in QGIS 3.16 onceuri = QgsDataSourceURI()
is replaced byuri=QgsDataSourceUri()
?PyQt5
orqgis.PyQt.QtCore
.