QGIS API Documentation 3.41.0-Master (cea29feecf2)
Loading...
Searching...
No Matches
qgssublayersdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgssublayersdialog.cpp - dialog for selecting sublayers
3 ---------------------
4 begin : January 2009
5 copyright : (C) 2009 by Florian El Ahdab
6 email : felahdab 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
16#include "qgssublayersdialog.h"
17#include "moc_qgssublayersdialog.cpp"
18#include "qgslogger.h"
19#include "qgssettings.h"
20#include "qgsgui.h"
21#include "qgsproviderregistry.h"
22
23#include <QTableWidgetItem>
24#include <QPushButton>
25
27class SubLayerItem : public QTreeWidgetItem
28{
29 public:
30 SubLayerItem( const QStringList &strings, int type = QTreeWidgetItem::Type )
31 : QTreeWidgetItem( strings, type )
32 {}
33
34 bool operator<( const QTreeWidgetItem &other ) const override
35 {
36 QgsSublayersDialog *d = qobject_cast<QgsSublayersDialog *>( treeWidget()->parent() );
37 const int col = treeWidget()->sortColumn();
38
39 if ( col == 0 || ( col > 0 && d->countColumn() == col ) )
40 return text( col ).toInt() < other.text( col ).toInt();
41 else
42 return text( col ) < other.text( col );
43 }
44};
46
47QgsSublayersDialog::QgsSublayersDialog( ProviderType providerType, const QString &name, QWidget *parent, Qt::WindowFlags fl, const QString &dataSourceUri )
48 : QDialog( parent, fl )
49 , mName( name )
50{
51 setupUi( this );
53
54 QString title;
55 switch ( providerType )
56 {
58 title = tr( "Select Vector Layers to Add…" );
59 layersTable->setHeaderLabels( QStringList() << tr( "Layer ID" ) << tr( "Layer name" ) << tr( "Number of features" ) << tr( "Geometry type" ) << tr( "Description" ) );
60 mShowCount = true;
61 mShowType = true;
62 mShowDescription = true;
63 break;
65 title = tr( "Select Raster Layers to Add…" );
66 layersTable->setHeaderLabels( QStringList() << tr( "Layer ID" ) << tr( "Layer name" ) );
67 break;
69 title = tr( "Select Mesh Layers to Add…" );
70 layersTable->setHeaderLabels( QStringList() << tr( "Layer ID" ) << tr( "Mesh name" ) );
71 break;
72 default:
73 title = tr( "Select Layers to Add…" );
74 layersTable->setHeaderLabels( QStringList() << tr( "Layer ID" ) << tr( "Layer name" ) << tr( "Type" ) );
75 mShowType = true;
76 }
77
78 const QVariantMap dataSourceUriParsed = QgsProviderRegistry::instance()->decodeUri( name, dataSourceUri );
79 const QString dataSourceFilePath = dataSourceUriParsed.value( QStringLiteral( "path" ) ).toString();
80 const QString filePath = dataSourceFilePath.isEmpty() ? dataSourceUri : dataSourceFilePath;
81 const QString fileName = QFileInfo( filePath ).fileName();
82
83 setWindowTitle( fileName.isEmpty() ? title : QStringLiteral( "%1 | %2" ).arg( title, fileName ) );
84 mLblFilePath->setText( QDir::toNativeSeparators( QFileInfo( filePath ).canonicalFilePath() ) );
85 mLblFilePath->setVisible( !fileName.isEmpty() );
86
87 // add a "Select All" button - would be nicer with an icon
88 connect( mBtnSelectAll, &QAbstractButton::pressed, layersTable, &QTreeView::selectAll );
89 connect( mBtnDeselectAll, &QAbstractButton::pressed, this, &QgsSublayersDialog::mBtnDeselectAll_pressed );
90 connect( layersTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsSublayersDialog::layersTable_selectionChanged );
91
92 mCbxAddToGroup->setVisible( false );
93}
94
96{
97 QgsSettings settings;
98 settings.setValue( "/Windows/" + mName + "SubLayers/headerColumnCount", layersTable->columnCount() );
99 settings.setValue( "/Windows/" + mName + "SubLayers/headerState", layersTable->header()->saveState() );
100}
101
102static bool _isLayerIdUnique( int layerId, QTreeWidget *layersTable )
103{
104 int count = 0;
105 for ( int j = 0; j < layersTable->topLevelItemCount(); j++ )
106 {
107 if ( layersTable->topLevelItem( j )->text( 0 ).toInt() == layerId )
108 {
109 count++;
110 }
111 }
112 return count == 1;
113}
114
116{
118 for ( int i = 0; i < layersTable->selectedItems().size(); i++ )
119 {
120 QTreeWidgetItem *item = layersTable->selectedItems().at( i );
121
122 LayerDefinition def;
123 def.layerId = item->text( 0 ).toInt();
124 def.layerName = item->text( 1 );
125 if ( mShowType )
126 {
127 // If there are more sub layers of the same name (virtual for geometry types),
128 // add geometry type
129 if ( !_isLayerIdUnique( def.layerId, layersTable ) )
130 def.type = item->text( mShowCount ? 3 : 2 );
131 }
132
133 list << def;
134 }
135 return list;
136}
137
138
140{
141 const auto constList = list;
142 for ( const LayerDefinition &item : constList )
143 {
144 QStringList elements;
145 elements << QString::number( item.layerId ) << item.layerName;
146 if ( mShowCount )
147 elements << ( item.count == static_cast<int>( Qgis::FeatureCountState::Uncounted ) || item.count == static_cast<int>( Qgis::FeatureCountState::UnknownCount ) ? tr( "Unknown" ) : QString::number( item.count ) );
148 if ( mShowType )
149 elements << item.type;
150 if ( mShowDescription )
151 elements << item.description;
152 layersTable->addTopLevelItem( new SubLayerItem( elements ) );
153 }
154
155 // resize columns
156 const QgsSettings settings;
157 const QByteArray ba = settings.value( "/Windows/" + mName + "SubLayers/headerState" ).toByteArray();
158 const int savedColumnCount = settings.value( "/Windows/" + mName + "SubLayers/headerColumnCount" ).toInt();
159 if ( !ba.isNull() && savedColumnCount == layersTable->columnCount() )
160 {
161 layersTable->header()->restoreState( ba );
162 }
163 else
164 {
165 for ( int i = 0; i < layersTable->columnCount(); i++ )
166 layersTable->resizeColumnToContents( i );
167 layersTable->setColumnWidth( 1, layersTable->columnWidth( 1 ) + 10 );
168 }
169}
170
171// override exec() instead of using showEvent()
172// because in some case we don't want the dialog to appear (depending on user settings)
173// TODO alert the user when dialog is not opened
175{
176 QgsSettings settings;
177 const Qgis::SublayerPromptMode promptLayers = settings.enumValue( QStringLiteral( "qgis/promptForSublayers" ), Qgis::SublayerPromptMode::AlwaysAsk );
178
179 // make sure three are sublayers to choose
180 if ( layersTable->topLevelItemCount() == 0 )
181 return QDialog::Rejected;
182
183 layersTable->selectAll();
184
185 // check promptForSublayers settings - perhaps this should be in QgsDataSource instead?
186 if ( promptLayers == Qgis::SublayerPromptMode::NeverAskSkip )
187 return QDialog::Rejected;
188 else if ( promptLayers == Qgis::SublayerPromptMode::NeverAskLoadAll )
189 return QDialog::Accepted;
190
191 // if there is only 1 sublayer (probably the main layer), just select that one and return
192 if ( layersTable->topLevelItemCount() == 1 )
193 return QDialog::Accepted;
194
195 layersTable->sortByColumn( 1, Qt::AscendingOrder );
196 layersTable->setSortingEnabled( true );
197
198 // if we got here, disable override cursor, open dialog and return result
199 // TODO add override cursor where it is missing (e.g. when opening via "Add Raster")
200 QCursor cursor;
201 const bool overrideCursor = nullptr != QApplication::overrideCursor();
202 if ( overrideCursor )
203 {
204 cursor = QCursor( *QApplication::overrideCursor() );
205 QApplication::restoreOverrideCursor();
206 }
207
208 // Checkbox about adding sublayers to a group
209 if ( mShowAddToGroupCheckbox )
210 {
211 mCbxAddToGroup->setVisible( true );
212 const bool addToGroup = settings.value( QStringLiteral( "/qgis/openSublayersInGroup" ), false ).toBool();
213 mCbxAddToGroup->setChecked( addToGroup );
214 }
215
216 const int ret = QDialog::exec();
217 if ( overrideCursor )
218 QApplication::setOverrideCursor( cursor );
219
220 if ( mShowAddToGroupCheckbox )
221 settings.setValue( QStringLiteral( "/qgis/openSublayersInGroup" ), mCbxAddToGroup->isChecked() );
222 return ret;
223}
224
225void QgsSublayersDialog::layersTable_selectionChanged( const QItemSelection &, const QItemSelection & )
226{
227 buttonBox->button( QDialogButtonBox::Ok )->setEnabled( layersTable->selectedItems().length() > 0 );
228}
229
230void QgsSublayersDialog::mBtnDeselectAll_pressed()
231{
232 layersTable->selectionModel()->clear();
233}
SublayerPromptMode
Specifies how to handle layer sources with multiple sublayers.
Definition qgis.h:1580
@ AlwaysAsk
Always ask users to select from available sublayers, if sublayers are present.
@ NeverAskLoadAll
Never ask users to select sublayers, instead automatically load all available sublayers.
@ NeverAskSkip
Never ask users to select sublayers, instead don't load anything.
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:210
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
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.
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
bool mShowType
Whether to show type in the table.
QList< QgsSublayersDialog::LayerDefinition > LayerDefinitionList
List of layer definitions for the purpose of this dialog.
Q_DECL_DEPRECATED QgsSublayersDialog(ProviderType providerType, const QString &name, QWidget *parent=nullptr, Qt::WindowFlags fl=Qt::WindowFlags(), const QString &dataSourceUri=QString())
Constructor for QgsSublayersDialog.
LayerDefinitionList selection()
Returns list of selected layers.
bool mShowCount
Whether to show number of features in the table.
bool mShowDescription
Whether to show description in the table.
void populateLayerTable(const LayerDefinitionList &list)
Populate the table with layers.
int countColumn() const
Returns column with count or -1.
QString mName
Provider type name.
@ Uncounted
Feature count not yet computed.
@ UnknownCount
Provider returned an unknown feature count.
bool operator<(const QVariant &v1, const QVariant &v2)
Compares two QVariant values and returns whether the first is less than the second.
Definition qgis.h:6425
A structure that defines layers for the purpose of this dialog.
QString layerName
Name of the layer (not necessarily unique)
QString type
Extra type depending on the use (e.g. geometry type for vector sublayers)
int layerId
Identifier of the layer (one unique layer id may have multiple types though)