mtl_gis_oo/scrub_layer_class.py

40 lines
1.1 KiB
Python
Raw Normal View History

2024-03-15 11:26:23 -04:00
from qgis.core import *
2024-03-15 12:08:52 -04:00
from qgis.analysis import QgsNativeAlgorithms
2024-03-15 11:26:23 -04:00
class ScrubLayer:
2024-03-15 12:08:52 -04:00
def __init__(self, qgis_path, layer_path, layer_name):
# Set the path to QGIS installation
QgsApplication.setPrefixPath(qgis_path, True)
# Initialize QGIS application
qgs = QgsApplication([], False)
qgs.initQgis()
2024-03-15 11:26:23 -04:00
self.layer_path = layer_path
self.layer_name = layer_name
2024-03-15 12:08:52 -04:00
self.layer = self.load_layer()
2024-03-15 11:26:23 -04:00
2024-03-15 12:08:52 -04:00
def load_layer(self):
the_layer = QgsVectorLayer(self.layer_path, self.layer_name, 'ogr')
2024-03-15 11:26:23 -04:00
if not the_layer.isValid():
2024-03-15 12:08:52 -04:00
raise ValueError(f'Failed to load layer {self.layer_name} from {self.layer_path}')
2024-03-15 11:26:23 -04:00
else:
2024-03-15 12:08:52 -04:00
QgsProject.instance().addMapLayer(the_layer)
return the_layer
@staticmethod
def cleanup():
QgsApplication.exitQgis()
2024-03-15 11:26:23 -04:00
if __name__ == '__main__':
2024-03-15 12:08:52 -04:00
app_path = 'C:/Program Files/QGIS 3.34.1/apps/qgis'
new_path = 'C:/Users/a_adli/PycharmProjects/hydroquebec_archetype_gispy/' \
'data/test_data/mtl_north/test_north_mtl.shp'
2024-03-15 11:26:23 -04:00
data_layer_name = 'mtl_north'
2024-03-15 12:08:52 -04:00
handle_layer = ScrubLayer(app_path, new_path, 'mtl_north')
print(handle_layer.layer.featureCount())