我试图运行以下代码来测试一个简单的独立QGIS应用程序并获得以下错误。
原始异常是: Traceback(最近一次调用最后一次): File" F:\ Eclipse workspace \ MyMap \ MyMap.py",第23行,in pr.addFeatures([linstr]) AttributeError:' NoneType'对象没有属性' addFeatures'
我尝试过多次修复但没有成功。从根本上说,我不明白为什么会产生错误,因此很难解决问题。为清楚起见,这来自QGIS Python Programming Cookbook 2nd ed。第23行是pr.addFeatures([linstr])。我在Windows 10上运行Eclipse
任何人都可以提供帮助。
# Standalone QGIS script
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QgsApplication([], True)
path = "C:/Program Files/QGIS2.18/apps/qgis"
app.setPrefixPath(path, True)
app.initQgis()
canvas = QgsMapCanvas()
title = "PyQGIS Standalone Application Example"
canvas.setWindowTitle(title)
canvas.setCanvasColor(Qt.white)
layer_info = 'LineString?crs=epsg:4326'
layer = QgsVectorLayer(layer_info, 'MyLine' , "memory")
pr = layer.dataProvider()
linstr = QgsFeature()
wkt = "LINESTRING (1 1, 10 15, 40 35)"
geom = QgsGeometry.fromWkt(wkt)
linstr.setGeometry(geom)
pr.addFeatures([linstr])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayer(layer)
canvas.setExtent(layer.extent())
canvas.setLayerSet([QgsMapCanvasLayer(layer)])
canvas.zoomToFullExtent()
canvas.show()
exitcode = app.exec_()
QgsApplication.exitQgis()
sys.exit(exitcode)