I run this example to create a temporary vector layer, in an empty QGis project. it is based on this tutorial - https://courses.spatialthoughts.com/pyqgis-in-a-day.html ,
canvas = iface.mapCanvas()
extent = canvas.extent()
vlayer = QgsVectorLayer('Polygon', 'extent', 'memory')
crs = QgsProject.instance().crs()
vlayer.setCrs(crs)
provider = vlayer.dataProvider()
f = QgsFeature()
geometry = QgsGeometry.fromRect(extent)
f.setGeometry(geometry)
provider.addFeature(f)
vlayer.updateExtents()
I add the layer to the canvas, like this:
layers = canvas.layers()
layers.insert(0, vlayer)
canvas.setLayers(layers)
canvas.refresh()
or to the project, like this:
QgsProject.instance().addMapLayer(vlayer)
Anyway, the problem is that when the user closes the project, he is asked if he wants to save it. I don't want that. I was expecting the layer to be ignored when closing the project, because it is a memory layer.
I have Qgis 3.22.4