Created
February 20, 2019 13:42
-
-
Save thbaumann/bbba7640cf98ab09dc9bb6018011f05e to your computer and use it in GitHub Desktop.
examples for pyqgis common functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Examples for some pyqgis common functions. | |
Some may be outdated as things can be done easier in qgis3 now but they should just be an example | |
for some functions that were use to make life easier during the development of QGIS plugins: | |
examples from https://github.com/boundlessgeo/lib-qgis-commons/blob/master/qgiscommons2/layers.py | |
def load_layer(filename, name = None): | |
''' | |
Tries to load a layer from the given file | |
:param filename: the path to the file to load. | |
:param name: the name to use for adding the layer to the current project. | |
If not passed or None, it will use the filename basename | |
''' | |
name = name or os.path.splitext(os.path.basename(filename))[0] | |
qgslayer = QgsVectorLayer(filename, name, 'ogr') | |
if not qgslayer.isValid(): | |
qgslayer = QgsRasterLayer(filename, name) | |
if not qgslayer.isValid(): | |
raise RuntimeError('Could not load layer: ' + unicode(filename)) | |
return qgslayer | |
def newVectorLayer(filename, fields, geometryType, crs, encoding="utf-8"): | |
''' | |
Creates a new vector layer | |
:param filename: The filename to store the file. The extensions determines the type of file. | |
If extension is not among the supported ones, a shapefile will be created and the file will | |
get an added '.shp' to its path. | |
If the filename is None, a memory layer will be created | |
:param fields: the fields to add to the layer. Accepts a QgsFields object or a list of tuples (field_name, field_type) | |
Accepted field types are basic Python types str, float, int and bool | |
:param geometryType: The type of geometry of the layer to create. | |
:param crs: The crs of the layer to create. Accepts a QgsCoordinateSystem object or a string with the CRS authId. | |
:param encoding: The layer encoding | |
''' | |
if isinstance(crs, basestring): | |
crs = QgsCoordinateReferenceSystem(crs) | |
if filename is None: | |
uri = GEOM_TYPE_MAP[geometryType] | |
if crs.isValid(): | |
uri += '?crs=' + crs.authid() + '&' | |
fieldsdesc = ['field=' + f for f in fields] | |
fieldsstring = '&'.join(fieldsdesc) | |
uri += fieldsstring | |
layer = QgsVectorLayer(uri, "mem_layer", 'memory') | |
else: | |
formats = QgsVectorFileWriter.supportedFiltersAndFormats() | |
OGRCodes = {} | |
for (key, value) in formats.items(): | |
extension = unicode(key) | |
extension = extension[extension.find('*.') + 2:] | |
extension = extension[:extension.find(' ')] | |
OGRCodes[extension] = value | |
extension = os.path.splitext(filename)[1][1:] | |
if extension not in OGRCodes: | |
extension = 'shp' | |
filename = filename + '.shp' | |
if isinstance(fields, QgsFields): | |
qgsfields = fields | |
else: | |
qgsfields = QgsFields() | |
for field in fields: | |
qgsfields.append(_toQgsField(field)) | |
QgsVectorFileWriter(filename, encoding, qgsfields, | |
geometryType, crs, OGRCodes[extension]) | |
layer = QgsVectorLayer(filename, os.path.basename(filename), 'ogr') | |
return layer | |
def layerFromName(name): | |
''' | |
Returns the layer from the current project with the passed name | |
Raises WrongLayerNameException if no layer with that name is found | |
If several layers with that name exist, only the first one is returned | |
''' | |
layers =_layerreg.mapLayers().values() | |
for layer in layers: | |
if layer.name() == name: | |
return layer | |
raise WrongLayerNameException() | |
def layerFromSource(source): | |
''' | |
Returns the layer from the current project with the passed source | |
Raises WrongLayerSourceException if no layer with that source is found | |
''' | |
layers =_layerreg.mapLayers().values() | |
for layer in layers: | |
if layer.source() == source: | |
return layer | |
raise WrongLayerSourceException() | |
def loadLayer(filename, name = None, provider=None): | |
''' | |
Tries to load a layer from the given file | |
:param filename: the path to the file to load. | |
:param name: the name to use for adding the layer to the current project. | |
If not passed or None, it will use the filename basename | |
''' | |
name = name or os.path.splitext(os.path.basename(filename))[0] | |
if provider != 'gdal': # QGIS3 crashes if opening a raster as vector ... this needs further investigations | |
qgslayer = QgsVectorLayer(filename, name, provider or "ogr") | |
if provider == 'gdal' or not qgslayer.isValid(): | |
qgslayer = QgsRasterLayer(filename, name, provider or "gdal") | |
if not qgslayer.isValid(): | |
raise RuntimeError('Could not load layer: ' + unicode(filename)) | |
return qgslayer | |
def loadLayerNoCrsDialog(filename, name=None, provider=None): | |
''' | |
Tries to load a layer from the given file | |
Same as the loadLayer method, but it does not ask for CRS, regardless of current | |
configuration in QGIS settings | |
''' | |
settings = QSettings() | |
prjSetting = settings.value('/Projections/defaultBehaviour') | |
settings.setValue('/Projections/defaultBehaviour', '') | |
# QGIS3: | |
prjSetting3 = settings.value('/Projections/defaultBehavior') | |
settings.setValue('/Projections/defaultBehavior', '') | |
layer = loadLayer(filename, name, provider) | |
settings.setValue('/Projections/defaultBehaviour', prjSetting) | |
settings.setValue('/Projections/defaultBehavior', prjSetting3) | |
return layer | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment