1

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

Example:

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

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?

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

2 Answers 2

1

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
lyr_error.isValid()
>>> False
lyr_no_error.isValid()
>>> True
lyr_no_error2.isValid()
>>> True
# Here it doesn't output anything even no error
QgsProject.instance().addMapLayer(lyr_error)
# Here it output the instance and the layer show up.
QgsProject.instance().addMapLayer(lyr_no_error)
>>> <qgis._core.QgsVectorLayer object at 0x0000000009ED4D38>

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

1
  • Thanks a lot!,your information will help me a lot
    – Oskar
    Mar 15, 2019 at 12:34
-1

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 and acknowledge you have read our privacy policy.

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