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'
sys.path.extend([r'c:\osgeo4w64\apps\qgis\python',r'c:\osgeo4w64\apps\Python37\Lib\site-packages'])
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)
app.initQgis()
#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
vector_source? Put it withrin front – Fran Raga May 23 '19 at 19:44vector_sourceisvector_source = "C:/users/name/otherfolders/shapefile.shp". The result is still the same with anrbefore the quotation. – Perfalcon May 24 '19 at 09:50path: str = '', which it is. Also, the string leads to a valid file – Perfalcon May 24 '19 at 15:28/? I have tried every place possible – Perfalcon May 30 '19 at 11:31