I created a categorized symbology with labels and saved it to a .qml file. When trying to load this .qml via PyQGIS nothing happens.

layer.loadNamedStyle('path\to\file.qml')
layer.triggerRepaint()


What I'm doing is clipping from a layer that already has this style applied, but the new clipped layer doesn't inherit the styling. I'm trying to put it back by loading from an external file. (Is it possible to easily copy the styling of an existing layer?)

If I manually apply the style via the GUI, it loads perfectly (categories, labels, etc).

The above code DOES work perfect when loading a different .qml I made that consists of a simple outline for a single symbol.

I think I'm missing something when it comes to loading a .qml and getting the QgsCategorizedSymbolRenderer set correctly.

I have tried adding iface.layerTreeView().refreshLayerSymbology( layer.id()) to no avail.

EDIT:
I have a similar layer I am clipping with it's own categorized symbology exported to a .qml. The code I have successfully loads the .qml for that clipped layer. Seems the code isn't the problem. For the layer I'm having an issue with, I tried exporting a .qml from it representing a single symbol with a solid color. Not even that .qml loads successfully via pyqgis, not on any layer I try it. It still loads if I do it manually. It seems that perhaps when exporting a style from that layer, there is an error with the .qml it generates. At least in terms of loading it via loadNamedStyle.

Edit:

I was wrong. Devs pointed out what is now obvious. One needs to use "/" slashes in paths, even on Windows. Try:

layer.loadNamedStyle('path/to/file.qml')


"something\bxxx.qml" is interpreting "\b" as a "backspace" character. See https://docs.python.org/3/reference/lexical_analysis.html#strings