TransWikia.com

QGIS configuration: Import Style Libary

Geographic Information Systems Asked on April 25, 2021

I would like to script QGIS to import a style library as part as a configuration for a new user. By Python commands, how do I instruct QGIS to do what a QGIS user can do with the “Import Items” dialog box that is within the “Style Manager”. Specifically, I would like to instruct QGIS to: Import from “File” (not “URL”); check to “Add to favorites”; blank for “Additional tag(s) and “Select All”.

When I look at the QGIS Python API I have found classes for working map layers or for prompting the Style Manager Dialog. From my understanding the map layers requires a layer to exist and isn’t suitable for a blank workspace, whilst, the Dialog option doesn’t allow one to set all of the options.

"Import Item(s)" dialog box from QGIS Style Manager

Some pseudo code could be like:

newStyleCollection = QgsStyleManager()
newStyleCollection = newStyleCollection.importXML('c:SymbolSet.xml')
newStyleCollection.AddToFavourites('True')
newStyleCollection.AdditionalTags(None)
newStyleCollection.sync()

I am basically after the libraries for working with the QGIS style manager.

One Answer

Reading symbols

You can do it with just two lines using QgsStyle class:

qstyles = QgsStyle.defaultStyle()
qstyles.importXml('mycompanystyles.xml')

All styles will be added to the Style Manager. You can check qstyles.symbolCount() before and after the importXml.

Tags

If you use tags on symbols, you don't need to add them to favourites. Users can browse the symbols based on the tags (like your company name). Tags are imported when importing the symbols.

Adding new symbols to favourites

You can, however, add any of those style to the favourites with:

qstyles.addFavorite( QgsStyle.StyleEntity.SymbolEntity, 'Snake' )

If you want to add them all, you can calculate the list of new symbols with something like this:

qstyles = QgsStyle.defaultStyle()
before = qstyles.symbolNames()
qstyles.importXml('mycompanystyles.xml')
after = qstyles.symbolNames()
mystyles = list( set(after) - set(before) )
for s in mystyles:
    qstyles.addFavorite( QgsStyle.StyleEntity.SymbolEntity, s )

Applying styles

You you want to apply any of the styles to a layer, the active layer for example, you can use:

layer = iface.activeLayer()
qstyles = QgsStyle.defaultStyle()
style = qstyles.symbol('Snake')
layer.renderer().setSymbol(style)
layer.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(layer.id())

Related

Get a list of all symbols out of the QGIS Style Manger via PyQGIS

Change point symbol to an existing single marker symbol in PyQGIS

Answered by jgrocha on April 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP