QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgsdatadefinedsizelegendwidget.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsdatadefinedsizelegendwidget.cpp
3  --------------------------------------
4  Date : June 2017
5  Copyright : (C) 2017 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
17 
18 #include <QInputDialog>
19 #include <QStyledItemDelegate>
20 
22 #include "qgslayertree.h"
23 #include "qgslayertreemodel.h"
24 #include "qgsmapcanvas.h"
26 #include "qgsstyle.h"
27 #include "qgssymbol.h"
28 #include "qgssymbollayer.h"
30 #include "qgsvectorlayer.h"
32 #include "qgsmarkersymbol.h"
33 #include "qgslinesymbol.h"
34 
36  : QgsPanelWidget( parent )
37  , mSizeProperty( ddSize )
38  , mMapCanvas( canvas )
39 {
40  setupUi( this );
41  setPanelTitle( tr( "Data-defined Size Legend" ) );
42 
43  mLineSymbolButton->setSymbolType( Qgis::SymbolType::Line );
44 
45  QgsMarkerSymbol *symbol = nullptr;
46 
47  if ( !ddsLegend )
48  {
49  radDisabled->setChecked( true );
50  }
51  else
52  {
54  radSeparated->setChecked( true );
55  else
56  radCollapsed->setChecked( true );
57 
59  cboAlignSymbols->setCurrentIndex( 0 );
60  else
61  cboAlignSymbols->setCurrentIndex( 1 );
62 
63  if ( ddsLegend->lineSymbol() )
64  mLineSymbolButton->setSymbol( ddsLegend->lineSymbol()->clone() );
65 
66  symbol = ddsLegend->symbol() ? ddsLegend->symbol()->clone() : nullptr; // may be null (undefined)
67  }
68 
69  if ( overrideSymbol )
70  {
71  symbol = overrideSymbol; // takes ownership
72  mOverrideSymbol = true;
73  }
74 
75  if ( !symbol )
76  {
77  symbol = QgsMarkerSymbol::createSimple( QVariantMap() );
78  }
79  mSourceSymbol.reset( symbol );
80 
81  btnChangeSymbol->setEnabled( !mOverrideSymbol );
82 
83  QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( mSourceSymbol.get(), btnChangeSymbol->iconSize() );
84  btnChangeSymbol->setIcon( icon );
85 
86  editTitle->setText( ddsLegend ? ddsLegend->title() : QString() );
87 
88  mSizeClassesModel = new QStandardItemModel( viewSizeClasses );
89  mSizeClassesModel->setHorizontalHeaderLabels( QStringList() << tr( "Value" ) << tr( "Label" ) );
90  mSizeClassesModel->setSortRole( Qt::UserRole + 1 );
91  if ( ddsLegend )
92  {
93  groupManualSizeClasses->setChecked( !ddsLegend->classes().isEmpty() );
94  const auto constClasses = ddsLegend->classes();
95  for ( const QgsDataDefinedSizeLegend::SizeClass &sc : constClasses )
96  {
97  QStandardItem *item = new QStandardItem( QString::number( sc.size ) );
98  item->setData( sc.size );
99  QStandardItem *itemLabel = new QStandardItem( sc.label );
100  mSizeClassesModel->appendRow( QList<QStandardItem *>() << item << itemLabel );
101  }
102  mSizeClassesModel->sort( 0 );
103  }
104 
105  connect( btnAddClass, &QToolButton::clicked, this, &QgsDataDefinedSizeLegendWidget::addSizeClass );
106  connect( btnRemoveClass, &QToolButton::clicked, this, &QgsDataDefinedSizeLegendWidget::removeSizeClass );
107 
108  viewSizeClasses->setItemDelegateForColumn( 0, new SizeClassDelegate( viewSizeClasses ) );
109  viewSizeClasses->setModel( mSizeClassesModel );
110  connect( mSizeClassesModel, &QStandardItemModel::dataChanged, this, &QgsDataDefinedSizeLegendWidget::onSizeClassesChanged );
111 
112  // prepare layer and model to preview legend
114  mPreviewLayer = new QgsVectorLayer( QStringLiteral( "Point?crs=EPSG:4326" ), QStringLiteral( "Preview" ), QStringLiteral( "memory" ), options );
115  mPreviewTree = new QgsLayerTree;
116  mPreviewLayerNode = mPreviewTree->addLayer( mPreviewLayer ); // node owned by the tree
117  mPreviewModel = new QgsLayerTreeModel( mPreviewTree );
118  if ( canvas )
119  mPreviewModel->setLegendMapViewData( canvas->mapUnitsPerPixel(), canvas->mapSettings().outputDpi(), canvas->scale() );
120  viewLayerTree->setModel( mPreviewModel );
121 
122  connect( cboAlignSymbols, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, [ = ] { emit widgetChanged(); } );
123  connect( radDisabled, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
124  connect( radSeparated, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
125  connect( radCollapsed, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
126  connect( groupManualSizeClasses, &QGroupBox::clicked, this, &QgsPanelWidget::widgetChanged );
127  connect( btnChangeSymbol, &QPushButton::clicked, this, &QgsDataDefinedSizeLegendWidget::changeSymbol );
128  connect( editTitle, &QLineEdit::textChanged, this, &QgsPanelWidget::widgetChanged );
129  connect( mLineSymbolButton, &QgsSymbolButton::changed, this, &QgsPanelWidget::widgetChanged );
130  connect( this, &QgsPanelWidget::widgetChanged, this, &QgsDataDefinedSizeLegendWidget::updatePreview );
131  updatePreview();
132 }
133 
135 {
136  delete mPreviewModel;
137  delete mPreviewTree;
138  delete mPreviewLayer;
139 }
140 
142 {
143  if ( radDisabled->isChecked() )
144  return nullptr;
145 
148  ddsLegend->setVerticalAlignment( cboAlignSymbols->currentIndex() == 0 ? QgsDataDefinedSizeLegend::AlignBottom : QgsDataDefinedSizeLegend::AlignCenter );
149  if ( !mOverrideSymbol )
150  {
151  ddsLegend->setSymbol( mSourceSymbol->clone() );
152  }
153 
154  ddsLegend->setTitle( editTitle->text() );
155 
156  if ( groupManualSizeClasses->isChecked() )
157  {
158  QList<QgsDataDefinedSizeLegend::SizeClass> classes;
159  for ( int i = 0; i < mSizeClassesModel->rowCount(); ++i )
160  {
161  double value = mSizeClassesModel->item( i, 0 )->data().toDouble();
162  QString label = mSizeClassesModel->item( i, 1 )->text();
163  classes << QgsDataDefinedSizeLegend::SizeClass( value, label );
164  }
165  ddsLegend->setClasses( classes );
166  }
167 
168  ddsLegend->setLineSymbol( mLineSymbolButton->clonedSymbol< QgsLineSymbol >() );
169  return ddsLegend;
170 }
171 
172 void QgsDataDefinedSizeLegendWidget::updatePreview()
173 {
174  QgsMarkerSymbol *symbol = mSourceSymbol->clone();
175  symbol->setDataDefinedSize( mSizeProperty );
178  mPreviewLayer->setRenderer( r );
179  mPreviewModel->refreshLayerLegend( mPreviewLayerNode );
180  viewLayerTree->expandAll();
181 }
182 
183 void QgsDataDefinedSizeLegendWidget::changeSymbol()
184 {
185  std::unique_ptr<QgsMarkerSymbol> newSymbol( mSourceSymbol->clone() );
186  QgsSymbolWidgetContext context;
187  if ( mMapCanvas )
188  context.setMapCanvas( mMapCanvas );
189 
194  if ( mMapCanvas )
196  context.setExpressionContext( &ec );
197 
198  QString crsAuthId = mMapCanvas ? mMapCanvas->mapSettings().destinationCrs().authid() : QString();
200  std::unique_ptr<QgsVectorLayer> layer = std::make_unique<QgsVectorLayer>( QStringLiteral( "Point?crs=%1" ).arg( crsAuthId ),
201  QStringLiteral( "tmp" ),
202  QStringLiteral( "memory" ),
203  options ) ;
204 
205  QgsSymbolSelectorDialog d( newSymbol.get(), QgsStyle::defaultStyle(), layer.get(), this );
206  d.setContext( context );
207 
208  if ( d.exec() != QDialog::Accepted )
209  return;
210 
211  mSourceSymbol = std::move( newSymbol );
212  QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( mSourceSymbol.get(), btnChangeSymbol->iconSize() );
213  btnChangeSymbol->setIcon( icon );
214 
215  emit widgetChanged();
216 }
217 
218 void QgsDataDefinedSizeLegendWidget::addSizeClass()
219 {
220  bool ok;
221  double v = QInputDialog::getDouble( this, tr( "Add Size Class" ), tr( "Enter value for a new class" ),
222  0, -2147483647, 2147483647, 6, &ok );
223  if ( !ok )
224  return;
225 
226  QStandardItem *item = new QStandardItem( QString::number( v ) );
227  item->setData( v );
228  QStandardItem *itemLabel = new QStandardItem( QString::number( v ) );
229  mSizeClassesModel->appendRow( QList<QStandardItem *>() << item << itemLabel );
230  mSizeClassesModel->sort( 0 );
231  emit widgetChanged();
232 }
233 
234 void QgsDataDefinedSizeLegendWidget::removeSizeClass()
235 {
236  QModelIndex idx = viewSizeClasses->currentIndex();
237  if ( !idx.isValid() )
238  return;
239 
240  mSizeClassesModel->removeRow( idx.row() );
241  emit widgetChanged();
242 }
243 
244 void QgsDataDefinedSizeLegendWidget::onSizeClassesChanged()
245 {
246  for ( int row = 0; row < mSizeClassesModel->rowCount(); ++row )
247  {
248  QStandardItem *item = mSizeClassesModel->item( row, 0 );
249  item->setData( item->text().toDouble() );
250  }
251 
252  mSizeClassesModel->sort( 0 );
253  emit widgetChanged();
254 }
@ Line
Line symbol.
QString authid() const
Returns the authority identifier for the CRS.
QgsDataDefinedSizeLegendWidget(const QgsDataDefinedSizeLegend *ddsLegend, const QgsProperty &ddSize, QgsMarkerSymbol *overrideSymbol, QgsMapCanvas *canvas=nullptr, QWidget *parent=nullptr)
Creates the dialog and initializes the content to what is passed in the legend configuration (may be ...
QgsDataDefinedSizeLegend * dataDefinedSizeLegend() const
Returns configuration as set up in the dialog (may be nullptr). Ownership is passed to the caller.
Object that keeps configuration of appearance of marker symbol's data-defined size in legend.
void setTitle(const QString &title)
Sets title label for data-defined size legend.
QList< QgsDataDefinedSizeLegend::SizeClass > classes() const
Returns list of classes: each class is a pair of symbol size (in units used by the symbol) and label.
void setSymbol(QgsMarkerSymbol *symbol SIP_TRANSFER)
Sets marker symbol that will be used to draw markers in legend.
void setVerticalAlignment(VerticalAlignment vAlign)
Sets vertical alignment of symbols - only valid for collapsed legend.
void setLineSymbol(QgsLineSymbol *symbol SIP_TRANSFER)
Sets the line symbol that will be used to draw callout lines in legend.
LegendType legendType() const
Returns how the legend should be rendered.
QgsMarkerSymbol * symbol() const
Returns marker symbol that will be used to draw markers in legend.
@ AlignCenter
Symbols are aligned to the center.
@ AlignBottom
Symbols are aligned to the bottom.
void setClasses(const QList< QgsDataDefinedSizeLegend::SizeClass > &classes)
Sets list of classes: each class is a pair of symbol size (in units used by the symbol) and label.
void setLegendType(LegendType type)
Sets how the legend should be rendered.
QString title() const
Returns title label for data-defined size legend.
@ LegendSeparated
Each class (size value) has a separate legend node.
@ LegendCollapsed
All classes are rendered within one legend node.
QgsLineSymbol * lineSymbol() const
Returns the line symbol that will be used to draw callout lines in legend.
VerticalAlignment verticalAlignment() const
Returns vertical alignment of symbols - only valid for collapsed legend.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
static QgsExpressionContextScope * mapSettingsScope(const QgsMapSettings &mapSettings)
Creates a new scope which contains variables and functions relating to a QgsMapSettings object.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsLayerTreeLayer * addLayer(QgsMapLayer *layer)
Append a new layer node for given map layer.
The QgsLayerTreeModel class is model implementation for Qt item views framework.
void setLegendMapViewData(double mapUnitsPerPixel, int dpi, double scale)
Give the layer tree model hints about the currently associated map view so that legend nodes that use...
void refreshLayerLegend(QgsLayerTreeLayer *nodeLayer)
Force a refresh of legend nodes of a layer node.
Namespace with helper functions for layer tree operations.
Definition: qgslayertree.h:33
A line symbol type, for rendering LineString and MultiLineString geometries.
Definition: qgslinesymbol.h:30
QgsLineSymbol * clone() const override
Returns a deep copy of this symbol.
Map canvas is a class for displaying all GIS data types on a canvas.
Definition: qgsmapcanvas.h:86
double scale() const
Returns the last reported scale of the canvas.
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
double outputDpi() const
Returns the DPI (dots per inch) used for conversion between real world units (e.g.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
A marker symbol type, for rendering Point and MultiPoint geometries.
static QgsMarkerSymbol * createSimple(const QVariantMap &properties)
Create a marker symbol with one symbol layer: SimpleMarker with specified properties.
void setDataDefinedSize(const QgsProperty &property)
Set data defined size for whole symbol (including all symbol layers).
QgsMarkerSymbol * clone() const override
Returns a deep copy of this symbol.
Base class for any widget that can be shown as a inline panel.
void widgetChanged()
Emitted when the widget state changes.
void setPanelTitle(const QString &panelTitle)
Set the title of the panel when shown in the interface.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:467
QgsCoordinateTransformContext transformContext
Definition: qgsproject.h:105
A store for object properties.
Definition: qgsproperty.h:232
void setDataDefinedSizeLegend(QgsDataDefinedSizeLegend *settings)
Configures appearance of legend when renderer is configured to use data-defined size for marker symbo...
static QgsStyle * defaultStyle()
Returns default application-wide style.
Definition: qgsstyle.cpp:131
void changed()
Emitted when the symbol's settings are changed.
static QIcon symbolPreviewIcon(const QgsSymbol *symbol, QSize size, int padding=0, QgsLegendPatchShape *shape=nullptr)
Returns an icon preview for a color ramp.
Contains settings which reflect the context in which a symbol (or renderer) widget is shown,...
void setMapCanvas(QgsMapCanvas *canvas)
Sets the map canvas associated with the widget.
void setExpressionContext(QgsExpressionContext *context)
Sets the optional expression context used for the widget.
Represents a vector layer which manages a vector based data sets.
void setRenderer(QgsFeatureRenderer *r)
Sets the feature renderer which will be invoked to represent this layer in 2D map views.
Definition of one class for the legend.
Setting options for loading vector layers.