Skip to content

Commit

Permalink
Fixed strings replacement in the layout labels within templates. (#17)
Browse files Browse the repository at this point in the history
* Fixed strings replacement in the layout labels within templates.
  • Loading branch information
ldebek authored Jan 17, 2020
1 parent e7a48f2 commit 93337c0
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
</layer>
</symbol>
</LayoutItem>
<LayoutItem referencePoint="7" id="author" frame="false" marginY="1" visibility="1" itemRotation="0" background="true" outlineWidthM="0.3,mm" type="65641" zValue="9" size="105.484,8,mm" marginX="1" htmlState="0" positionOnPage="319.173,49.3655,mm" templateUuid="{8f66d0c3-a63a-47a8-b273-431d3a84f8a6}" groupUuid="" halign="1" excludeFromExports="0" position="319.173,49.3655,mm" positionLock="false" blendMode="0" frameJoinStyle="miter" opacity="1" uuid="{8f66d0c3-a63a-47a8-b273-431d3a84f8a6}" labelText="Compiled by [username] on [%concat(day($now ),'/',month($now),'/',year($now))%]" valign="32">
<LayoutItem referencePoint="7" id="author" frame="false" marginY="1" visibility="1" itemRotation="0" background="true" outlineWidthM="0.3,mm" type="65641" zValue="9" size="105.484,8,mm" marginX="1" htmlState="0" positionOnPage="319.173,49.3655,mm" templateUuid="{8f66d0c3-a63a-47a8-b273-431d3a84f8a6}" groupUuid="" halign="1" excludeFromExports="0" position="319.173,49.3655,mm" positionLock="false" blendMode="0" frameJoinStyle="miter" opacity="1" uuid="{8f66d0c3-a63a-47a8-b273-431d3a84f8a6}" labelText="[author]" valign="32">
<FrameColor blue="0" green="0" alpha="255" red="0"/>
<BackgroundColor blue="255" green="255" alpha="255" red="255"/>
<LayoutObject>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
</layer>
</symbol>
</LayoutItem>
<LayoutItem templateUuid="{1ccf4a9b-a394-46d8-8587-67688268fbc8}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="11" marginY="1" type="65641" uuid="{1ccf4a9b-a394-46d8-8587-67688268fbc8}" frame="false" background="true" labelText="Compiled by martin on [%concat(day($now ),'/',month($now),'/',year($now))%]" htmlState="0" id="author" positionLock="false" position="196.739,36.7397,mm" visibility="1" blendMode="0" positionOnPage="196.739,36.7397,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="72.1814,7,mm" valign="32" marginX="1" halign="1" referencePoint="7">
<LayoutItem templateUuid="{1ccf4a9b-a394-46d8-8587-67688268fbc8}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="11" marginY="1" type="65641" uuid="{1ccf4a9b-a394-46d8-8587-67688268fbc8}" frame="false" background="true" labelText="[author]" htmlState="0" id="author" positionLock="false" position="196.739,36.7397,mm" visibility="1" blendMode="0" positionOnPage="196.739,36.7397,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="72.1814,7,mm" valign="32" marginX="1" halign="1" referencePoint="7">
<FrameColor red="0" green="0" blue="0" alpha="255"/>
<BackgroundColor red="255" green="255" blue="255" alpha="255"/>
<LayoutObject>
Expand All @@ -109,7 +109,7 @@
<LabelFont description="Arial,10,-1,5,50,0,0,0,0,0" style=""/>
<FontColor red="0" green="0" blue="0"/>
</LayoutItem>
<LayoutItem templateUuid="{c28f468d-8f9a-4d0a-8e22-6f00c0fd2dfe}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="10" marginY="1" type="65641" uuid="{c28f468d-8f9a-4d0a-8e22-6f00c0fd2dfe}" frame="false" background="true" labelText="" htmlState="0" id="title" positionLock="false" position="51.2105,26.7476,mm" visibility="1" blendMode="0" positionOnPage="51.2105,26.7476,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="78.4211,11.9842,mm" valign="32" marginX="1" halign="1" referencePoint="4">
<LayoutItem templateUuid="{c28f468d-8f9a-4d0a-8e22-6f00c0fd2dfe}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="10" marginY="1" type="65641" uuid="{c28f468d-8f9a-4d0a-8e22-6f00c0fd2dfe}" frame="false" background="true" labelText="[title]" htmlState="0" id="title" positionLock="false" position="51.2105,26.7476,mm" visibility="1" blendMode="0" positionOnPage="51.2105,26.7476,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="78.4211,11.9842,mm" valign="32" marginX="1" halign="1" referencePoint="4">
<FrameColor red="0" green="0" blue="0" alpha="255"/>
<BackgroundColor red="255" green="255" blue="255" alpha="255"/>
<LayoutObject>
Expand Down Expand Up @@ -163,7 +163,7 @@
<fillColor2 red="255" green="255" blue="255" alpha="255"/>
<strokeColor red="0" green="0" blue="0" alpha="255"/>
</LayoutItem>
<LayoutItem templateUuid="{ece15dd0-d2ca-4308-9ee3-8a6195f3ab86}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="5" marginY="1" type="65641" uuid="{ece15dd0-d2ca-4308-9ee3-8a6195f3ab86}" frame="true" background="true" labelText="Aerial 2010|Cities Revealed aerial photography copyright The GeoInformation Group 2010|0" htmlState="0" id="copyright" positionLock="false" position="12.3591,192.599,mm" visibility="1" blendMode="0" positionOnPage="12.3591,192.599,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="118.993,6.58662,mm" valign="32" marginX="1" halign="1" referencePoint="0">
<LayoutItem templateUuid="{ece15dd0-d2ca-4308-9ee3-8a6195f3ab86}" excludeFromExports="0" opacity="1" frameJoinStyle="miter" zValue="5" marginY="1" type="65641" uuid="{ece15dd0-d2ca-4308-9ee3-8a6195f3ab86}" frame="true" background="true" labelText="[copyright]" htmlState="0" id="copyright" positionLock="false" position="12.3591,192.599,mm" visibility="1" blendMode="0" positionOnPage="12.3591,192.599,mm" itemRotation="0" groupUuid="" outlineWidthM="0.3,mm" size="118.993,6.58662,mm" valign="32" marginX="1" halign="1" referencePoint="0">
<FrameColor red="0" green="0" blue="0" alpha="255"/>
<BackgroundColor red="255" green="255" blue="255" alpha="255"/>
<LayoutObject>
Expand Down
6 changes: 4 additions & 2 deletions QGIS Plugin/metadata.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ name=Project and Template Selector
qgisMinimumVersion=3.4
qgisMaximumVersion=3.99
description=Tool for selecting pre-defined QGIS projects.
version=1.3.2
version=1.3.3
author=Dartmoor National Park Authority
email=gi@dartmoor.gov.uk
about=Tools for simplifying and automating common tasks for national parks and other protected areas.
Expand All @@ -23,7 +23,9 @@ about=Tools for simplifying and automating common tasks for national parks and o
# Optional items:

# Uncomment the following line and add your changelog entries:
changelog=1.3.2 - Bug fixes:
changelog=1.3.3 - Bug fixes:
- Fixed strings replacement within templates
<p>1.3.2 - Bug fixes:
- Added zooming to full extent after opening print layout
<p>1.3.1 - Bug fixes:
- Fixed issue #616
Expand Down
46 changes: 32 additions & 14 deletions QGIS Plugin/templateselectordialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import os
import traceback
import locale
from sys import platform
from qgis.PyQt import QtGui, uic
from qgis.PyQt.QtXml import QDomDocument
from qgis.PyQt.QtWidgets import (
Expand All @@ -44,6 +45,7 @@
QgsLayerTreeLayer,
QgsLayoutItemLegend,
QgsLayoutItemMap,
QgsLayoutItemLabel,
QgsReadWriteContext,
QgsFeature,
QgsPointXY,
Expand Down Expand Up @@ -90,9 +92,13 @@ def __init__(self, iface):

# Replacement map
self.ui.suitableForComboBox.addItem('<custom>')
self.user = os.environ.get('username', '[user]')
if platform == 'win32':
self.username = os.environ.get('username', '<username>')
else:
self.username = os.environ.get('USER', '<username>')
self.replaceMap = {
'author': "Compiled by {} on [%concat(day($now ),'/',month($now),'/',year($now))%]".format(self.user)
'username': self.username,
'author': f"Compiled by {self.username} on [%concat(day($now ),'/',month($now),'/',year($now))%]"
}
self.ui.autofit_btn.clicked.connect(self.autofit_map)
self.ui.suitableForComboBox.currentIndexChanged.connect(self.specify_dpi)
Expand Down Expand Up @@ -253,7 +259,7 @@ def populateScaleChoices(self):
locale.setlocale(locale.LC_ALL, '')
currentMapCanvasScale = self.iface.mapCanvas().scale()
scaleString = locale.format('%d', currentMapCanvasScale, grouping=True)
comboBox.addItem('%s (Current map canvas)' % scaleString)
comboBox.addItem(f'{scaleString} (Current map canvas)')
for scale in self.presetScales:
comboBox.addItem(str(scale))
self.ui.scalesGridLayout.addWidget(comboBox, i, 3)
Expand Down Expand Up @@ -329,7 +335,7 @@ def getCopyrightText(self):
self.ui.templateTypeComboBox.currentText(), 'Copyrights',
self.ui.copyrightComboBox.currentText() + '.txt')
try:
with open(copyrightFilePath, 'r') as copyrightFile:
with open(copyrightFilePath, 'r', errors='ignore') as copyrightFile:
copyrightText = copyrightFile.read().strip()
except IOError:
return ''
Expand All @@ -340,15 +346,15 @@ def openTemplate(self):
# Load replaceable text
self.replaceMap['copyright'] = self.getCopyrightText()
self.replaceMap['title'] = self.ui.titleLineEdit.text()
# not in examples, is it still supported?
self.replaceMap['subtitle'] = self.ui.subtitleLineEdit.text()
self.replaceMap['gridref'] = self.getPoiText()

for k, v in self.replaceMap.items():
item = print_layout.itemById(k)
if item:
item.setText(v)

for item in self.get_text_items(print_layout):
item_text = item.currentText()
for k, v in self.replaceMap.items():
item_text = item_text.replace(f'[{k}]', v) if v else item_text
item.setText(item_text)
gridref_item = print_layout.itemById('gridref')
if gridref_item:
gridref_item.setText(self.getPoiText())
# Update images of all maps elements in layout
if self.identifiable_only:
try:
Expand Down Expand Up @@ -419,13 +425,13 @@ def getPoiText(self):
poiLayer = layer
break
if poiLayer == None:
return 'Failed to find POI layer %s' % self.ui.poiLayerComboBox.currentText()
return 'Failed to find POI layer {}'.format(self.ui.poiLayerComboBox.currentText())
poiString = 'Grid References\n\n'
f = QgsFeature()
fit = poiLayer.getFeatures()
while fit.nextFeature(f):
gridRef = xy_to_osgb(f.geometry().centroid().asPoint()[0], f.geometry().centroid().asPoint()[1], 10)
coordText = '%s\t%s\n' % (f.attribute(self.ui.poiFieldComboBox.currentText()), gridRef)
coordText = '{}\t{}\n'.format(f.attribute(self.ui.poiFieldComboBox.currentText()), gridRef)
poiString += coordText
return poiString

Expand Down Expand Up @@ -476,3 +482,15 @@ def get_print_layout(self):
return

return print_layout

@staticmethod
def get_text_items(print_layout):
print_layout_item_model = print_layout.itemsModel()
row_count = print_layout_item_model.rowCount()
column_count = print_layout_item_model.columnCount()
for r in range(row_count):
for c in range(column_count):
index = print_layout_item_model.index(r, c)
item = print_layout_item_model.itemFromIndex(index)
if isinstance(item, QgsLayoutItemLabel):
yield item
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ This section describes how to create effective layout templates.

### String Replacement

_Template Selector_ supports automatic replacement of strings in addition to those already supported by QGIS. The following strings will automatically be replaced within layout templates:
_Template Selector_ supports automatic replacement of strings in addition to those already supported by QGIS. The following strings will automatically be replaced within layout templates labels:

- [username] : the user's username (e.g. %USERNAME%), specified as environment variable
- [author]: the user's username + compilation date info
- [title] : The _Title_ specified by the user in the above dialog
- [subtitle] : The _Sub-title_ specified by the user in the above dialog
- [copyright] : The content of the selected copyright file

NOTE: If you update from QGIS 2 print templates, in QGIS 3 it is necessary to set up 'id' fields of the items above as 'author', 'title', 'subtitle', 'copyright', respectively.
### Multiple Composer Maps

Templates with multiple layout maps are supported. Composer maps are identified by their _Item ID_ property wherever present and their scales can be set independently.
Expand Down

0 comments on commit 93337c0

Please sign in to comment.