5

I want to load a (.qml) style file to a specific layer, I tried this:

layer = QgsProject.instance().mapLayersByName(layer_name)
if layer.wkbType() == QGis.WKBLineString:
    layer.loadNamedStyle('styles/lines.qml')
layer.triggerRepaint()

Also, I tried this:

layer = QgsProject.instance().mapLayersByName(layer_name)
if layer.geometryType() == QgsWkbTypes.LineGeometry:
    layer.loadNamedStyle('styles/lines.qml')
layer.triggerRepaint()

But I get this error:

if layer.wkbType() == QGis.WKBLineString:

# AttributeError: 'list' object has no attribute 'wkbType'
1
  • FYI QGis.WKBLineString was in QGIS old series 1.x and 2.x. layer.wkbType() == QGis.WKBLineString: should be now layer.wkbType() == QgsWkbTypes.LineString. See doc at qgis.org/api/… @ben-w has already answered for your overall issue
    – ThomasG77
    May 10, 2021 at 8:33

1 Answer 1

4

The method mapLayersByName() returns a list. To return a layer object you need to index the list to access its first element (assuming there is only one layer by that name in your project) e.g.

layer = QgsProject.instance().mapLayersByName(layer_name)[0]
if layer.geometryType() == 1:#Line geometry
    layer.loadNamedStyle('path\\to\\style_file.qml')
1
  • Correct about the list. I would really keep if layer.geometryType() == QgsWkbTypes.LineGeometry:. It makes the code more readable instead of having to keep an index.
    – etrimaille
    May 11, 2021 at 2:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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