[GIS] Add layer to map in qgis3 via a python script

pyqgisqgis-3

I'm trying convert my old plugin to QGIS3 and one part is to create a shapefile, and afterwards load it to the Layer menu like this:

from qgis.core import QgsVectorLayer, QgsProject
layer = QgsVectorLayer('c:/dev/test.shp', 'test', "ogr")
print(layer.isValid())
QgsProject.instance().addMapLayer(layer)

The python console returns True and the Layer appears in the layer list, hence I can't add features to it when I have toggled editing:

enter image description here

However, if I remove the layer from layer list and add the layer with the same code in the Python console I have no problem with adding a feature.

Any suggestions for what I can try?

Best Answer

I solved the problem, I believe that the layer was loaded without fields in some way. It was wired though, it had an 'ID' column when I checked in the Attribute table, but somehow I believe that it had something todo with error anyway. When I changed the layer creation method (by the help of the code in this question) the layer was loaded correctly from the plugin.

Related Question