1

I did this script in Pycharm and I don't know why python show me this wrong:

QObject::connect: Cannot connect (null)::raiseError( QString ) to QgsVectorLayer::raiseError( QString )

My script below:

import os
from osgeo import ogr
from qgis.core import  *
from PyQt4.QtGui import QApplication

app = QApplication([])
QgsApplication.setPrefixPath("/usr/lib/", True) # Adjust prefix path according to your installation (see note below)
QgsApplication.initQgis()

rootdir = '/media/dogosousa/56A22ED6A22EBA7F/Geoprocessamento/BASE DE DADOS/3.1_SHP/'
extensions = ('.shp')

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        ext = os.path.splitext(file)[-1].lower()
        #Print all files which have .shp extension
        if ext in extensions:
            print (os.path.join(subdir, file))
        #Select only one file
        if file == 'leste_otobacia_2015.shp':
            print "#############"
            print file
            # Bringing shape file fileds
            daShapefile = (os.path.join(subdir, file))

            dataSource = ogr.Open(daShapefile)
            daLayer = dataSource.GetLayer(0)
            layerDefinition = daLayer.GetLayerDefn()

            field = []
            for i in range(layerDefinition.GetFieldCount()):
                print layerDefinition.GetFieldDefn(i).GetName()
                field.append(layerDefinition.GetFieldDefn(i).GetName())
            field


        if file == 'leste_otobacia_2015.shp':
            layer = QgsVectorLayer(rootdir, str(file), "ogr")

            idx = layer.fieldNameIndex('cobacia')
            values = layer.uniqueValues(idx)

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

                #break
  • Sidenote: don't force unrequired type conversions on strings (like str(file) if you know that file is a string already). This will make your code more compatible with unicode folder names and strings in general. – Matthias Kuhn Nov 3 '16 at 9:46
1

Need to include filename with root as below:

 if file == 'leste_otobacia_2015.shp':
            layer = QgsVectorLayer(os.path.join(rootdir, file), str(file), "ogr")

Reference:
http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html

  • Better use os.path.join(rootdir, file) – Matthias Kuhn Nov 3 '16 at 9:44

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.