3

The following code gives an "invalid" layer.

urlWithParams = 'type=xyz&url=https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0'
raster_layer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')
print(raster_layer.isValid()) # False

I guess it can be invalid for many different reasons:

  • online resource is currently not available
  • data is corrupted
  • URL is invalid
  • authentication is required but not provided
  • authentication was rejected by server
  • etc.

I want to ask overall:

  • How can I get information about why a layer is invalid?
  • Is there a log that I should read?
  • Or is it possible to get more information interactively through Python, maybe with a kind of error code that my plugin can act on and then give relevant feedback to the plugin user

Motivation for asking this:

I am trying to add a raster layer with Open Street Maps in pyqgis in a standalone script, but the layer is invalid (QgsRasterLayer is invalid when run as standalone PyQGIS).

Mads Skjern
  • 759
  • 3
  • 15
  • It gives me True and a valid OSM WMS layer when I changed print(raster_layer.isValid()) – Taras Jun 07 '22 at 06:06
  • I made a typo in my post, thanks for correcting, Taras. My test code did not include this typo, and says that it is invalid. – Mads Skjern Jun 07 '22 at 08:02
  • I strongly dislike the way you edited my post (besides the typo) to be an entirely different question. I know how to get and read lots and lots of informaiton about any given layer. But I don't know what makes QGIS conclude that it is invalid. Eg, if data is corrupted, if constraints are violated, if there is no access to the online resource at the moment of calling isInvalid(). Could you please (or should I) revert to the original question? – Mads Skjern Jun 07 '22 at 08:09
  • @Taras, thanks :) I made an additional edit, that makes it more explicit what kind of details I am hoping to get, when a layer is considered invalid. – Mads Skjern Jun 07 '22 at 08:20
  • You (or someone) are welcome to delete these comments, since I guess they are not providing any help for readers. Sincerely. – Mads Skjern Jun 07 '22 at 08:20

1 Answers1

3

Accessing additional details on why a layer might be invalid is possible via the error function.

Copied from docs:

Gets current status error. This error describes some principal problem for which layer cannot work and thus is not valid

Example where I passed a wrong data provider on purpose:

urlWithParams = 'type=xyz&url=https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0'
raster_layer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'W M S')
print(raster_layer.isValid()) # False
print(raster_layer.error().summary()) 
# Cannot instantiate the 'W M S' data provider

Unfortunately error() does not always provide a useful hint. I tried some different cases using an invalid vector layer where error() often results in an empty QgsError object.

CodeBard
  • 3,511
  • 1
  • 7
  • 20