def newPolygonVector(self):
vlt = QgsVectorLayer("Polygon?crs=EPSG:32647", "", "memory")
vlt.dataProvider().addAttributes([QgsField("id", QVariant.Int)])
vlt.updateFields()
self.MakeFile()
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"
QgsVectorFileWriter.writeAsVectorFormatV2(vlt, self.mypath + f'/FieldBorderPolygon{self.index}.shp',
project.transformContext(), options)
self.vlb = self.iface.addVectorLayer(self.mypath + f'/FieldBorderPolygon{self.index}.shp', "", "ogr")
Symbol = QgsFillSymbol.createSimple(
{'color_border': '#3232fa', 'width_border': '1', 'style': 'no'})
self.vlb.renderer().setSymbol(Symbol)
self.vlb.startEditing()
self.vlb.triggerRepaint()
def newLineVector(self):
vlt = QgsVectorLayer("LineString?crs=EPSG:32647", "", "memory")
vlt.dataProvider().addAttributes([QgsField("id"
, QVariant.Int)])
vlt.updateFields()
self.MakeFile()
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"
QgsVectorFileWriter.writeAsVectorFormatV2(vlt, self.mypath + f'/RajahLine{self.index}.shp',
project.transformContext(), options)
self.vlr = self.iface.addVectorLayer(self.mypath + f'/RajahLine{self.index}.shp', "", "ogr")
self.vlr.renderer().symbol().setWidth(0.6)
self.vlr.renderer().symbol().setColor(QColor.fromRgb(255, 0, 0))
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
self.newLineVector()
self.newPolygonVector()
#Grouping
root = project.layerTreeRoot()
group = root.insertGroup(0, f"Prelining {self.index}")
group.addLayer(self.vlb)
group.addLayer(self.vlr)
root.removeLayer(self.vlb)
root.removeLayer(self.vlr)
These are some of my code snippet for one of the processes in a plugin and the plugin is iterable.
Whenever it runs the first time, it gets the result that I want, as it creates a 2 new vector outside of a group in TOC
But when it comes to the second time I run the plugin, it will create the first 2 vector inside the 1st group and then will add it into 2nd group having duplicated layer in Group1 and Group2
Results are shown below
1.1) This is the first time running the plugin and everything lays greatly inside the group:

1.2) When I click on the iterable plugin again, it will create the vector inside the previous group instead of outside the group:



root = QgsProject.instance().layerTreeRoot()and thenroot.insertLayer(0, my_layer). On the other hand, you can read this answer to know about the recommended way of adding layers to groups. – Germán Carrillo Dec 28 '20 at 17:41