11

I need an invalid layer to test a plugin in QGIS. In the plugin window, I select a layer from combobox. So, the invalid layer should be in Layers panel. I google for a while but I cannot find a way to generate an invalid vector layer.

How can I generate one so that layer.isValid() returns False?

8
  • Did you try self crossing lines, polygons? See also here (at the bottom of the paragraph): docs.qgis.org/3.10/en/docs/user_manual/plugins/core_plugins/…
    – Babel
    Dec 18 '20 at 12:59
  • @babel, Doesn't it create an invalid geometry instead of an invalid layer? Dec 18 '20 at 13:01
  • OK, you're probably right. Could you just create any kind of geopackage, than open it in a text editor, add or delete a few characters, thus making it invalid? Not sure if that is what you want.
    – Babel
    Dec 18 '20 at 13:03
  • @babel Thanks for the trick. This method genereate an invalid data. But in this case, I cannot add the data to Layers panel. I've added more information. Dec 18 '20 at 14:12
  • 1
    A good source of "unusual" data can usually be found in the software tests (see the Github repo)
    – JGH
    Dec 18 '20 at 15:21
13
  • Providing an invalid path makes it invalid: layer = QgsVectorLayer("zxcxzcxc/home/bera/GIS/Data/testdata/ak_riks.shp", "testlayer_shp", "ogr")
  • Or a providerlib that doesnt exist: layer = QgsVectorLayer("/home/bera/GIS/Data/testdata/ak_riks.shp", "testlayer_shp", "O G R"), it should be "ogr"

Then add layer to the project:

QgsProject.instance().addMapLayer(layer)

enter image description here

1
  • 3
    Nice and simple answer! Dec 23 '20 at 1:14

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.