I have a vector layer in QGIS and using pyqgis I have created two styles/renderers:

style_1 = QgsFeatureRendererV2(...)
style_2 = QgsFeatureRendererV2(...)


One of the styles is assigned to the vector layer and the other one is for later use.

Saving the QGIS project will store style_1 with the layer but the second style will be lost if the project is closed. I would like to store the second style in the QGIS project file, not in a seperate style file.

Using QgsProject.writeEntry(...) I can store numbers, texts and lists in the QGIS project file.

Is there a corresponding method for storing custom styles/renderers in the QGIS project file?


Interesting question! Although I can't give a direct answer, an alternative approach could be to define a function containing the code for the second style and save this in a macro. This way, when you load the project, the style is available to be added to a layer by running the function from the Python Console.

You can add a macro for your project from the menubar:

Project > Project Properties > Macros

Enable the checkbox and enter your code in a function. E.g.:

def style(layerName):
    vector_layer= QgsMapLayerRegistry.instance().mapLayersByName( layerName )[0]        
    style_2 = QgsFeatureRendererV2(...)

Click Apply then OK. Then make sure QGIS allows macros to be run by from the menubar:

Settings > Options > General > Project files > Enable macros

And to run the above function from the Python Console, you can type:

style('name of layer')

Don't forget to include single quotation marks as the name of the layer should be a string!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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