I tried to use QgsProject.instance().addMapLayer(layer) on QGIS 3.4 but I didn't succeed.


layer = QgsVectorLayer(r'C:\CURSO_PYQGIS\CAPAS\urbano.shp','urbano','ogr ') 

But the layer didn't show up, and it didn't give me an error on Python console. I don't understand it, someone knows why?

  • Did you check layer validity before adding it ? By doing layer.isValid() – SIGIS Mar 15 '19 at 8:19
  • There should not be a space after ogr. Change 'ogr ' to 'ogr'. – Joseph Mar 15 '19 at 10:25
  • Thanks Joseph!!! that was the reason "There should not be a space after ogr. Change 'ogr ' to 'ogr'" – Oskar Mar 15 '19 at 12:30

The format ("\" instead of "/") of the path could be the cause of your error (see the test below). (I work on Windows and I install Qgis3 with OSGEo4)

This is output of some test I made :

# Here with your format '\'
lyr_error = QgsVectorLayer(r'C:\temp\Parcelles_agricoles_5.shp', 'Parcelles agricole', 'ogr')
# Here with this format "/"
lyr_no_error = QgsVectorLayer(r'C:/temp/Parcelles agricoles_5.shp', 'Parcelles agricole', 'ogr')
# An other format that also valid
lyr_no_error2 = QgsVectorLayer('C:\\temp\\Parcelles agricoles_5.shp', 'Parcelles agricole', 'ogr')
# Test validity
>>> False
>>> True
>>> True
# Here it doesn't output anything even no error
# Here it output the instance and the layer show up.
>>> <qgis._core.QgsVectorLayer object at 0x0000000009ED4D38>

I didn't try other type of format but this could be the solution. Hope it helps.

  • Thanks a lot!,your information will help me a lot – Oskar Mar 15 '19 at 12:34

There are some good tutorial about QGIS Python Programming at Geodose. Some tutorials are: Working with Vector Layer ,Add/Delete Field and Updating Attribute Value ,Adding CSV Data,Drawing Marker,Drawing,Polyline and Polygon,Animate GPS Track, Set and Reload Basemap Datasource. Quite good resource.

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.