[GIS] How to get the file name of current style using PyQGIS

pyqgispythonqgisstyle

I get the name of the current style file using layer.styleURI(). Then, I change the style file using layer.loadNamedStyle(different_filename).

However, when I call layer.styleURI() again, it returns the same name as in previous call. How can I get the file name of the current style in QGIS using Python?

Best Answer

I suggest you to do what I state in 1. and choose whether you want to go for 2. while the problem is fixed in QGIS.

  1. Indeed, there is a problem with those functions, so you can inform QGIS devs about the issue you found by posting in the QGIS-dev mailing list and/or reporting it in the QGIS bug tracker (see Filing an issue).

  2. Implement a workaround.

    Since layer.styleURI() is not giving you the updated style, you can use your own functions for keeping track of your styles. For instance, by implementing the following functions, you could get updated styles by calling styleURI( layer ) and loadNamedStyle( layer, stylePath ).

    Just define the functions this way:

    def loadNamedStyle( layer, stylePath ):
        res = layer.loadNamedStyle( stylePath )
        if res[1]: # Style loaded
            layer.setCustomProperty( "layerStyle", stylePath )
            return True
        return False
    
    def styleURI( layer ):
        return layer.customProperty( "layerStyle", "" )
    

    Once they are defined, you could use them this way:

    layer = iface.activeLayer()
    styleURI( layer ) # Will print "" (A style file hasn't been set) 
    loadNamedStyle( layer, "/path/to/mystyle.qml") # Prints True if style exists and applies it
    styleURI( layer ) # Will print "/path/to/mystyle.qml" if previous line was True
    

    Since I've used custom properties in these functions, the style path will be saved across sessions just by saving your QGIS project.

    You could even write the function definitions in a .py file (say style_functions.py) and save it in the same folder as your QGIS project. This way, you would just need to write:

    from style_functions import *
    

    in the QGIS Python console to have the functions ready to be used.

Related Question