Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport release-3_40] Fix data-defined overrides ignored in legend text format #60662

Merged
merged 4 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions python/PyQt6/core/auto_generated/qgslegendsettings.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ The content of the legend is driven by the :py:class:`QgsLegendModel` class.
public:
QgsLegendSettings();

void updateDataDefinedProperties( QgsRenderContext &context );
%Docstring
Updates any data-defined properties in the settings, using the specified
render ``context``.

.. versionadded:: 3.42
%End

void setTitle( const QString &t );
%Docstring
Sets the title for the legend, which will be rendered above all legend items.
Expand Down
8 changes: 8 additions & 0 deletions python/PyQt6/core/auto_generated/qgslegendstyle.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,14 @@ Writes the component's style definition to an XML element.
Reads the component's style definition from an XML element.

.. seealso:: :py:func:`writeXml`
%End

void updateDataDefinedProperties( QgsRenderContext &context );
%Docstring
Updates any data-defined properties in the style, using the specified
render ``context``.

.. versionadded:: 3.42
%End

static QString styleName( Style s );
Expand Down
8 changes: 8 additions & 0 deletions python/core/auto_generated/qgslegendsettings.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ The content of the legend is driven by the :py:class:`QgsLegendModel` class.
public:
QgsLegendSettings();

void updateDataDefinedProperties( QgsRenderContext &context );
%Docstring
Updates any data-defined properties in the settings, using the specified
render ``context``.

.. versionadded:: 3.42
%End

void setTitle( const QString &t );
%Docstring
Sets the title for the legend, which will be rendered above all legend items.
Expand Down
8 changes: 8 additions & 0 deletions python/core/auto_generated/qgslegendstyle.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,14 @@ Writes the component's style definition to an XML element.
Reads the component's style definition from an XML element.

.. seealso:: :py:func:`writeXml`
%End

void updateDataDefinedProperties( QgsRenderContext &context );
%Docstring
Updates any data-defined properties in the style, using the specified
render ``context``.

.. versionadded:: 3.42
%End

static QString styleName( Style s );
Expand Down
2 changes: 2 additions & 0 deletions src/core/qgslegendrenderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ QSizeF QgsLegendRenderer::paintAndDetermineSize( QgsRenderContext &context )
if ( !rootGroup )
return size;

mSettings.updateDataDefinedProperties( context );

// temporarily remove painter from context -- we don't need to actually draw anything yet. But we DO need
// to send the full render context so that an expression context is available during the size calculation
QgsScopedRenderContextPainterSwap noPainter( context, nullptr );
Expand Down
8 changes: 8 additions & 0 deletions src/core/qgslegendsettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ QgsLegendSettings::QgsLegendSettings()
rstyle( QgsLegendStyle::SymbolLabel ).setTextFormat( f );
}

void QgsLegendSettings::updateDataDefinedProperties( QgsRenderContext &context )
{
rstyle( QgsLegendStyle::Title ).updateDataDefinedProperties( context );
rstyle( QgsLegendStyle::Group ).updateDataDefinedProperties( context );
rstyle( QgsLegendStyle::Subgroup ).updateDataDefinedProperties( context );
rstyle( QgsLegendStyle::SymbolLabel ).updateDataDefinedProperties( context );
}

QColor QgsLegendSettings::fontColor() const
{
return style( QgsLegendStyle::SymbolLabel ).textFormat().color();
Expand Down
8 changes: 8 additions & 0 deletions src/core/qgslegendsettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ class CORE_EXPORT QgsLegendSettings
public:
QgsLegendSettings();

/**
* Updates any data-defined properties in the settings, using the specified
* render \a context.
*
* \since QGIS 3.42
*/
void updateDataDefinedProperties( QgsRenderContext &context );

/**
* Sets the title for the legend, which will be rendered above all legend items.
*
Expand Down
8 changes: 8 additions & 0 deletions src/core/qgslegendstyle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "qgsfontutils.h"
#include "qgis.h"
#include "qgsreadwritecontext.h"
#include "qgspropertycollection.h"

#include <QFont>
#include <QMap>
Expand Down Expand Up @@ -110,6 +111,13 @@ void QgsLegendStyle::readXml( const QDomElement &elem, const QDomDocument &doc,
mIndent = elem.attribute( QStringLiteral( "indent" ), QStringLiteral( "0" ) ).toDouble();
}

void QgsLegendStyle::updateDataDefinedProperties( QgsRenderContext &context )
{
if ( mTextFormat.dataDefinedProperties().hasActiveProperties() ) // note, we use format instead of tmpFormat here, it's const and potentially avoids a detach
mTextFormat.updateDataDefinedProperties( context );

}

QString QgsLegendStyle::styleName( Style s )
{
switch ( s )
Expand Down
8 changes: 8 additions & 0 deletions src/core/qgslegendstyle.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,14 @@ class CORE_EXPORT QgsLegendStyle
*/
void readXml( const QDomElement &elem, const QDomDocument &doc, const QgsReadWriteContext &context = QgsReadWriteContext() );

/**
* Updates any data-defined properties in the style, using the specified
* render \a context.
*
* \since QGIS 3.42
*/
void updateDataDefinedProperties( QgsRenderContext &context );

/**
* Returns the name for a style component as a string.
*
Expand Down
41 changes: 41 additions & 0 deletions tests/src/core/testqgslegendrenderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ class TestQgsLegendRenderer : public QgsTest
void testLeftAlignTextRightAlignSymbol();
void testCenterAlignTextRightAlignSymbol();
void testRightAlignTextRightAlignSymbol();
void testDataDefinedTextFormat();

void testGroupHeadingSpacing();
void testGroupIndentSetup();
Expand Down Expand Up @@ -739,6 +740,46 @@ void TestQgsLegendRenderer::testRightAlignTextRightAlignSymbol()
QVERIFY( _verifyImage( res, QStringLiteral( "legend_two_cols_right_align_symbol_right_align_text" ) ) );
}

void TestQgsLegendRenderer::testDataDefinedTextFormat()
{
QgsMarkerSymbol *sym = new QgsMarkerSymbol();
sym->setColor( Qt::red );
sym->setSize( sym->size() * 6 );
QgsCategorizedSymbolRenderer *catRenderer = dynamic_cast<QgsCategorizedSymbolRenderer *>( mVL3->renderer() );
QVERIFY( catRenderer );
catRenderer->updateCategorySymbol( 0, sym );

QgsLayerTreeModel legendModel( mRoot );
QgsLegendSettings settings;

setStandardTestFont( settings, QStringLiteral( "Bold" ) );
QgsTextFormat format = settings.style( QgsLegendStyle::Group ).textFormat();
format.dataDefinedProperties().setProperty( QgsPalLayerSettings::Property::Color, QgsProperty::fromExpression( "@text_color_group" ) );
settings.rstyle( QgsLegendStyle::Group ).setTextFormat( format );

format = settings.style( QgsLegendStyle::Subgroup ).textFormat();
format.dataDefinedProperties().setProperty( QgsPalLayerSettings::Property::Color, QgsProperty::fromExpression( "@text_color_subgroup" ) );
settings.rstyle( QgsLegendStyle::Subgroup ).setTextFormat( format );

format = settings.style( QgsLegendStyle::SymbolLabel ).textFormat();
format.dataDefinedProperties().setProperty( QgsPalLayerSettings::Property::Color, QgsProperty::fromExpression( "@text_color_symbol_label" ) );
settings.rstyle( QgsLegendStyle::SymbolLabel ).setTextFormat( format );

QgsExpressionContext context;
QgsExpressionContextScope *scope = new QgsExpressionContextScope();
scope->setVariable( QStringLiteral( "text_color_group" ), QStringLiteral( "255,0,0" ) );
scope->setVariable( QStringLiteral( "text_color_subgroup" ), QStringLiteral( "0,255,255" ) );
scope->setVariable( QStringLiteral( "text_color_symbol_label" ), QStringLiteral( "255,0,255" ) );
context.appendScope( scope );

QgsRenderContext rc;
rc.setExpressionContext( context );
settings.updateDataDefinedProperties( rc );

QImage res = renderLegend( &legendModel, settings );
QVERIFY( _verifyImage( res, QStringLiteral( "data_defined_text_format" ) ) );
}

void TestQgsLegendRenderer::testGroupHeadingSpacing()
{
QgsMarkerSymbol *sym = new QgsMarkerSymbol();
Expand Down
2 changes: 2 additions & 0 deletions tests/src/python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ ADD_PYTHON_TEST(PyQgsLayoutSnapper test_qgslayoutsnapper.py)
ADD_PYTHON_TEST(PyQgsLayoutTable test_qgslayouttable.py)
ADD_PYTHON_TEST(PyQgsLegendPatchShape test_qgslegendpatchshape.py)
ADD_PYTHON_TEST(PyQgsLegendRenderer test_qgslegendrenderer.py)
ADD_PYTHON_TEST(PyQgsLegendSettings test_qgslegendsettings.py)
ADD_PYTHON_TEST(PyQgsLegendStyle test_qgslegendstyle.py)
ADD_PYTHON_TEST(PyQgsLinearReferencingSymbolLayer test_qgslinearreferencingsymbollayer.py)
ADD_PYTHON_TEST(PyQgsLineSegment test_qgslinesegment.py)
ADD_PYTHON_TEST(PyQgsLineString test_qgslinestring.py)
Expand Down
188 changes: 188 additions & 0 deletions tests/src/python/test_qgslegendsettings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
""""Test QgsLegendSettings

.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Run with ctest -V -R PyQgsLegendSettings

"""

from qgis.PyQt.QtCore import Qt, QSizeF
from qgis.PyQt.QtGui import QColor

from qgis.core import (
Qgis,
QgsLegendStyle,
QgsLegendSettings,
QgsExpressionContext,
QgsExpressionContextScope,
QgsTextFormat,
QgsRenderContext,
QgsPalLayerSettings,
QgsProperty,
)
import unittest
from qgis.testing import start_app, QgisTestCase

from utilities import unitTestDataPath

QGISAPP = start_app()
TEST_DATA_DIR = unitTestDataPath()


class TestPyQgsLegendSettings(QgisTestCase):

def test_getters_setters(self):
settings = QgsLegendSettings()

title = "Test Legend"
settings.setTitle(title)
self.assertEqual(settings.title(), title)

settings.setTitleAlignment(Qt.AlignmentFlag.AlignRight)
self.assertEqual(settings.titleAlignment(), Qt.AlignmentFlag.AlignRight)

test_style = QgsLegendStyle()
test_style.setIndent(33)
settings.setStyle(QgsLegendStyle.Style.Symbol, test_style)
self.assertEqual(settings.style(QgsLegendStyle.Style.Symbol).indent(), 33)

test_style2 = QgsLegendStyle()
test_style2.setIndent(35)
settings.setStyle(QgsLegendStyle.Style.SymbolLabel, test_style2)
self.assertEqual(settings.style(QgsLegendStyle.Style.Symbol).indent(), 33)
self.assertEqual(settings.style(QgsLegendStyle.Style.SymbolLabel).indent(), 35)

settings.setBoxSpace(5.0)
self.assertEqual(settings.boxSpace(), 5.0)

settings.setWrapChar("\n")
self.assertEqual(settings.wrapChar(), "\n")

settings.setColumnSpace(5.0)
self.assertEqual(settings.columnSpace(), 5.0)

settings.setColumnCount(3)
self.assertEqual(settings.columnCount(), 3)

settings.setSplitLayer(True)
self.assertTrue(settings.splitLayer())
settings.setSplitLayer(False)
self.assertFalse(settings.splitLayer())

settings.setEqualColumnWidth(True)
self.assertTrue(settings.equalColumnWidth())
settings.setEqualColumnWidth(False)
self.assertFalse(settings.equalColumnWidth())

settings.setSymbolSize(QSizeF(10.0, 10.0))
self.assertEqual(settings.symbolSize(), QSizeF(10.0, 10.0))
settings.setMaximumSymbolSize(20.0)
settings.setMinimumSymbolSize(5.0)
self.assertEqual(settings.maximumSymbolSize(), 20.0)
self.assertEqual(settings.minimumSymbolSize(), 5.0)

settings.setSymbolAlignment(Qt.AlignmentFlag.AlignRight)
self.assertEqual(settings.symbolAlignment(), Qt.AlignmentFlag.AlignRight)

settings.setDrawRasterStroke(True)
self.assertTrue(settings.drawRasterStroke())

settings.setRasterStrokeColor(QColor(255, 0, 0))
self.assertEqual(settings.rasterStrokeColor(), QColor(255, 0, 0))

settings.setRasterStrokeWidth(2.0)
self.assertEqual(settings.rasterStrokeWidth(), 2.0)

settings.setWmsLegendSize(QSizeF(50.0, 150.0))
self.assertEqual(settings.wmsLegendSize(), QSizeF(50.0, 150.0))

settings.setSynchronousLegendRequests(True)
self.assertTrue(settings.synchronousLegendRequests())
settings.setSynchronousLegendRequests(False)
self.assertFalse(settings.synchronousLegendRequests())

settings.setJsonRenderFlags(Qgis.LegendJsonRenderFlag.ShowRuleDetails)
self.assertEqual(
settings.jsonRenderFlags(), Qgis.LegendJsonRenderFlag.ShowRuleDetails
)

def test_split_string_for_wrapping(self):
settings = QgsLegendSettings()
settings.setWrapChar("|")
self.assertEqual(
settings.splitStringForWrapping("Test|String|Wrapping"),
["Test", "String", "Wrapping"],
)

def test_evaluate_item_text(self):
settings = QgsLegendSettings()
settings.setWrapChar("|")

expression_context_scope = QgsExpressionContextScope()
expression_context_scope.setVariable("test_string", "Test|String")
expression_context = QgsExpressionContext()
expression_context.appendScope(expression_context_scope)

self.assertEqual(
settings.evaluateItemText(
"[% @test_string %]|Wrapping", expression_context
),
["Test", "String", "Wrapping"],
)

def test_update_data_defined_properties(self):
style = QgsLegendStyle()
text_format = QgsTextFormat()
text_format.setColor(QColor(255, 0, 0, 255))
text_format.dataDefinedProperties().setProperty(
QgsPalLayerSettings.Property.Color,
QgsProperty.fromExpression("@text_color"),
)
style.setTextFormat(text_format)
settings = QgsLegendSettings()
settings.setStyle(QgsLegendStyle.Style.Group, style)

style2 = QgsLegendStyle()
text_format = QgsTextFormat()
text_format.setColor(QColor(255, 0, 255, 255))
text_format.dataDefinedProperties().setProperty(
QgsPalLayerSettings.Property.Color,
QgsProperty.fromExpression("@text_color2"),
)
style2.setTextFormat(text_format)
settings.setStyle(QgsLegendStyle.Style.Subgroup, style2)

self.assertEqual(
settings.style(QgsLegendStyle.Style.Group).textFormat().color(),
QColor(255, 0, 0, 255),
)
self.assertEqual(
settings.style(QgsLegendStyle.Style.Subgroup).textFormat().color(),
QColor(255, 0, 255, 255),
)

# apply data defined properties
rc = QgsRenderContext()
expression_context_scope = QgsExpressionContextScope()
expression_context_scope.setVariable("text_color", "0,255,0")
expression_context_scope.setVariable("text_color2", "255,255,255")
expression_context = QgsExpressionContext()
expression_context.appendScope(expression_context_scope)
rc.setExpressionContext(expression_context)
settings.updateDataDefinedProperties(rc)

self.assertEqual(
settings.style(QgsLegendStyle.Style.Group).textFormat().color(),
QColor(0, 255, 0, 255),
)
self.assertEqual(
settings.style(QgsLegendStyle.Style.Subgroup).textFormat().color(),
QColor(255, 255, 255, 255),
)


if __name__ == "__main__":
unittest.main()
Loading
Loading