2

I'm trying to create some layer visibility preset in QGIS 2.18 using its API. But, for some reason, when I try to add layers that are visible in legend interface, it simply doesn't work.

Here is the piece of the code that I'm refering to:

# Creating a preset
root = QgsProject.instance().layerTreeRoot()
clPreset = QgsProject.instance().visibilityPresetCollection()
clPreset.insert('MapaPrincipal', QgsVisibilityPresetCollection.PresetRecord())

# Adding visible layers to created preset
root = QgsProject.instance().layerTreeRoot()

for l in root.findLayers():
    if not l.isVisible():
        iface.legendInterface().setLayerVisible(root.findLayer(l).layer(), True)

clPreset.addVisibleLayersToPreset(root, clPreset.presetState('MapaPrincipal'))

When I check for the visible layers added to the visibility preset, it returns an empty list. What am I doing wrong?

0

Solved:

# Defining a preset
root = QgsProject.instance().layerTreeRoot()
clPreset = QgsProject.instance().visibilityPresetCollection()

namePreset = 'MapaPrincipal'
prRecord = clPreset.presetState(namePreset)

# Adding visible layers to preset
for l in root.findLayers():
    if not l.isVisible():
        l.setVisible(True)

clPreset.addVisibleLayersToPreset(root, prRecord)

# Creating or updating the preset
if clPreset.hasPreset(namePreset):
    clPreset.update(namePreset, prRecord)
else:
    clPreset.insert(namePreset, prRecord)

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.