基于
https://gis.stackexchange.com/questions/428662/how-to-add-a-layer-to-a-maptheme-in-qgis-with-pyqgis
和
https://gis.stackexchange.com/questions/364733/automatically-creating-themes-in-qgis-3-x
我编写了两个 Pyqgis 代码来为每个图层组生成主题。两者都不起作用。
哪一个显示了可能的解决方案,并且是错误的(2 是我最喜欢的)?
1.
root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()
for group in groups:
group.setItemVisibilityChecked(True)
layersToChanges = group.findLayers()
for layer in layersToChanges:
for child in root.children():
if isinstance(child, QgsLayerTreeGroup):
print("- group: " + child.name())
elif isinstance(child, QgsLayerTreeLayer):
print("- layer: " + child.name() + " ID: " + child.layerId())
# Layer you want to tick
if (child.name() == layer):
child.setItemVisibilityChecked(True)
print("Check only once")
elif child.name() in layersToChanges:
child.setItemVisibilityChecked(False)
print("Check the others you want to hide")
mapThemeRecord = QgsMapThemeCollection.createThemeFromCurrentState(
QgsProject.instance().layerTreeRoot(),
iface.layerTreeView().layerTreeModel()
)
mapThemesCollection.insert(layer, mapThemeRecord)
2.编辑:
#Variables: Groups, project layer
root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()
AllLayers = root.findLayers()
#Visibilities
for layer in AllLayers:
layer.setItemVisibilityChecked(False)
for group in groups:
group.setItemVisibilityChecked(False)
for group in groups:
group.setItemVisibilityChecked(True)
groupLayers = group.findLayers()
for groupLayer in groupLayers:
groupLayer.setItemVisibilityChecked(True)
#Set themes for each group
mtc = QgsProject.instance().mapThemeCollection()
theme_name = str(group)
theme_state = mtc.mapThemeState(theme_name)
layer_record = QgsMapThemeCollection.MapThemeLayerRecord()
theme_state.addLayerRecord(layer_record)
group.setItemVisibilityChecked(False)
这成功了:
#Variables: Groups, project layer
root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()
AllLayers = root.findLayers()
mapThemesCollection = QgsProject.instance().mapThemeCollection()
#Visibilities
for layer in AllLayers:
layer.setItemVisibilityChecked(False)
for group in groups:
group.setItemVisibilityChecked(False)
for group in groups:
group.setItemVisibilityChecked(True)
groupLayers = group.findLayers()
for groupLayer in groupLayers:
groupLayer.setItemVisibilityChecked(True)
#Set themes for each group
mapThemeRecord = QgsMapThemeCollection.createThemeFromCurrentState(
QgsProject.instance().layerTreeRoot(),
iface.layerTreeView().layerTreeModel())
mapThemesCollection.insert(str(group), mapThemeRecord)