我在QGIS 1.8中有一个工作正常的插件,该插件从MSAccess数据库读取数据并将其添加到一系列内存层中。过渡过程中涉及一些处理,因此我不认为仅使用QGIS直接从数据库读取是一种选择。
我想从QGIS 1.8升级到1.9(主要是因为打印作曲家的素质得到了提高)。该插件不适用于新的API。
我尝试了Google搜索中出现的各种方法。一种,修改以下代码-来自http://www.qgis.org/pyqgis-cookbook/vector.html#memory-provider,即向数据提供者添加几何形状和属性,然后更新层-以适应新的API有点,但是直到我手动进入编辑模式(类似于http://hub.qgis.org/issues/3713),属性才可见。在上述链接的回复#1中详细介绍了一种替代方法,该方法正确添加了图层和属性,但无法向图层添加要素。
鉴于这应该是一个非常简单的任务,所以我希望在座的人可以提供一个如何完成此工作的示例。(附言:我不是专业的程序员,我的大多数编码都还很粗糙-我欢迎任何指导,但请您原谅我的无知)
# Receivers = a list of lists returned from a database query
# create layer
vl = QgsVectorLayer("Point", item, "memory")
pr = vl.dataProvider()
# add fields
pr.addAttributes( [ QgsField("Rec_No", QVariant.Int), QgsField("Include", QVariant.String), QgsField("Label", QVariant.String), QgsField("X", QVariant.Double),
QgsField("Y", QVariant.Double), QgsField("Z", QVariant.Double), QgsField("Height", QVariant.Double),
QgsField("Project_Re", QVariant.String), QgsField("NCA", QVariant.String),
QgsField("DayCrit", QVariant.Int), QgsField("EveCrit", QVariant.Int), QgsField("NightCrit", QVariant.Int) ] )
for i in range(len(Receivers)):
# add a feature
fet = QgsFeature()
X = Receivers[i][3]
Y = Receivers[i][4]
fet.setGeometry( QgsGeometry.fromPoint(QgsPoint(X,Y)) )
# Details = a list of results returned from a database query specific to each result in 'Receivers'
if Receivers[i][3] != 0:
Include = 'Yes'
else:
Include = 'No'
fet.setAttributeMap( { 0 : QVariant(Receivers[i][0]), 1 : QVariant(Include), 2 : QVariant(Receivers[i][2]),
3 : QVariant(Receivers[i][3]), 4 : QVariant(Receivers[i][4]), 5 : QVariant(Receivers[i][5]), 6 : QVariant(Receivers[i][6]),
7 : QVariant(Details[0]), 8 : QVariant(Details[1]), 9 : QVariant(Details[2]), 10 : QVariant(Details[3]), 11 : QVariant(Details[4]) } )
pr.addFeatures( [ fet ] )
# add a style
vl.loadNamedStyle('C:/OSGeo4W/apps/qgis/python/plugins/Gopher2QGIS/styles/Receiver_Style.qml')
# update layer's extent when new features have been added
# because change of extent in provider is not propagated to the layer
vl.commitChanges()
vl.updateExtents()
vl.updateFieldMap()
QgsMapLayerRegistry.instance().addMapLayer(vl)
看一下PinPoint插件。它将带有属性的功能添加到存储层,并与2.0 API一起使用。
—
gsherman
很好,像魅力一样。我使用此示例添加了一个来自restfull服务的点的层。QGis很棒
—
Peter