I am trying to create a standalone application using Python 3.7 and QGIS3.6. on Windows 10. I have installed QGIS using the OSGEO4W method, in the 64-bit flavour.

My issue is that when I try to load a layer, it always says that the layer is not valid, as determined by layer.isValid() = False.

current paths are:

pythonpath=C:\OSGeo4W64\apps\qgis\python path=C:\OSGeo4W64\apps\qgis\bin;C:\OSGEO4~1\apps\Python37;C:\OSGEO4~1\apps\Python37\Scripts;C:\OSGEO4~1\apps\Python27\Scripts;C:\OSGEO4~1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\WBem

I have read several answers on this, but none of them have worked for my so far; mostly the answers have been to do with changing setPrefixPath, which I have done in several different ways to no avail. I have also changed the pythonpath, but that did not work either.

What else can I try?

My script:

import os, sys, time, csv
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'c:\osgeo4w64\apps\Qt5\plugins'
os.environ['PATH'] += r';c:\osgeo4w64\apps\qgis\bin;c:\osgeo4w64\apps\Qt5\plugins'


from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from qgis.core import QgsProject
from PyQt5.QtCore import *
from PyQt5.QtGui import *

#   Instantiate the QGIS Application
app = QgsApplication([], False)   # second argument to False disables the GUI

#   Update prefix path
app.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
#print (QgsApplication.showSettings())

#   File to study area (vector)
vector_source = "path/to/inputs StudyArea.shp"

#   Read layer from file
layer = QgsVectorLayer(vector_source, "Vector_Layer", "ogr")

# Test if the file path points to a valid file
print ("File Path points to a file: ", os.path.isfile(vector_source))
#  Test if the layer is valid
print ("Output of layer.isValid(): ", layer.isValid())

I finally found the answer by changing by setting the os.environ['QGIS_PREFIX_PATH']. See @Matt Brauer’s answer to PyQGIS QgsVectorLayer() Loads Invalid Layer in Standalone Python 3 Script

  • How is the path vector_source? Put it with r in front
    – Fran Raga
    May 23 '19 at 19:44
  • @FranRaga vector_source is vector_source = "C:/users/name/otherfolders/shapefile.shp". The result is still the same with an r before the quotation.
    – Perfalcon
    May 24 '19 at 9:50
  • This line doesn't look right - vector_source = "path/to/inputs StudyArea.shp" The layer is invalid because of this. You should double check your code. Look up the parameters for QgsVectorLayer.
    – enolan
    May 24 '19 at 12:04
  • @enolan it says that it should be path: str = '', which it is. Also, the string leads to a valid file
    – Perfalcon
    May 24 '19 at 15:28
  • Looks like it is missing a "/".
    – enolan
    May 24 '19 at 16:41

Browse other questions tagged or ask your own question.