前段时间由于工作需要,学习使用Python为qgis制作一个插件,现在把制作插件期间遇到的问题和解决方法记录下来,以方便自己和其他朋友.
mapCanvas = iface.mapCanvas()
layers = mapCanvas.layers()
for layer in layers:
if layer.name() == 'point':
layer_point = layer
if layer.name() == 'line':
layer_line = layer
if layer.name() == 'area':
layer_area = layer
for feature in layer_point.getFeatures():
_Attri = feature.attribute('attri1')
_Other = feature.attribute('attri2')
if _Attri == SomeThing:
x = feature.geometry().asPoint().x()
y = feature.geometry().asPoint().y()
......(do something you want)
# create memory layer
lineVecLayer = QgsVectorLayer("LineString", "line_layer", "memory")
lineProvider = lineVecLayer.dataProvider()
pointVecLayer = QgsVectorLayer("Point", "point_layer", "memory")
pointProvider = pointVecLayer.dataProvider()
lineVecLayer.startEditing()
linefeatures = []
points = [QgsPoint(x,y),QgsPoint(x1,y1),QgsPoint(x2,y2),QgsPoint(x3,y3)]
line_feature = QgsFeature()
line_feature.setGeometry(QgsGeometry().fromPolyline(points))
linefeatures.append(line_feature)
lineProvider.addFeatures(linefeatures)
lineVecLayer.commitChanges()
# add fields
lineProvider.addAttributes( [ QgsField("attri1", QVariant.Int),QgsField("attri2", QVariant.Int),QgsField("attri3", QVariant.Int)] )
lineVecLayer.startEditing()
linefeatures = []
points = [QgsPoint(x,y),QgsPoint(x1,y1),QgsPoint(x2,y2),QgsPoint(x3,y3)]
line_feature = QgsFeature(lineVecLayer.pendingFields())
line_feature.setGeometry(QgsGeometry().fromPolyline(points)
line_feature.setAttributes([1, 2, 3])
#line_feature['attri1'] = 1
#line_feature['attri2'] = 2
#line_feature['attri3'] = 3
linefeatures.append(line_feature)
lineProvider.addFeatures(linefeatures)
lineVecLayer.commitChanges()
- _init_.py,是插件调用的起点,一般例如版本号、插件名、插件主类等信息会在这里面定义
- mainPlugin.py,插件主体啦,所有的插件操作都必须在这里完成,也是写代码最多的部分
- metadata.txt,QGIS>=1.8.0版本要求提供,是插件元数据,描述了插件的基本信息,如版本号,插件名和其他一些插件网址,框架信息等。在_init_.py文件中会用到,用来获取上述插件相关信息。然而从QGIS2.0开始,所有的插件元数据信息只能在metadata.txt中设置了,在_init_.py中的设置将被视为无效.笔者使用官方文档提供的plugin creator生成的插件中,无metadata.txt在2.12版qgis中插件不能直接安装