QGIS API Documentation 3.40.0-Bratislava (b56115d8743)
Loading...
Searching...
No Matches
qgsmaplayerloadstyledialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmaplayerloadstyledialog.cpp
3 ---------------------
4 begin : April 2013
5 copyright : (C) 2013 by Emilio Loi
6 email : loi at faunalia dot it
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
16#include <QMessageBox>
17#include <QVector>
18
20#include "qgslogger.h"
21#include "qgssettings.h"
24#include "qgshelp.h"
25#include "qgsapplication.h"
26#include "qgsgui.h"
27
29 : QDialog( parent )
30 , mLayer( layer )
31{
32 setupUi( this );
34 setWindowTitle( tr( "Database Styles Manager" ) );
35
36 mDeleteButton = mButtonBox->button( QDialogButtonBox::StandardButton::Close );
37 mDeleteButton->setText( tr( "Delete Style" ) );
38 mDeleteButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteSelected.svg" ) ) );
39 mLoadButton = mButtonBox->button( QDialogButtonBox::StandardButton::Open );
40 mLoadButton->setText( tr( "Load Style" ) );
41 mCancelButton = mButtonBox->button( QDialogButtonBox::StandardButton::Cancel );
42
43 QgsSettings settings;
44
45 const QString myLastUsedDir = settings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString();
46
47 // load style type combobox
48 connect( mStyleTypeComboBox, qOverload<int>( &QComboBox::currentIndexChanged ), this, [ = ]( int )
49 {
53 mFromDbWidget->setVisible( type == QgsLayerPropertiesDialog::StyleType::DatasourceDatabase );
55
56 mStyleCategoriesListView->setEnabled( currentStyleType() != QgsLayerPropertiesDialog::StyleType::SLD );
57 updateLoadButtonState();
58 } );
59 mStyleTypeComboBox->addItem( tr( "From file" ), QgsLayerPropertiesDialog::QML ); // QML is used as entry, but works for SLD too, see currentStyleType()
60 mStyleTypeComboBox->addItem( tr( "Default from local database" ), QgsLayerPropertiesDialog::UserDatabase );
61
63 {
64 mStyleTypeComboBox->addItem( tr( "From datasource database" ), QgsLayerPropertiesDialog::StyleType::DatasourceDatabase );
65 if ( settings.value( QStringLiteral( "style/lastLoadStyleTypeSelection" ) ) == QgsLayerPropertiesDialog::StyleType::DatasourceDatabase )
66 {
67 mStyleTypeComboBox->setCurrentIndex( mStyleTypeComboBox->findData( QgsLayerPropertiesDialog::StyleType::DatasourceDatabase ) );
68 }
69 }
70
71 // fill style categories
72 mModel = new QgsMapLayerStyleCategoriesModel( mLayer->type(), this );
73 const QgsMapLayer::StyleCategories lastStyleCategories = settings.flagValue( QStringLiteral( "style/lastStyleCategories" ), QgsMapLayer::AllStyleCategories );
74 mModel->setCategories( lastStyleCategories );
75 mStyleCategoriesListView->setModel( mModel );
76 mStyleCategoriesListView->setWordWrap( true );
77 mStyleCategoriesListView->setItemDelegate( new QgsCategoryDisplayLabelDelegate( this ) );
78
79 // load from file setup
80 switch ( mLayer->type() )
81 {
83 mFileWidget->setFilter( tr( "QGIS Layer Style File, SLD File" ) + QStringLiteral( " (*.qml *.sld)" ) );
84 break;
85
87 mFileWidget->setFilter( tr( "All Styles" ) + QStringLiteral( " (*.qml *.json);;" )
88 + tr( "QGIS Layer Style File" ) + QStringLiteral( " (*.qml);;" )
89 + tr( "MapBox GL Style JSON File" ) + QStringLiteral( " (*.json)" ) );
90 break;
91
99 break;
100
101 }
102
103 mFileWidget->setStorageMode( QgsFileWidget::GetFile );
104 mFileWidget->setDefaultRoot( myLastUsedDir );
105 connect( mFileWidget, &QgsFileWidget::fileChanged, this, [ = ]( const QString & path )
106 {
107 mStyleCategoriesListView->setEnabled( currentStyleType() != QgsLayerPropertiesDialog::SLD );
108 QgsSettings settings;
109 const QFileInfo tmplFileInfo( path );
110 settings.setValue( QStringLiteral( "style/lastStyleDir" ), tmplFileInfo.absolutePath() );
111
112 updateLoadButtonState();
113 } );
114
115 // load from DB
116 mLoadButton->setDisabled( true );
117 mDeleteButton->setDisabled( true );
118 mRelatedTable->setEditTriggers( QTableWidget::NoEditTriggers );
119 mRelatedTable->horizontalHeader()->setStretchLastSection( true );
120 mRelatedTable->setSelectionBehavior( QTableWidget::SelectRows );
121 mRelatedTable->verticalHeader()->setVisible( false );
122 mOthersTable->setEditTriggers( QTableWidget::NoEditTriggers );
123 mOthersTable->horizontalHeader()->setStretchLastSection( true );
124 mOthersTable->setSelectionBehavior( QTableWidget::SelectRows );
125 mOthersTable->verticalHeader()->setVisible( false );
126 connect( mRelatedTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onRelatedTableSelectionChanged );
127 connect( mOthersTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onOthersTableSelectionChanged );
128 connect( mRelatedTable, &QTableWidget::doubleClicked, this, &QDialog::accept );
129 connect( mOthersTable, &QTableWidget::doubleClicked, this, &QDialog::accept );
130 connect( mCancelButton, &QPushButton::clicked, this, &QDialog::reject );
131 connect( mButtonBox, &QDialogButtonBox::helpRequested, this, &QgsMapLayerLoadStyleDialog::showHelp );
132 connect( mLoadButton, &QPushButton::clicked, this, &QDialog::accept );
133 connect( mDeleteButton, &QPushButton::clicked, this, &QgsMapLayerLoadStyleDialog::deleteStyleFromDB );
134 connect( this, &QgsMapLayerLoadStyleDialog::rejected, [ = ]
135 {
136 QgsSettings().setValue( QStringLiteral( "style/lastLoadStyleTypeSelection" ), currentStyleType() );
137 } );
138
139 setTabOrder( mRelatedTable, mOthersTable );
140
141 mStyleCategoriesListView->adjustSize();
142
143 // select and deselect all categories
144 connect( mSelectAllButton, &QPushButton::clicked, this, &QgsMapLayerLoadStyleDialog::selectAll );
145 connect( mDeselectAllButton, &QPushButton::clicked, this, &QgsMapLayerLoadStyleDialog::deselectAll );
146 connect( mInvertSelectionButton, &QPushButton::clicked, this, &QgsMapLayerLoadStyleDialog::invertSelection );
147}
148
149void QgsMapLayerLoadStyleDialog::invertSelection()
150{
151 for ( int i = 0; i < mModel->rowCount( QModelIndex() ); i++ )
152 {
153 QModelIndex index = mModel->index( i, 0 );
154 Qt::CheckState currentState = Qt::CheckState( mModel->data( index, Qt::CheckStateRole ).toInt() );
155 Qt::CheckState newState = ( currentState == Qt::Checked ) ? Qt::Unchecked : Qt::Checked;
156 mModel->setData( index, newState, Qt::CheckStateRole );
157 }
158}
159
160void QgsMapLayerLoadStyleDialog::selectAll()
161{
162 for ( int i = 0; i < mModel->rowCount( QModelIndex() ); i++ )
163 {
164 QModelIndex index = mModel->index( i, 0 );
165 mModel->setData( index, Qt::Checked, Qt::CheckStateRole );
166 }
167}
168
169void QgsMapLayerLoadStyleDialog::deselectAll()
170{
171 for ( int i = 0; i < mModel->rowCount( QModelIndex() ); i++ )
172 {
173 QModelIndex index = mModel->index( i, 0 );
174 mModel->setData( index, Qt::Unchecked, Qt::CheckStateRole );
175 }
176}
177
182
184{
185 QgsLayerPropertiesDialog::StyleType type = mStyleTypeComboBox->currentData().value<QgsLayerPropertiesDialog::StyleType>();
186 if ( type == QgsLayerPropertiesDialog::QML )
187 {
188 const QFileInfo fi( mFileWidget->filePath() );
189 if ( fi.exists() && fi.suffix().compare( QStringLiteral( "sld" ), Qt::CaseInsensitive ) == 0 )
191 }
192 return type;
193}
194
196{
197 return QFileInfo( mFileWidget->filePath() ).suffix();
198}
199
201{
202 return mFileWidget->filePath();
203}
204
205void QgsMapLayerLoadStyleDialog::initializeLists( const QStringList &ids, const QStringList &names, const QStringList &descriptions, int sectionLimit )
206{
207 // -1 means no ids
208 mSectionLimit = sectionLimit;
209 const int relatedTableNOfCols = sectionLimit > 0 ? 2 : 1;
210 const int othersTableNOfCols = ( sectionLimit >= 0 && ids.count() - sectionLimit > 0 ) ? 2 : 1;
211 const QString twoColsHeader( QStringLiteral( "Name;Description" ) );
212 const QString oneColsHeader( QStringLiteral( "No styles found in the database" ) );
213 const QString relatedTableHeader = relatedTableNOfCols == 1 ? oneColsHeader : twoColsHeader;
214 const QString othersTableHeader = othersTableNOfCols == 1 ? oneColsHeader : twoColsHeader;
215
216 mRelatedTable->setColumnCount( relatedTableNOfCols );
217 mOthersTable->setColumnCount( othersTableNOfCols );
218 mRelatedTable->setHorizontalHeaderLabels( relatedTableHeader.split( ';' ) );
219 mOthersTable->setHorizontalHeaderLabels( othersTableHeader.split( ';' ) );
220 mRelatedTable->setRowCount( sectionLimit );
221 mOthersTable->setRowCount( sectionLimit >= 0 ? ( ids.count() - sectionLimit ) : 0 );
222 mRelatedTable->setDisabled( relatedTableNOfCols == 1 );
223 mOthersTable->setDisabled( othersTableNOfCols == 1 );
224
225 if ( sectionLimit >= 0 )
226 {
227 for ( int i = 0; i < sectionLimit; i++ )
228 {
229 QTableWidgetItem *item = new QTableWidgetItem( names.value( i, QString() ) );
230 item->setData( Qt::UserRole, ids[i] );
231 mRelatedTable->setItem( i, 0, item );
232 mRelatedTable->setItem( i, 1, new QTableWidgetItem( descriptions.value( i, QString() ) ) );
233 }
234 for ( int i = sectionLimit; i < ids.count(); i++ )
235 {
236 const int j = i - sectionLimit;
237 QTableWidgetItem *item = new QTableWidgetItem( names.value( i, QString() ) );
238 item->setData( Qt::UserRole, ids[i] );
239 mOthersTable->setItem( j, 0, item );
240 mOthersTable->setItem( j, 1, new QTableWidgetItem( descriptions.value( i, QString() ) ) );
241 }
242 }
243}
244
246{
247 return mSelectedStyleId;
248}
249
250void QgsMapLayerLoadStyleDialog::onRelatedTableSelectionChanged()
251{
252 selectionChanged( mRelatedTable );
253 if ( mRelatedTable->selectionModel()->hasSelection() )
254 {
255 if ( mOthersTable->selectionModel()->hasSelection() )
256 {
257 disconnect( mOthersTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onOthersTableSelectionChanged );
258 const QTableWidgetSelectionRange range( 0, 0, mOthersTable->rowCount() - 1, mOthersTable->columnCount() - 1 );
259 mOthersTable->setRangeSelected( range, false );
260 connect( mOthersTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onOthersTableSelectionChanged );
261 }
262 }
263}
264
265void QgsMapLayerLoadStyleDialog::onOthersTableSelectionChanged()
266{
267 selectionChanged( mOthersTable );
268 if ( mOthersTable->selectionModel()->hasSelection() )
269 {
270 if ( mRelatedTable->selectionModel()->hasSelection() )
271 {
272 disconnect( mRelatedTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onRelatedTableSelectionChanged );
273 const QTableWidgetSelectionRange range( 0, 0, mRelatedTable->rowCount() - 1, mRelatedTable->columnCount() - 1 );
274 mRelatedTable->setRangeSelected( range, false );
275 connect( mRelatedTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsMapLayerLoadStyleDialog::onRelatedTableSelectionChanged );
276 }
277 }
278}
279
280void QgsMapLayerLoadStyleDialog::selectionChanged( QTableWidget *styleTable )
281{
282 QTableWidgetItem *item = nullptr;
283 const QList<QTableWidgetItem *> selected = styleTable->selectedItems();
284
285 if ( !selected.isEmpty() )
286 {
287 item = selected.at( 0 );
288 mSelectedStyleName = item->text();
289 mSelectedStyleId = item->data( Qt::UserRole ).toString();
290 mLoadButton->setEnabled( true );
291 mDeleteButton->setEnabled( true );
292 }
293 else
294 {
295 mSelectedStyleName.clear();
296 mSelectedStyleId.clear();
297 mLoadButton->setEnabled( false );
298 mDeleteButton->setEnabled( false );
299 }
300
301 updateLoadButtonState();
302}
303
305{
306 QgsSettings settings;
307 settings.setFlagValue( QStringLiteral( "style/lastStyleCategories" ), styleCategories() );
308 settings.setValue( QStringLiteral( "style/lastLoadStyleTypeSelection" ), currentStyleType() );
309 QDialog::accept();
310}
311
312void QgsMapLayerLoadStyleDialog::deleteStyleFromDB()
313{
314 QString msgError;
315 const QString opInfo = QObject::tr( "Delete style %1 from %2" ).arg( mSelectedStyleName, mLayer->providerType() );
316
317 if ( QMessageBox::question( nullptr, QObject::tr( "Delete Style" ),
318 QObject::tr( "Are you sure you want to delete the style %1?" ).arg( mSelectedStyleName ),
319 QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
320 return;
321
322 mLayer->deleteStyleFromDatabase( mSelectedStyleId, msgError );
323 if ( !msgError.isNull() )
324 {
325 QgsDebugError( opInfo + " failed." );
326 QMessageBox::warning( this, opInfo, tr( "%1: fail. %2" ).arg( opInfo, msgError ) );
327 }
328 else
329 {
330// QgisApp::instance()->messageBar()->pushMessage( opInfo, tr( "%1: success" ).arg( opInfo ), Qgis::MessageLevel::Info, QgisApp::instance()->messageTimeout() );
331
332 //Delete all rows from the UI table widgets
333 mRelatedTable->setRowCount( 0 );
334 mOthersTable->setRowCount( 0 );
335
336 //Fill UI widgets again from DB. Other users might have changed the styles meanwhile.
337 QString errorMsg;
338 QStringList ids, names, descriptions;
339 //get the list of styles in the db
340 const int sectionLimit = mLayer->listStylesInDatabase( ids, names, descriptions, errorMsg );
341 if ( !errorMsg.isNull() )
342 {
343 QMessageBox::warning( this, tr( "Error occurred while retrieving styles from database" ), errorMsg );
344 }
345 else
346 {
347 initializeLists( ids, names, descriptions, sectionLimit );
348 }
349 }
350}
351
352void QgsMapLayerLoadStyleDialog::updateLoadButtonState()
353{
355 mLoadButton->setEnabled( ( type == QgsLayerPropertiesDialog::DatasourceDatabase
356 && ( mRelatedTable->selectionModel()->hasSelection() || mOthersTable->selectionModel()->hasSelection()
357 ) ) ||
358 ( type != QgsLayerPropertiesDialog::DatasourceDatabase && !mFileWidget->filePath().isEmpty() ) ||
360}
361
362void QgsMapLayerLoadStyleDialog::showHelp()
363{
364 QgsHelp::openHelp( QStringLiteral( "introduction/general_tools.html#save-and-share-layer-properties" ) );
365}
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ Vector
Vector layer.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ Raster
Raster layer.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
A label delegate being able to display html encoded content.
virtual Qgis::ProviderStyleStorageCapabilities styleStorageCapabilities() const
Returns the style storage capabilities.
@ GetFile
Select a single file.
void fileChanged(const QString &path)
Emitted whenever the current file or directory path is changed.
static void enableAutoGeometryRestore(QWidget *widget, const QString &key=QString())
Register the widget to allow its position to be automatically saved and restored when open and closed...
Definition qgsgui.cpp:208
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition qgshelp.cpp:39
QgsMapLayer::StyleCategories styleCategories() const
Returns the list of selected style categories the user has opted to load.
void initializeLists(const QStringList &ids, const QStringList &names, const QStringList &descriptions, int sectionLimit)
Initialize list of database stored styles.
QString selectedStyleId()
Returns the ID of the selected database stored style.
QgsMapLayerLoadStyleDialog(QgsMapLayer *layer, QWidget *parent=nullptr)
Constructor for QgsMapLayerLoadStyleDialog, associated with the specified map layer.
QString filePath() const
Returns the full path to the selected layer style source file.
QString fileExtension() const
Returns the file extension for the selected layer style source file.
QgsLayerPropertiesDialog::StyleType currentStyleType() const
Returns the selected style type.
void setCategories(QgsMapLayer::StyleCategories categories)
Reset the model data.
QVariant data(const QModelIndex &index, int role) const override
bool setData(const QModelIndex &index, const QVariant &value, int role) override
QgsMapLayer::StyleCategories categories() const
Returns the categories as defined in the model.
int rowCount(const QModelIndex &=QModelIndex()) const override
Base class for all map layer types.
Definition qgsmaplayer.h:76
virtual bool deleteStyleFromDatabase(const QString &styleId, QString &msgError)
Deletes a style from the database.
QString providerType() const
Returns the provider type (provider key) for this layer.
virtual int listStylesInDatabase(QStringList &ids, QStringList &names, QStringList &descriptions, QString &msgError)
Lists all the style in db split into related to the layer and not related to.
Qgis::LayerType type
Definition qgsmaplayer.h:86
QFlags< StyleCategory > StyleCategories
virtual Q_INVOKABLE QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
T flagValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on a flag.
void setFlagValue(const QString &key, const T &value, const Section section=NoSection)
Set the value of a setting based on a flag.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
#define QgsDebugError(str)
Definition qgslogger.h:38