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)
  • 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. – Germán Carrillo Apr 1 '16 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? – brgionta Apr 1 '16 at 21:43
  • 1
    First guess, try with C:\\OSGeo4W\\apps\\qgis\\ as prefix path. – Germán Carrillo Apr 1 '16 at 21:46
  • Tried to no avail. Still get fatal pop-up window on that line – brgionta Apr 1 '16 at 21:54
  • @brgionta - Try adding QgsApplication( [], False, "C:\\Users\\You\\AppData\\Local\\Temp" ) before QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis", True). – Joseph Apr 4 '16 at 10:04
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)

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.