[Qgis-user] QgsVectorLayer Fails to Load in PyQGIS 3

Matt Brauer jbrauer90 at gmail.com
Fri Jan 11 09:41:47 PST 2019


I am having issues getting a shape file to load with the QgsVectorLayer
function in PyQGIS. If I use the function in the python console within the
QGIS GUI the layer loads fine and is valid. However, if I implement the
same function in my standalone python 3 script, the layer.isValid()
function returns False and the layer fails to load.

import sys, os, time

sys.path.extend([r'C:\OSGeo4W\apps\qgis\python',r'C:\OSGeo4W\apps\Python37\L
ib\site-packages'])

#modify environment variables to find qgis and qt plugins during qgis.core
import
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGeo4W\apps\Qt5\plugins'
#os.environ['QT_PLUGIN_PATH'] =
r'%QT_PLUGIN_PATH%;C:\OSGeo4W\apps\Qt5\plugins;C:\OSGeo4W\apps\qgis\qtplugins'
os.environ['PATH'] += r';C:\OSGeo4W\apps\qgis\bin;C:\OSGeo4W\apps\Qt5\bin'

from qgis.core import *
from qgis.gui import *

# supply path to qgis install location
QgsApplication.setPrefixPath(r'C:\OSGeo4W\apps\qgis', True)
#QgsApplication.setPluginPath('C:\\OSGeo4W\\apps\Qt5\\plugins\\platforms')
#print(QgsApplication.systemEnvVars())

# create a reference to the QgsApplication
# setting the second argument to True enables the GUI, which we need to do
# since this is a custom application
qgs = QgsApplication([], True)

# load providers
qgs.initQgis()

##########################
# Write your code here to load some layers, use processing algorithms, etc.
canvas = QgsMapCanvas()
canvas.show()
layer = QgsVectorLayer(r'C:\Users\Matt\OneDrive\FarmProject\Kankakee_Parcels
\K3_TaxParcels.shp', 'Kankakee', 'ogr')
print(layer.attributeList())
if not layer.isValid():
print('Failed to open the layer')

# add layer to the registry
add_layers = QgsProject.instance().addMapLayer(layer)

# set extent to the extent of our layer
canvas.setExtent(layer.extent())

# set the map canvas layer set
canvas.setLayers([add_layers])
canvas.refresh()
time.sleep(30)
########################

# When your script is complete, call exitQgis() to remove the provider and
# layer registries from memory
qgs.exitQgis()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20190111/3b65e503/attachment.html>


More information about the Qgis-user mailing list