1

The following is the code that I wrote with the help of PyQGIS Developer Cookbook

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

#Reference to QgsApplication
qgs = QgsApplication([], False)

#path to QGIS install Location
QgsApplication.setPrefixPath("/Applications/QGIS3.4.app", True)

#Load providers
qgs.initQgis()

print (QgsApplication.showSettings())

######################################

#loading projects
#load current project
project = QgsProject.instance()

#read project from file
project.read(os.path.join(project.homePath(),'Documents/GIS/Kandahar/Project/Kandahar.qgz'))

#fileName() returns the path of the project
print (project.fileName())

#loading Vectors
vpath = os.path.join(project.homePath(), "Documents","GIS", "Test","farmland.shp")
vlayer = QgsVectorLayer(vpath, "Farmland", "ogr")
print(vpath)
if vlayer.isValid():
   print("Layer loaded")
else:
   print("Layer failed to load")

I have also edited my .bash_profile to include system paths as

export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH
export LD_LIBRARY_PATH=/Applications/QGIS3.4.app/Contents/MacOS/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/Applications/QGIS3.4.app/Contents/Frameworks:$LD_LIBRARY_PATH
export PYTHONPATH=/Applications/QGIS3.4.app/Contents/Resources/python:$PYTHONPATH
export PYTHONPATH=~/.qgis2/python/plugins/opengeo/ext-libs:$PYTHONPATH
export PATH=/Applications/QGIS3.4.app/Contents/MacOS/bin:$PATH
export QT_QPA_PLATFORM_PLUGIN_PATH=/Applications/QGIS3.4.app/Contents/Plugins
export QGIS_PREFIX_PATH=${QGIS_BUNDLE}/MacOS
export PATH=${QGIS_PREFIX_PATH}/bin:$PATH

my output is the following

Application state:
QGIS_PREFIX_PATH env var:       /MacOS
Prefix:     /MacOS
Plugin Path:        /MacOS/../PlugIns/qgis
Package Data Path:  /MacOS/../Resources
Active Theme Name:  
Active Theme Path:  /MacOS/../Resources/resources/themes//icons/
Default Theme Path: :/images/themes/default/
SVG Search Paths:   /MacOS/../Resources/svg/
    /Users/joelrhine/Library/Application Support/profiles/default/svg/
User DB Path:   /MacOS/../Resources/resources/qgis.db
Auth DB Path:   /Users/joelrhine/Library/Application     Support/profiles/default/qgis-auth.db

Documents/GIS/Kandahar/Project/Kandahar.qgz
Documents/GIS/Test/farmland.shp
Layer failed to load
[Finished in 0.493s]`
0

The problem seems to be with the syntax of

.isValid():

When I don't use parentheses I get the output Layer Loaded, which actually gets loaded when I tested it in the QGIS python console too. Please correct me if I'm wrong.

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.