PyQGIS – Triggering Add Feature Action in Polygon Layer in Plugin

pyqgis-3qgis-3qgis-plugins

In Pyqgis after an "edit" button is pressed on my plugin, first I add google sat layer, then move it to the bottom, then I add a polygon layer and move it to the top, then I trigger editing and the add feature action. the user can then add polygons but they are invisible. I even have a button that will upload the polygon layer to a database and when I check the polygons are there but they will not show up on the canvas. Here is my code that triggers editing:

'''

# Add google sat layer
service_url = "mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}" 
service_uri = "type=xyz&zmin=0&zmax=21&url=https://"+requests.utils.quote(service_url)
tms_layer = iface.addRasterLayer(service_uri, "Google Sat", "wms")

# move sat layer to the bottom
root = QgsProject.instance().layerTreeRoot()
root.setHasCustomLayerOrder (True)
order = root.customLayerOrder()
root.setCustomLayerOrder( order[::-1]

# Add polygon layer
self.poly = QgsVectorLayer("Polygon", "target_polygons", "memory")
pr = self.poly.dataProvider
QgsProject.instance().addMapLayer(self.poly)

# move polygon layer to the top
order.insert( 1, order.pop( -1 ) ) # self.poly to the top
root.setCustomLayerOrder(order)

# Enter editing mode
self.poly.startEditing()
iface.actionAddFeature().trigger()

'''

I have another function for when an "ok" button is pressed that will trigger:

iface.mainWindow().findChild(QAction, 'mActionToggleEditing').trigger()

and that will prompt the user to save changes. Also when I check the layer properties the opacity and everything looks fine. Maybe the polygons need certain attributes? I have also tried deleting every layer except the polygon layer and they still don't show up, but I know they are there.

Best Answer

I was able to solve this by using this code after creating the polygon layer:

        myalayer = root.findLayer(self.poly.id())
        myClone = myalayer.clone()
        parent = myalayer.parent()
        parent.insertChildNode(0, myClone)
        parent.removeChildNode(myalayer)

This basically simulates dragging the layer around manually in the UI and when I did that the polygons show up.

Related Question