Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Created May 11, 2021 20:28
Show Gist options
  • Save ThomasG77/048fc9a490b8fef7d11c91fda8de04b5 to your computer and use it in GitHub Desktop.
Save ThomasG77/048fc9a490b8fef7d11c91fda8de04b5 to your computer and use it in GitHub Desktop.
# Run from project origin
layout_name = "your_layout_name"
project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName(layout_name)
def duplicate_item(item, layout, position=None):
doc = QDomDocument('Clipboard')
element = doc.createElement('Copied items')
context = QgsReadWriteContext()
item.writeXml(element, doc, context)
if type(item) == QgsLayoutItemGroup:
for subitem in item.items():
subitem.writeXml(element, doc, context)
if type(item) == QgsLayoutFrame:
selected.multiFrame().writeXml(element, doc, context)
doc.appendChild(element)
layout_items = doc.elementsByTagName('LayoutItem')
for i in range(layout_items.count()):
item_node = layout_items.at(i)
if item_node.isElement():
item_node.toElement().removeAttribute('uuid')
item_node.toElement().removeAttribute('groupUuid')
layout_frames = doc.elementsByTagName('LayoutMultiFrame')
for i in range(layout_frames.count()):
item_node = layout_frames.at(i)
if item_node.isElement():
item_node.toElement().removeAttribute('uuid')
item_node.toElement().removeAttribute('groupUuid')
layout_childframes = doc.elementsByTagName('childFrame')
for i in range(layout_childframes.count()):
item_node = layout_childframes.at(i)
if item_node.isElement():
item_node.toElement().removeAttribute('uuid')
item_node.toElement().removeAttribute('groupUuid')
return doc
item = layout.selectedItems()[0]
# Alternatively if set item id
#item = layout.itemById('item_id')
with open('/tmp/shared_item.xml', 'w') as outfile:
outfile.write(duplicate_item(item, layout).toString())
# Run from destination project
# Paste section from file
layout_name = "your_layout_name"
project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName(layout_name)
def copyFromXml(file_path, layout):
doc1 = QDomDocument();
file = QFile(file_path)
doc1.setContent(file)
file.close()
layout.addItemsFromXml(doc1.firstChildElement(), doc1, QgsReadWriteContext())
copyFromXml("/tmp/shared_item.xml", layout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment