4

In QGIS 3.16.5-Hannover, with pyqgis I wan't to get the provider name of a selected layer. I need to know if it's an ESRI Shapefile layer or a POSTGIS layer for example.

Information

I don't see how to get this value in QgsProviderRegistry, or in QgsVectorDataProvider.

I try this :

# Get the name of a selected layer from a combo box
selectedLayerName = self.mMapLayerComboBox.currentText()
layer = QgsProject.instance().mapLayersByName(selectedLayerName)[0]

# Could it be something like this ?
layerProvider = layer.getProvider()

Is there a way with pyqgis to know the provider of a selected vector layer ? (like metadata informations)

2
  • For a QgsVectorLayer, that is indeed the way to get the provider. You add features to the provider to put them in the layer. – wingnut Apr 15 at 8:13
  • And how to get the source type of a vector layer with PyQGIS ? (ESRI Shapefile, PostGIS...) – GeoGyro Apr 15 at 8:16
6

To get the information (storage) which you have highlighted in your screenshot you could use:

selectedLayerName = self.mMapLayerComboBox.currentText()
layer = QgsProject.instance().mapLayersByName(selectedLayerName)[0]
layerProvider = layer.dataProvider()
layerStorage = layerProvider.storageType()
print(layerStorage)

The storageType() method, according to the docs:

Returns the permanent storage type for this layer as a friendly name.

So you will get values like:

"GPKG"

"ESRI Shapefile"

"MapInfo File"

2
  • 1
    storageType(), cool! Should have a deeper look in the docs next time :-) – Jochen Schwarze Apr 15 at 8:53
  • 1
    Great answer, exactly what I expected. – GeoGyro Apr 15 at 9:17
4

For the selected Layer in the Layer tree:

my_lyr = iface.activeLayer()

For your combo-Box:

my_lyr = mMapLayerComboBox.currentLayer()

Get the data provider:

dp = my_lyr.dataProvider()

Get the provider name:

name = dp.name()

Will return something like ogr, wms, postgres, ...

For deeper insights I recommend the data source specification:

uri = dp.uri()

Will give you e.g.

<QgsDataSourceUri: crs='EPSG:3857&format&type=xyz&url=http://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0'> (wms) or

<QgsDataSourceUri: /home/jxxxxx/Dokumente/QGIS/.../.../my_document.ods|layername='my layer'> (ogr)

2
  • That's it. In my example I get ogr for ESRI Shapefiles or postgres values for PostgreSQL/PostGIS database layers. – GeoGyro Apr 15 at 8:30
  • @Ben W's answer solves your issue better than mine – Jochen Schwarze Apr 15 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.