4

I search for a possibility to import WMS-connections to the data source manager with the startup.py in QGIS. I tried the following code, but always get errors:

from qgis.core import QgsOwsConnection
# WMS-URL
url = "https://geodienste.sachsen.de/wms_list_ttsib/guest?"

# Name WMS-Connection
conn_name = "test-layer"

# Add WMS-Connection
QgsOwsConnection.addWmsWcsConnectionSettings(url,conn_name)

I get this error and don't know how to solve it:

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.8\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 9, in <module>
TypeError: QgsOwsConnection.addWmsWcsConnectionSettings(): argument 1 has unexpected type 'str'
1
  • What are the errors?
    – PolyGeo
    Commented Jan 20, 2023 at 9:09

1 Answer 1

4
+50

The OGC web service connections that are configured in the data source manager are stored using the QgsSettings API. This is based on QSettings which provides a way to store application specific settings in a key-value storage. You can read the docs on how that works in detail: https://doc.qt.io/qt-6/qsettings.html#details

All connections are stored under the entries following the pattern /qgis/connections-{service}/{connection_name}. Addressing your example the correct settings key will be /qgis/connections-wms/WMS Sachsen where WMS Sachsen is just a name I chose that will be shown in the list of connections.

from qgis.core import QgsSettings

url = "https://geodienste.sachsen.de/wms_list_ttsib/guest?"
conn_name = 'WMS Sachsen'

key = f'/qgis/connections-wms/{conn_name}/'

settings = QgsSettings()
settings.setValue(key + 'url', url)

# all the additional parameter settings. Change these to your needs.
settings.setValue(key + 'dpi-mode', 7)
settings.setValue(key + 'ignore-get-map-uri', False)
settings.setValue(key + 'ignore-get-feature-info-uri', False)
settings.setValue(key + 'smooth-pixmap-transform', False)
settings.setValue(key + 'ignore-axis-orientation', False)
settings.setValue(key + 'invert-axis-orientation', False)

If you use the code above in a startup.py file, the WMS connection will be available in the data source manager.

One final note on your initial attempt: Although the addWmsWcsConnectionSettings method sounds like it adds a new connection, it actually reads existing connection parameters from QgsSettings and populates a QgsDataSourceUri object. I find the name a bit misleading.

1
  • This is vastly different between QGIS versions. Isn't there a PyQGIS API way to do this without manually trying to find some settings sections and keys? Commented Jun 29, 2023 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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