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'
menes
1,4272 gold badges8 silver badges25 bronze badges
asked May 10, 2021 at 7:22
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 Commented 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')
answered May 10, 2021 at 8:20
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. Commented May 11, 2021 at 2:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.