[GIS] Adding shapefile using PyQGIS

pyqgisqgisshapefilestandalone

I am trying to add a Shapefile outside of the QGIS environment using PyQGIS. Ideally this would be done without creating a map in QGIS. I've started with the code below but am receiving the following error:

QObject::connect: Cannot connect <null>::raiseError< QString > to QgsVectorLayer::raiseError< QString >

Does the command below create a new map canvas?

from qgis.core import *
import qgis.utils

layer = QgsVectorLayer("F:\\IrrigatedLands\\FC_qgis\\boundary.shp", "testlayer_shp", "ogr")
#if not layer.isValid():
  #print "Layer failed to load!"

Best Answer

When you intend to run PyQGIS scripts out of QGIS, you need to initialize a QgsApplication so that it loads data providers and other resources. The following code snippet should work:

from qgis.core import *
from PyQt4.QtGui import QApplication

app = QApplication([])
QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis\\", True) # Adjust prefix path according to your installation (see note below)
QgsApplication.initQgis()

layer = QgsVectorLayer("F:\\IrrigatedLands\\FC_qgis\\boundary.shp", "testlayer_shp", "ogr")

if not layer.isValid():
  print "Layer failed to load!"

Now you can start doing anything with your valid Shapefile, even without a map canvas.

Note: See https://gis.stackexchange.com/a/155852/4972 for more details about setting a prefix path on both Windows and GNU/Linux.

Related Question