2

I've been able to execute the command below in the Python console in QGIS. I am able to execute from qgis.core import * and import qgis.utils with no errors in the OSGeo4W shell but adding the layer I am still getting QObject::connect: Cannot connect <null>::raiseError< QString > to QgsVectorLayer::raiseError< QString >

The script below works in the Python console within QGIS. My paths are set in Environment Variables as: PYTHONPATH=c:\OSGeo4W\apps\qgis\python and PATH=c:\OSGeo4W\apps\qgis\bin

from qgis.core import *
import gdal
import qgis.utils
QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis", True)
QgsApplication.initQgis() 
print QgsApplication.showSettings()
layer = QgsVectorLayer('/path/to/shapefile_folder/test.shp', 'test', 'ogr')
if not layer.isValid():
 print "Layer failed to load!"
else:
 print "Layer was loaded successfully!"
QgsMapLayerRegistry.instance().addMapLayer(layer)
asked Apr 1, 2016 at 19:48
5
  • Have a look at docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/… You're only missing a few lines that must be always present when running Python scripts out of QGIS. Commented Apr 1, 2016 at 21:27
  • I've edited the code above. When running the modified code, a pop-up window stating "python.exe has stopped working" shows up. I've gone line by line in the code and it seems that QgsApplication.initQgis() is crashing Python. Any thoughts? Commented Apr 1, 2016 at 21:43
  • 1
    First guess, try with C:\\OSGeo4W\\apps\\qgis\\ as prefix path. Commented Apr 1, 2016 at 21:46
  • Tried to no avail. Still get fatal pop-up window on that line Commented Apr 1, 2016 at 21:54
  • @brgionta - Try adding QgsApplication( [], False, "C:\\Users\\You\\AppData\\Local\\Temp" ) before QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis", True). Commented Apr 4, 2016 at 10:04

1 Answer 1

1
from qgis.core import *
import gdal
import qgis.utils
QgsApplication.setPrefixPath("C:\OSGeo4W64\apps\qgis", True)
qgs = QgsApplication([], True)
qgs.initQgis()
print QgsApplication.showSettings()
layer = QgsVectorLayer('C:\Users\path to your shape\CB.shp', 'CB', 'ogr')
if not layer.isValid():
 print "Layer failed to load!"
else:
 print "Layer was loaded successfully!"
QgsMapLayerRegistry.instance().addMapLayer(layer)
Matt
1,69218 silver badges24 bronze badges
answered Jun 16, 2016 at 9:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.