3

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.

1
  • As a small update, I have found that if I simply move the polygon layer in the stack (doesn't matter where) the polygons will show up. They will always be covered by the google sat layer though, UNLESS I drag in the sat layer from xyz tiles, then they will be on top of that layer. So I will need to find a way to programatically refresh the layer in the stack, and also pull in the google sat layer that will be on bottom.
    – tbob
    Apr 22 at 17:23

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.