Вот мой код, который я написал для выполнения этой задачи:
Код: Выделить всё
from qgis.core import QgsProject, QgsSVGFillSymbolLayer
import os
# Replace with the name of your layer
layer_name = "layer"
nouveau_chemin = "Z:/../../Image_svg/"
# Recovery of the layer
layer = QgsProject.instance().mapLayersByName(layer_name)
if not layer:
print(f"Layer '{layer_name}' was not found.")
else:
layer = layer[0]
renderer = layer.renderer()
if renderer is None:
print("No symbology detected.")
else:
# Function to update SVG paths in symbols
def update_svg_paths_in_symbols(symbols):
for symbol in symbols:
for symbol_layer in symbol.symbolLayers():
if isinstance(symbol_layer, QgsSVGFillSymbolLayer):
try:
# Use properties() to get the SVG path
properties = symbol_layer.properties()
print(f"Symbol properties : {properties}")
svg_path = properties.get('svgFile', None)
if svg_path:
print(f"Old SVG path : {svg_path}")
# Extract the file name from the existing path
file_name = os.path.basename(svg_path)
# Make sure the. svg extension is present
if not file_name.lower().endswith('.svg'):
file_name += '.svg'
# Build the new full path
new_svg_path = os.path.join(nouveau_chemin, file_name)
# Show the new path (before checking if it exists)
print(f"Nouveau chemin SVG : {new_svg_path}")
# Check if the file exists in this new path
if os.path.exists(new_svg_path):
# Use the setDataDefinedProperty method to change the path
symbol_layer.setDataDefinedProperty('svgFile', new_svg_path)
print(f"Updated SVG path : {new_svg_path}")
else:
print(f"The SVG file does not exist at the location : {new_svg_path}")
else:
print("No SVG path found for this symbol.")
except Exception as e:
print(f"Error while updating SVG path : {str(e)}")
# Function to browse rules and update SVG paths
def update_svg_paths_in_rules(rule):
for symbol in rule.symbols():
update_svg_paths_in_symbols([symbol])
for child_rule in rule.children():
update_svg_paths_in_rules(child_rule)
# If the renderer is a RuleRenderer, it means that it uses a set of rules
if renderer.type() == 'RuleRenderer':
print("Symbology based on rules detected.")
root_rule = renderer.rootRule()
update_svg_paths_in_rules(root_rule)
else:
print(f"Symbology type not supported : {renderer.type()}")
# Apply changes
layer.triggerRepaint()
print("SVG path update completed.")
Код: Выделить всё
Error while updating SVG path : QgsSymbolLayer.setDataDefinedProperty(): argument 1 has unexpected type 'str'
Что я пробовал:
- Я пытался использовать метод setSvgFile, но, похоже, он не работает
с версия QGIS (3.34.4), которую я использую используя. - Я пытался найти другие подходы, но не знаю, как правильно обновить
путь к файлу SVG.
Мой вопрос: - Есть ли другой метод динамического изменения пути к файлу SVG в
QgsSVGFillSymbolLayer ? - Проблема с версией QGIS, и если да, то какой метод мне следует
использовать в этом случае?
Я француз и старался максимально использовать свой код на английском языке. Извините, если есть ошибки.
Подробнее здесь: https://stackoverflow.com/questions/793 ... ng-in-qgis
Мобильная версия