Graphics Reference
In-Depth Information
geometries_1 = []
for feature in provider_1.getFeatures(QgsFeatureRequest()):
geometries_1.append(QgsGeometry(feature.geometry()))
This last line of code includes an important feature. Notice that we use the following:
QgsGeometry(feature.geometry())
We use the preceding line instead of the following:
feature.geometry()
This is to get the geometry object to add to the list. In other words, we had to create a new
geometry object based on the feature's existing geometry object. This is a limitation of the
way the QGIS Python wrappers work: the feature.geometry() method returns a
reference to the geometry, but the C++ code doesn't know that you are storing this referen-
ce away in your Python code. So, when the feature is no longer needed, the memory used
by the feature's geometry is also released. If you then try to access that geometry later on,
the entire QGIS system will crash. To get around this, we make a copy of the geometry so
that we can refer to it even after the feature's memory has been released.
Now that we've loaded our first set of geometries into memory, let's do the same for the
second shapefile:
filename_2 = QFileDialog.getOpenFileName(iface.mainWindow(),
"Second Shapefile",
"~", "*.shp")
if not filename_2:
return
provider_2 = registry.provider("ogr", filename_2)
geometries_2 = []
for feature in provider_2.getFeatures(QgsFeatureRequest()):
geometries_2.append(QgsGeometry(feature.geometry()))
With the two sets of geometries loaded into memory, we're ready to start subtracting one
from the other. However, to make this process more efficient, we will combine the geo-
metries from the second shapefile into one large geometry, which we can then subtract all
Search WWH ::




Custom Search