QGIS API Documentation  2.11.0-Master
qgsrulebasedrendererv2widget.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsrulebasedrendererv2widget.cpp - Settings widget for rule-based renderer
3  ---------------------
4  begin : May 2010
5  copyright : (C) 2010 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 "qgsrulebasedrendererv2.h"
19 #include "qgssymbollayerv2utils.h"
20 #include "qgssymbolv2.h"
21 #include "qgsvectorlayer.h"
22 #include "qgsapplication.h"
23 #include "qgsexpression.h"
25 #include "qgslogger.h"
26 #include "qstring.h"
28 
29 #include <QKeyEvent>
30 #include <QMenu>
31 #include <QProgressDialog>
32 #include <QSettings>
33 #include <QTreeWidgetItem>
34 #include <QVBoxLayout>
35 #include <QMessageBox>
36 
37 #ifdef ENABLE_MODELTEST
38 #include "modeltest.h"
39 #endif
40 
42 {
43  return new QgsRuleBasedRendererV2Widget( layer, style, renderer );
44 }
45 
47  : QgsRendererV2Widget( layer, style )
48 {
49  mRenderer = 0;
50  // try to recognize the previous renderer
51  // (null renderer means "no previous renderer")
52 
53 
54  if ( renderer )
55  {
57  }
58  if ( !mRenderer )
59  {
60  // some default options
62 
63  mRenderer = new QgsRuleBasedRendererV2( symbol );
64  }
65 
66  setupUi( this );
67 
69 #ifdef ENABLE_MODELTEST
70  new ModelTest( mModel, this ); // for model validity checking
71 #endif
72  viewRules->setModel( mModel );
73 
74  mDeleteAction = new QAction( tr( "Remove Rule" ), this );
75  mDeleteAction->setShortcut( QKeySequence( QKeySequence::Delete ) );
76 
77  viewRules->addAction( mDeleteAction );
78  viewRules->addAction( mCopyAction );
79  viewRules->addAction( mPasteAction );
80 
81  mRefineMenu = new QMenu( tr( "Refine current rule" ), btnRefineRule );
82  mRefineMenu->addAction( tr( "Add scales to rule" ), this, SLOT( refineRuleScales() ) );
83  mRefineMenu->addAction( tr( "Add categories to rule" ), this, SLOT( refineRuleCategories() ) );
84  mRefineMenu->addAction( tr( "Add ranges to rule" ), this, SLOT( refineRuleRanges() ) );
85  btnRefineRule->setMenu( mRefineMenu );
87 
88  btnAddRule->setIcon( QIcon( QgsApplication::iconPath( "symbologyAdd.svg" ) ) );
89  btnEditRule->setIcon( QIcon( QgsApplication::iconPath( "symbologyEdit.png" ) ) );
90  btnRemoveRule->setIcon( QIcon( QgsApplication::iconPath( "symbologyRemove.svg" ) ) );
91 
92  connect( viewRules, SIGNAL( doubleClicked( const QModelIndex & ) ), this, SLOT( editRule( const QModelIndex & ) ) );
93 
94  // support for context menu (now handled generically)
95  connect( viewRules, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT( contextMenuViewCategories( const QPoint& ) ) );
96 
97  connect( viewRules->selectionModel(), SIGNAL( currentChanged( QModelIndex, QModelIndex ) ), this, SLOT( currentRuleChanged( QModelIndex, QModelIndex ) ) );
98 
99  connect( btnAddRule, SIGNAL( clicked() ), this, SLOT( addRule() ) );
100  connect( btnEditRule, SIGNAL( clicked() ), this, SLOT( editRule() ) );
101  connect( btnRemoveRule, SIGNAL( clicked() ), this, SLOT( removeRule() ) );
102  connect( mDeleteAction, SIGNAL( triggered() ), this, SLOT( removeRule() ) );
103  connect( btnCountFeatures, SIGNAL( clicked() ), this, SLOT( countFeatures() ) );
104 
105  connect( btnRenderingOrder, SIGNAL( clicked() ), this, SLOT( setRenderingOrder() ) );
106 
108 
109  // store/restore header section widths
110  connect( viewRules->header(), SIGNAL( sectionResized( int, int, int ) ), this, SLOT( saveSectionWidth( int, int, int ) ) );
111 
113 
114 }
115 
117 {
118  qDeleteAll( mCopyBuffer );
119  delete mRenderer;
120 }
121 
123 {
124  return mRenderer;
125 }
126 
128 {
131 
132  QgsRendererRulePropsDialog dlg( newrule, mLayer, mStyle, this );
133  if ( dlg.exec() )
134  {
136  if ( current )
137  {
138  // add after this rule
139  QModelIndex currentIndex = viewRules->selectionModel()->currentIndex();
140  mModel->insertRule( currentIndex.parent(), currentIndex.row() + 1, newrule );
141  }
142  else
143  {
144  // append to root rule
145  int rows = mModel->rowCount();
146  mModel->insertRule( QModelIndex(), rows, newrule );
147  }
149  }
150  else
151  {
152  delete newrule;
153  }
154 }
155 
157 {
158  QItemSelectionModel* sel = viewRules->selectionModel();
159  QModelIndex idx = sel->currentIndex();
160  if ( !idx.isValid() )
161  return NULL;
162  return mModel->ruleForIndex( idx );
163 }
164 
166 {
167  editRule( viewRules->selectionModel()->currentIndex() );
168 }
169 
171 {
172  if ( !index.isValid() )
173  return;
175 
176  QgsRendererRulePropsDialog dlg( rule, mLayer, mStyle, this );
177  if ( dlg.exec() )
178  {
179  // model should know about the change and emit dataChanged signal for the view
180  mModel->updateRule( index.parent(), index.row() );
182  }
183 }
184 
186 {
187  QItemSelection sel = viewRules->selectionModel()->selection();
188  QgsDebugMsg( QString( "REMOVE RULES!!! ranges: %1" ).arg( sel.count() ) );
189  foreach ( QItemSelectionRange range, sel )
190  {
191  QgsDebugMsg( QString( "RANGE: r %1 - %2" ).arg( range.top() ).arg( range.bottom() ) );
192  if ( range.isValid() )
193  mModel->removeRows( range.top(), range.bottom() - range.top() + 1, range.parent() );
194  }
195  // make sure that the selection is gone
196  viewRules->selectionModel()->clear();
198 }
199 
201 {
202  Q_UNUSED( previous );
203  btnRefineRule->setEnabled( current.isValid() );
204 }
205 
206 
212 #include <QDialogButtonBox>
213 #include <QInputDialog>
214 #include <QClipboard>
215 
217 {
218  QModelIndexList indexlist = viewRules->selectionModel()->selectedRows();
219 
220  if ( indexlist.isEmpty() )
221  return;
222 
223 
224  if ( type == 0 ) // categories
225  refineRuleCategoriesGui( indexlist );
226  else if ( type == 1 ) // ranges
227  refineRuleRangesGui( indexlist );
228  else // scales
229  refineRuleScalesGui( indexlist );
230 
231  // TODO: set initial rule's symbol to NULL (?)
232 
233  // show the newly added rules
234  foreach ( QModelIndex index, indexlist )
235  viewRules->expand( index );
236 }
237 
239 {
240  refineRule( 0 );
241 }
242 
244 {
245  refineRule( 1 );
246 }
247 
249 {
250  refineRule( 2 );
251 }
252 
253 void QgsRuleBasedRendererV2Widget::refineRuleCategoriesGui( const QModelIndexList& indexList )
254 {
255  QDialog dlg;
256  dlg.setWindowTitle( tr( "Refine a rule to categories" ) );
257  QVBoxLayout* l = new QVBoxLayout();
259  l->addWidget( w );
260  QDialogButtonBox* bb = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel );
261  l->addWidget( bb );
262  connect( bb, SIGNAL( accepted() ), &dlg, SLOT( accept() ) );
263  connect( bb, SIGNAL( rejected() ), &dlg, SLOT( reject() ) );
264  dlg.setLayout( l );
265 
266  if ( !dlg.exec() )
267  return;
268 
269  // create new rules
271  foreach ( QModelIndex index, indexList )
272  {
273  QgsRuleBasedRendererV2::Rule* initialRule = mModel->ruleForIndex( index );
274  mModel->willAddRules( index, r->categories().count() );
276  }
278 }
279 
280 
281 void QgsRuleBasedRendererV2Widget::refineRuleRangesGui( const QModelIndexList& indexList )
282 {
283 
284 
285  QDialog dlg;
286  dlg.setWindowTitle( tr( "Refine a rule to ranges" ) );
287  QVBoxLayout* l = new QVBoxLayout();
289  l->addWidget( w );
290  QDialogButtonBox* bb = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel );
291  l->addWidget( bb );
292  connect( bb, SIGNAL( accepted() ), &dlg, SLOT( accept() ) );
293  connect( bb, SIGNAL( rejected() ), &dlg, SLOT( reject() ) );
294  dlg.setLayout( l );
295 
296  if ( !dlg.exec() )
297  return;
298 
299  // create new rules
301  foreach ( QModelIndex index, indexList )
302  {
303  QgsRuleBasedRendererV2::Rule* initialRule = mModel->ruleForIndex( index );
304  mModel->willAddRules( index, r->ranges().count() );
306  }
308 }
309 
310 void QgsRuleBasedRendererV2Widget::refineRuleScalesGui( const QModelIndexList& indexList )
311 {
312  foreach ( QModelIndex index, indexList )
313  {
314  QgsRuleBasedRendererV2::Rule* initialRule = mModel->ruleForIndex( index );
315 
316  // If any of the rules don't have a symbol let the user know and exit.
317  if ( initialRule->symbol() == NULL )
318  {
319  QMessageBox::warning( this, tr( "Scale refinement" ), tr( "Parent rule %1 must have a symbol for this operation." ).arg( initialRule->label() ) );
320  return;
321  }
322  }
323 
324  QString txt = QInputDialog::getText( this,
325  tr( "Scale refinement" ),
326  tr( "Please enter scale denominators at which will split the rule, separate them by commas (e.g. 1000,5000):" ) );
327  if ( txt.isEmpty() )
328  return;
329 
330  QList<int> scales;
331  bool ok;
332  foreach ( QString item, txt.split( ',' ) )
333  {
334  int scale = item.toInt( &ok );
335  if ( ok )
336  scales.append( scale );
337  else
338  QMessageBox::information( this, tr( "Error" ), QString( tr( "\"%1\" is not valid scale denominator, ignoring it." ) ).arg( item ) );
339  }
340 
341  foreach ( QModelIndex index, indexList )
342  {
343  QgsRuleBasedRendererV2::Rule* initialRule = mModel->ruleForIndex( index );
344  mModel->willAddRules( index, scales.count() + 1 );
345  QgsRuleBasedRendererV2::refineRuleScales( initialRule, scales );
346  }
348 }
349 
351 {
352  QList<QgsSymbolV2*> symbolList;
353 
354  if ( !mRenderer )
355  {
356  return symbolList;
357  }
358 
359  QItemSelection sel = viewRules->selectionModel()->selection();
360  foreach ( QItemSelectionRange range, sel )
361  {
362  QModelIndex parent = range.parent();
363  QgsRuleBasedRendererV2::Rule* parentRule = mModel->ruleForIndex( parent );
365  for ( int row = range.top(); row <= range.bottom(); row++ )
366  {
367  symbolList.append( children[row]->symbol() );
368  }
369  }
370 
371  return symbolList;
372 }
373 
375 {
377  QItemSelection sel = viewRules->selectionModel()->selection();
378  foreach ( QItemSelectionRange range, sel )
379  {
380  QModelIndex parent = range.parent();
381  QgsRuleBasedRendererV2::Rule* parentRule = mModel->ruleForIndex( parent );
383  for ( int row = range.top(); row <= range.bottom(); row++ )
384  {
385  rl.append( children[row]->clone() );
386  }
387  }
388  return rl;
389 }
390 
392 {
393  // TODO: model/view
394  /*
395  if ( treeRules )
396  {
397  treeRules->populateRules();
398  }
399  */
400 }
401 
403 {
404  if ( !event )
405  {
406  return;
407  }
408 
409  if ( event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier )
410  {
411  qDeleteAll( mCopyBuffer );
412  mCopyBuffer.clear();
414  }
415  else if ( event->key() == Qt::Key_V && event->modifiers() == Qt::ControlModifier )
416  {
418  for ( ; rIt != mCopyBuffer.constEnd(); ++rIt )
419  {
420  int rows = mModel->rowCount();
421  mModel->insertRule( QModelIndex(), rows, ( *rIt )->clone() );
422  }
423  }
424 }
425 
426 #include "qgssymbollevelsv2dialog.h"
427 
429 {
431 
432  QgsSymbolLevelsV2Dialog dlg( lst, true, this );
433  dlg.setForceOrderingEnabled( true );
434 
435  dlg.exec();
436 }
437 
438 void QgsRuleBasedRendererV2Widget::saveSectionWidth( int section, int oldSize, int newSize )
439 {
440  Q_UNUSED( oldSize );
441  // skip last section, as it stretches
442  if ( section == 5 )
443  return;
444  QSettings settings;
445  QString path = "/Windows/RuleBasedTree/sectionWidth/" + QString::number( section );
446  settings.setValue( path, newSize );
447 }
448 
450 {
451  QSettings settings;
452  QString path = "/Windows/RuleBasedTree/sectionWidth/";
453  QHeaderView* head = viewRules->header();
454  head->resizeSection( 0, settings.value( path + QString::number( 0 ), 150 ).toInt() );
455  head->resizeSection( 1, settings.value( path + QString::number( 1 ), 150 ).toInt() );
456  head->resizeSection( 2, settings.value( path + QString::number( 2 ), 80 ).toInt() );
457  head->resizeSection( 3, settings.value( path + QString::number( 3 ), 80 ).toInt() );
458  head->resizeSection( 4, settings.value( path + QString::number( 4 ), 50 ).toInt() );
459  head->resizeSection( 5, settings.value( path + QString::number( 5 ), 50 ).toInt() );
460 }
461 
463 {
464  QModelIndexList indexlist = viewRules->selectionModel()->selectedRows();
465  QgsDebugMsg( QString( "%1" ).arg( indexlist.count() ) );
466 
467  if ( indexlist.isEmpty() )
468  return;
469 
470  QMimeData* mime = mModel->mimeData( indexlist );
472 }
473 
475 {
476  const QMimeData* mime = QApplication::clipboard()->mimeData();
477  QModelIndexList indexlist = viewRules->selectionModel()->selectedRows();
479  if ( indexlist.isEmpty() )
480  index = mModel->index( mModel->rowCount(), 0 );
481  else
482  index = indexlist.first();
483  mModel->dropMimeData( mime, Qt::CopyAction, index.row(), index.column(), index.parent() );
484 }
485 
486 
488 {
489  if ( !mLayer || !mRenderer || !mRenderer->rootRule() )
490  {
491  return;
492  }
494 
496  // insert all so that we have counts 0
497  foreach ( QgsRuleBasedRendererV2::Rule* rule, ruleList )
498  {
499  countMap[rule].count = 0;
500  countMap[rule].duplicateCount = 0;
501  }
502 
504 
505  QgsRenderContext renderContext;
506  renderContext.setRendererScale( 0 ); // ignore scale
507  mRenderer->startRender( renderContext, mLayer->pendingFields() );
508 
509  int nFeatures = mLayer->pendingFeatureCount();
510  QProgressDialog p( tr( "Calculating feature count." ), tr( "Abort" ), 0, nFeatures );
511  p.setWindowModality( Qt::WindowModal );
512  int featuresCounted = 0;
513 
514  QgsFeature f;
515  while ( fit.nextFeature( f ) )
516  {
518 
519  foreach ( QgsRuleBasedRendererV2::Rule* rule, featureRuleList )
520  {
521  countMap[rule].count++;
522  if ( featureRuleList.size() > 1 )
523  {
524  countMap[rule].duplicateCount++;
525  }
526  foreach ( QgsRuleBasedRendererV2::Rule* duplicateRule, featureRuleList )
527  {
528  if ( duplicateRule == rule ) continue;
529  countMap[rule].duplicateCountMap[duplicateRule] += 1;
530  }
531  }
532  ++featuresCounted;
533  if ( featuresCounted % 50 == 0 )
534  {
535  if ( featuresCounted > nFeatures ) //sometimes the feature count is not correct
536  {
537  p.setMaximum( 0 );
538  }
539  p.setValue( featuresCounted );
540  if ( p.wasCanceled() )
541  {
542  return;
543  }
544  }
545  }
546  p.setValue( nFeatures );
547 
548  mRenderer->stopRender( renderContext );
549 
550 #ifdef QGISDEBUG
551  foreach ( QgsRuleBasedRendererV2::Rule *rule, countMap.keys() )
552  {
553  QgsDebugMsg( QString( "rule: %1 count %2" ).arg( rule->label() ).arg( countMap[rule].count ) );
554  }
555 #endif
556 
557  mModel->setFeatureCounts( countMap );
558 }
559 
561 
563  : QDialog( parent ), mRule( rule ), mLayer( layer ), mSymbolSelector( NULL ), mSymbol( NULL )
564 {
565  setupUi( this );
566 #ifdef Q_OS_MAC
567  setWindowModality( Qt::WindowModal );
568 #endif
569 
570  connect( buttonBox, SIGNAL( accepted() ), this, SLOT( accept() ) );
571  connect( buttonBox, SIGNAL( rejected() ), this, SLOT( reject() ) );
572 
573  editFilter->setText( mRule->filterExpression() );
574  editFilter->setToolTip( mRule->filterExpression() );
575  editLabel->setText( mRule->label() );
576  editDescription->setText( mRule->description() );
577  editDescription->setToolTip( mRule->description() );
578 
579  if ( mRule->dependsOnScale() )
580  {
581  groupScale->setChecked( true );
582  // caution: rule uses scale denom, scale widget uses true scales
583  if ( rule->scaleMinDenom() > 0 )
584  mScaleRangeWidget->setMaximumScale( 1.0 / rule->scaleMinDenom() );
585  if ( rule->scaleMaxDenom() > 0 )
586  mScaleRangeWidget->setMinimumScale( 1.0 / rule->scaleMaxDenom() );
587  }
588 
589  if ( mRule->symbol() )
590  {
591  groupSymbol->setChecked( true );
592  mSymbol = mRule->symbol()->clone(); // use a clone!
593  }
594  else
595  {
596  groupSymbol->setChecked( false );
598  }
599 
600  mSymbolSelector = new QgsSymbolV2SelectorDialog( mSymbol, style, mLayer, this, true );
601  QVBoxLayout* l = new QVBoxLayout;
603  groupSymbol->setLayout( l );
604 
605  connect( btnExpressionBuilder, SIGNAL( clicked() ), this, SLOT( buildExpression() ) );
606  connect( btnTestFilter, SIGNAL( clicked() ), this, SLOT( testFilter() ) );
607 
608  QSettings settings;
609  restoreGeometry( settings.value( "/Windows/QgsRendererRulePropsDialog/geometry" ).toByteArray() );
610 }
611 
613 {
614  delete mSymbol;
615  QSettings settings;
616  settings.setValue( "/Windows/QgsRendererRulePropsDialog/geometry", saveGeometry() );
617 }
618 
620 {
621  QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this );
622 
623  if ( dlg.exec() )
624  editFilter->setText( dlg.expressionText() );
625 }
626 
628 {
629  QgsExpression filter( editFilter->text() );
630  if ( filter.hasParserError() )
631  {
632  QMessageBox::critical( this, tr( "Error" ), tr( "Filter expression parsing error:\n" ) + filter.parserErrorString() );
633  return;
634  }
635 
636  const QgsFields& fields = mLayer->pendingFields();
637 
638  if ( !filter.prepare( fields ) )
639  {
640  QMessageBox::critical( this, tr( "Evaluation error" ), filter.evalErrorString() );
641  return;
642  }
643 
644  QApplication::setOverrideCursor( Qt::WaitCursor );
645 
647 
648  int count = 0;
649  QgsFeature f;
650  while ( fit.nextFeature( f ) )
651  {
652  QVariant value = filter.evaluate( &f );
653  if ( value.toInt() != 0 )
654  count++;
655  if ( filter.hasEvalError() )
656  break;
657  }
658 
660 
661  QMessageBox::information( this, tr( "Filter" ), tr( "Filter returned %n feature(s)", "number of filtered features", count ) );
662 }
663 
665 {
666  mRule->setFilterExpression( editFilter->text() );
667  mRule->setLabel( editLabel->text() );
668  mRule->setDescription( editDescription->text() );
669  // caution: rule uses scale denom, scale widget uses true scales
670  mRule->setScaleMinDenom( groupScale->isChecked() ? mScaleRangeWidget->minimumScaleDenom() : 0 );
671  mRule->setScaleMaxDenom( groupScale->isChecked() ? mScaleRangeWidget->maximumScaleDenom() : 0 );
672  mRule->setSymbol( groupSymbol->isChecked() ? mSymbol->clone() : NULL );
673 
674  QDialog::accept();
675 }
676 
678 
679 /*
680  setDragEnabled(true);
681  viewport()->setAcceptDrops(true);
682  setDropIndicatorShown(true);
683  setDragDropMode(QAbstractItemView::InternalMove);
684 */
685 
686 static QString _formatScale( int denom )
687 {
688  if ( denom != 0 )
689  {
690  QString txt = QString( "1:%L1" ).arg( denom );
691  return txt;
692  }
693  else
694  return QString();
695 }
696 
698 
700  : mR( r )
701 {
702 }
703 
705 {
706  if ( !index.isValid() )
707  return Qt::ItemIsDropEnabled;
708 
709  // allow drop only at first column
710  Qt::ItemFlag drop = ( index.column() == 0 ? Qt::ItemIsDropEnabled : Qt::NoItemFlags );
711 
712  Qt::ItemFlag checkable = ( index.column() == 0 ? Qt::ItemIsUserCheckable : Qt::NoItemFlags );
713 
714  return Qt::ItemIsEnabled | Qt::ItemIsSelectable |
715  Qt::ItemIsEditable | checkable |
716  Qt::ItemIsDragEnabled | drop;
717 }
718 
720 {
721  if ( !index.isValid() )
722  return QVariant();
723 
725 
726  if ( role == Qt::DisplayRole || role == Qt::ToolTipRole )
727  {
728  switch ( index.column() )
729  {
730  case 0: return rule->label();
731  case 1:
732  if ( rule->isElse() )
733  {
734  return "ELSE";
735  }
736  else
737  {
738  return rule->filterExpression().isEmpty() ? tr( "(no filter)" ) : rule->filterExpression();
739  }
740  case 2: return rule->dependsOnScale() ? _formatScale( rule->scaleMaxDenom() ) : QVariant();
741  case 3: return rule->dependsOnScale() ? _formatScale( rule->scaleMinDenom() ) : QVariant();
742  case 4:
743  if ( mFeatureCountMap.count( rule ) == 1 )
744  {
745  return QVariant( mFeatureCountMap[rule].count );
746  }
747  return QVariant();
748  case 5:
749  if ( mFeatureCountMap.count( rule ) == 1 )
750  {
751  if ( role == Qt::DisplayRole )
752  {
753  return QVariant( mFeatureCountMap[rule].duplicateCount );
754  }
755  else // tooltip - detailed info about duplicates
756  {
757  if ( mFeatureCountMap[rule].duplicateCount > 0 )
758  {
759  QString tip = "<p style='margin:0px;'><ul>";
760  foreach ( QgsRuleBasedRendererV2::Rule* duplicateRule, mFeatureCountMap[rule].duplicateCountMap.keys() )
761  {
762  QString label = duplicateRule->label().replace( "&", "&amp;" ).replace( ">", "&gt;" ).replace( "<", "&lt;" );
763  tip += tr( "<li><nobr>%1 features also in rule %2</nobr></li>" ).arg( mFeatureCountMap[rule].duplicateCountMap[duplicateRule] ).arg( label );
764  }
765  tip += "</ul>";
766  return tip;
767  }
768  else
769  {
770  return 0;
771  }
772  }
773  }
774  return QVariant();
775  default: return QVariant();
776  }
777  }
778  else if ( role == Qt::DecorationRole && index.column() == 0 && rule->symbol() )
779  {
780  return QgsSymbolLayerV2Utils::symbolPreviewIcon( rule->symbol(), QSize( 16, 16 ) );
781  }
782  else if ( role == Qt::TextAlignmentRole )
783  {
784  return ( index.column() == 2 || index.column() == 3 ) ? Qt::AlignRight : Qt::AlignLeft;
785  }
786  else if ( role == Qt::FontRole && index.column() == 1 )
787  {
788  if ( rule->isElse() )
789  {
790  QFont italicFont;
791  italicFont.setItalic( true );
792  return italicFont;
793  }
794  return QVariant();
795  }
796  else if ( role == Qt::EditRole )
797  {
798  switch ( index.column() )
799  {
800  case 0: return rule->label();
801  case 1: return rule->filterExpression();
802  case 2: return rule->scaleMaxDenom();
803  case 3: return rule->scaleMinDenom();
804  default: return QVariant();
805  }
806  }
807  else if ( role == Qt::CheckStateRole )
808  {
809  if ( index.column() != 0 )
810  return QVariant();
811  return rule->checkState() ? Qt::Checked : Qt::Unchecked;
812  }
813  else
814  return QVariant();
815 }
816 
817 QVariant QgsRuleBasedRendererV2Model::headerData( int section, Qt::Orientation orientation, int role ) const
818 {
819  if ( orientation == Qt::Horizontal && role == Qt::DisplayRole && section >= 0 && section < 7 )
820  {
821  QStringList lst; lst << tr( "Label" ) << tr( "Rule" ) << tr( "Min. scale" ) << tr( "Max. scale" ) << tr( "Count" ) << tr( "Duplicate count" );
822  return lst[section];
823  }
824  else if ( orientation == Qt::Horizontal && role == Qt::ToolTipRole )
825  {
826  if ( section == 4 ) // Count
827  {
828  return tr( "Number of features in this rule." );
829  }
830  else if ( section == 5 ) // Duplicate count
831  {
832  return tr( "Number of features in this rule which are also present in other rule(s)." );
833  }
834  }
835 
836  return QVariant();
837 }
838 
840 {
841  if ( parent.column() > 0 )
842  return 0;
843 
844  QgsRuleBasedRendererV2::Rule* parentRule = ruleForIndex( parent );
845 
846  return parentRule->children().count();
847 }
848 
850 {
851  return 6;
852 }
853 
854 QModelIndex QgsRuleBasedRendererV2Model::index( int row, int column, const QModelIndex &parent ) const
855 {
856  if ( hasIndex( row, column, parent ) )
857  {
858  QgsRuleBasedRendererV2::Rule* parentRule = ruleForIndex( parent );
859  QgsRuleBasedRendererV2::Rule* childRule = parentRule->children()[row];
860  return createIndex( row, column, childRule );
861  }
862  return QModelIndex();
863 }
864 
866 {
867  if ( !index.isValid() )
868  return QModelIndex();
869 
870  QgsRuleBasedRendererV2::Rule* childRule = ruleForIndex( index );
871  QgsRuleBasedRendererV2::Rule* parentRule = childRule->parent();
872 
873  if ( parentRule == mR->rootRule() )
874  return QModelIndex();
875 
876  // this is right: we need to know row number of our parent (in our grandparent)
877  int row = parentRule->parent()->children().indexOf( parentRule );
878 
879  return createIndex( row, 0, parentRule );
880 }
881 
882 bool QgsRuleBasedRendererV2Model::setData( const QModelIndex & index, const QVariant & value, int role )
883 {
884  if ( !index.isValid() )
885  return false;
886 
888 
889  if ( role == Qt::CheckStateRole )
890  {
891  rule->setCheckState( value.toInt() == Qt::Checked );
892  emit dataChanged( index, index );
893  return true;
894  }
895 
896  if ( role != Qt::EditRole )
897  return false;
898 
899  switch ( index.column() )
900  {
901  case 0: // label
902  rule->setLabel( value.toString() );
903  break;
904  case 1: // filter
905  rule->setFilterExpression( value.toString() );
906  break;
907  case 2: // scale min
908  rule->setScaleMaxDenom( value.toInt() );
909  break;
910  case 3: // scale max
911  rule->setScaleMinDenom( value.toInt() );
912  break;
913  default:
914  return false;
915  }
916 
917  emit dataChanged( index, index );
918  return true;
919 }
920 
922 {
923  return Qt::MoveAction; // | Qt::CopyAction
924 }
925 
927 {
928  QStringList types;
929  types << "application/vnd.text.list";
930  return types;
931 }
932 
933 QMimeData *QgsRuleBasedRendererV2Model::mimeData( const QModelIndexList &indexes ) const
934 {
935  QMimeData *mimeData = new QMimeData();
936  QByteArray encodedData;
937 
938  QDataStream stream( &encodedData, QIODevice::WriteOnly );
939 
940  foreach ( const QModelIndex &index, indexes )
941  {
942  // each item consists of several columns - let's add it with just first one
943  if ( !index.isValid() || index.column() != 0 )
944  continue;
945 
946  // we use a clone of the existing rule because it has a new unique rule key
947  // non-unique rule keys would confuse other components using them (e.g. legend)
948  QgsRuleBasedRendererV2::Rule* rule = ruleForIndex( index )->clone();
949  QDomDocument doc;
950  QgsSymbolV2Map symbols;
951 
952  QDomElement rootElem = doc.createElement( "rule_mime" );
953  QDomElement rulesElem = rule->save( doc, symbols );
954  rootElem.appendChild( rulesElem );
955  QDomElement symbolsElem = QgsSymbolLayerV2Utils::saveSymbols( symbols, "symbols", doc );
956  rootElem.appendChild( symbolsElem );
957  doc.appendChild( rootElem );
958 
959  delete rule;
960 
961  stream << doc.toString( -1 );
962  }
963 
964  mimeData->setData( "application/vnd.text.list", encodedData );
965  return mimeData;
966 }
967 
969  Qt::DropAction action, int row, int column, const QModelIndex &parent )
970 {
971  Q_UNUSED( column );
972 
973  if ( action == Qt::IgnoreAction )
974  return true;
975 
976  if ( !data->hasFormat( "application/vnd.text.list" ) )
977  return false;
978 
979  if ( parent.column() > 0 )
980  return false;
981 
982  QByteArray encodedData = data->data( "application/vnd.text.list" );
983  QDataStream stream( &encodedData, QIODevice::ReadOnly );
984  int rows = 0;
985 
986  if ( row == -1 )
987  {
988  // the item was dropped at a parent - we may decide where to put the items - let's append them
989  row = rowCount( parent );
990  }
991 
992  while ( !stream.atEnd() )
993  {
994  QString text;
995  stream >> text;
996 
997  QDomDocument doc;
998  if ( !doc.setContent( text ) )
999  continue;
1000  QDomElement rootElem = doc.documentElement();
1001  if ( rootElem.tagName() != "rule_mime" )
1002  continue;
1003  QDomElement symbolsElem = rootElem.firstChildElement( "symbols" );
1004  if ( symbolsElem.isNull() )
1005  continue;
1006  QgsSymbolV2Map symbolMap = QgsSymbolLayerV2Utils::loadSymbols( symbolsElem );
1007  QDomElement ruleElem = rootElem.firstChildElement( "rule" );
1009 
1010  insertRule( parent, row + rows, rule );
1011 
1012  ++rows;
1013  }
1014  return true;
1015 }
1016 
1018 {
1019  if ( index.isValid() )
1020  return static_cast<QgsRuleBasedRendererV2::Rule*>( index.internalPointer() );
1021  return mR->rootRule();
1022 }
1023 
1024 bool QgsRuleBasedRendererV2Model::removeRows( int row, int count, const QModelIndex & parent )
1025 {
1026  QgsRuleBasedRendererV2::Rule* parentRule = ruleForIndex( parent );
1027 
1028  if ( row < 0 || row >= parentRule->children().count() )
1029  return false;
1030 
1031  QgsDebugMsg( QString( "Called: row %1 count %2 parent ~~%3~~" ).arg( row ).arg( count ).arg( parentRule->dump() ) );
1032 
1033  beginRemoveRows( parent, row, row + count - 1 );
1034 
1035  for ( int i = 0; i < count; i++ )
1036  {
1037  if ( row < parentRule->children().count() )
1038  {
1039  //QgsRuleBasedRendererV2::Rule* r = parentRule->children()[row];
1040  parentRule->removeChildAt( row );
1041  //parentRule->takeChildAt( row );
1042  }
1043  else
1044  {
1045  QgsDebugMsg( "trying to remove invalid index - this should not happen!" );
1046  }
1047  }
1048 
1049  endRemoveRows();
1050 
1051  return true;
1052 }
1053 
1054 
1056 {
1057  beginInsertRows( parent, before, before );
1058 
1059  QgsDebugMsg( QString( "insert before %1 rule: %2" ).arg( before ).arg( newrule->dump() ) );
1060 
1061  QgsRuleBasedRendererV2::Rule* parentRule = ruleForIndex( parent );
1062  parentRule->insertChild( before, newrule );
1063 
1064  endInsertRows();
1065 }
1066 
1068 {
1069  emit dataChanged( index( row, 0, parent ),
1070  index( row, columnCount( parent ), parent ) );
1071 }
1072 
1074 {
1075  emit dataChanged( index( 0, 0, idx ),
1076  index( rowCount( idx ) - 1, columnCount( idx ) - 1, idx ) );
1077 
1078  for ( int i = 0; i < rowCount( idx ); i++ )
1079  {
1080  updateRule( index( i, 0, idx ) );
1081  }
1082 }
1083 
1084 
1086 {
1087  if ( !index.isValid() )
1088  return;
1089 
1090  beginRemoveRows( index.parent(), index.row(), index.row() );
1091 
1092  QgsRuleBasedRendererV2::Rule* rule = ruleForIndex( index );
1093  rule->parent()->removeChild( rule );
1094 
1095  endRemoveRows();
1096 }
1097 
1099 {
1100  int row = rowCount( parent ); // only consider appending
1101  beginInsertRows( parent, row, row + count - 1 );
1102 }
1103 
1105 {
1106  emit endInsertRows();
1107 }
1108 
1110 {
1111  mFeatureCountMap = theCountMap;
1112  updateRule( QModelIndex() );
1113 }
1114 
1116 {
1118  updateRule( QModelIndex() );
1119 }
bool hasIndex(int row, int column, const QModelIndex &parent) const
void customContextMenuRequested(const QPoint &pos)
QgsRuleBasedRendererV2Widget(QgsVectorLayer *layer, QgsStyleV2 *style, QgsFeatureRendererV2 *renderer)
Class for parsing and evaluation of expressions (formerly called "search strings").
Definition: qgsexpression.h:86
void clear()
Wrapper for iterator of features from vector data provider or vector layer.
static QgsSymbolV2Map loadSymbols(QDomElement &element)
QByteArray toByteArray() const
static unsigned index
void refineRuleScalesGui(const QModelIndexList &index)
void setFeatureCounts(QMap< QgsRuleBasedRendererV2::Rule *, QgsRuleBasedRendererV2Count > theCountMap)
QByteArray data(const QString &mimeType) const
void setupUi(QWidget *widget)
QgsSymbolV2SelectorDialog * mSymbolSelector
int bottom() const
virtual void reject()
void keyPressEvent(QKeyEvent *event) override
QgsRuleBasedRendererV2Model * mModel
const QgsCategoryList & categories() const
void contextMenuViewCategories(const QPoint &p)
QModelIndex currentIndex() const
const QMimeData * mimeData(Mode mode) const
QDomNode appendChild(const QDomNode &newChild)
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
void setMaximum(int maximum)
void setWindowModality(Qt::WindowModality windowModality)
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
virtual bool hasFormat(const QString &mimeType) const
static QString iconPath(QString iconFile)
Returns path to the desired icon file.
QString toString(int indent) const
void setScaleMaxDenom(int scaleMaxDenom)
QStringList split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
virtual QgsSymbolV2 * clone() const =0
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
void rejected()
void setRendererScale(double scale)
void setIcon(const QIcon &icon)
const QObjectList & children() const
virtual QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
void addAction(QAction *action)
QList< QgsSymbolV2 * > selectedSymbols() override
Subclasses may provide the capability of changing multiple symbols at once by implementing the follow...
void refineRuleCategoriesGui(const QModelIndexList &index)
QgsRuleBasedRendererV2Model(QgsRuleBasedRendererV2 *r)
Qt::DropActions supportedDropActions() const override
Rule * clone() const
clone this rule, return new instance
void accepted()
int exec()
RuleList rulesForFeature(QgsFeature &feat)
tell which rules will be used to render the feature
Container of fields for a vector layer.
Definition: qgsfield.h:173
QgsRuleBasedRendererV2::RuleList mCopyBuffer
QDomElement documentElement() const
virtual QgsFeatureRendererV2 * renderer() override
return pointer to the renderer (no transfer of ownership)
void updateRule(const QModelIndex &parent, int row)
void saveSectionWidth(int section, int oldSize, int newSize)
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:119
virtual QgsFeatureRendererV2 * renderer() override
return pointer to the renderer (no transfer of ownership)
void clear()
QgsRuleBasedRendererV2::Rule * currentRule()
virtual QgsLegendSymbolList legendSymbolItems(double scaleDenominator=-1, QString rule="") override
return a list of item text / symbol
QString tr(const char *sourceText, const char *disambiguation, int n)
StandardButton information(QWidget *parent, const QString &title, const QString &text, QFlags< QMessageBox::StandardButton > buttons, StandardButton defaultButton)
void removeChildAt(int i)
delete child rule
int size() const
virtual int rowCount(const QModelIndex &parent=QModelIndex()) const override
int indexOf(const T &value, int from) const
void resizeSection(int logicalIndex, int size)
virtual QgsFeatureRendererV2 * renderer() override
return pointer to the renderer (no transfer of ownership)
QList< Key > keys() const
void setValue(const QString &key, const QVariant &value)
void setValue(int progress)
bool isValid() const
void refineRuleRangesGui(const QModelIndexList &index)
void addWidget(QWidget *widget, int stretch, QFlags< Qt::AlignmentFlag > alignment)
QString number(int n, int base)
static QIcon symbolPreviewIcon(QgsSymbolV2 *symbol, QSize size)
int count(const T &value) const
QgsVectorLayer * mLayer
void append(const T &value)
static void refineRuleCategories(Rule *initialRule, QgsCategorizedSymbolRendererV2 *r)
take a rule and create a list of new rules based on the categories from categorized symbol renderer ...
void setLayout(QLayout *layout)
int toInt(bool *ok) const
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
virtual void stopRender(QgsRenderContext &context) override
QClipboard * clipboard()
virtual Qt::ItemFlags flags(const QModelIndex &index) const override
bool restoreGeometry(const QByteArray &geometry)
static QString _formatScale(int denom)
virtual QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
int toInt(bool *ok, int base) const
static QDomElement saveSymbols(QgsSymbolV2Map &symbols, QString tagName, QDomDocument &doc)
static Rule * create(QDomElement &ruleElem, QgsSymbolV2Map &symbolMap)
bool isEmpty() const
void beginRemoveRows(const QModelIndex &parent, int first, int last)
int row() const
This class wraps a request for features to a vector layer (or directly its vector data provider)...
void setOverrideCursor(const QCursor &cursor)
QDomElement save(QDomDocument &doc, QgsSymbolV2Map &symbolMap)
int pendingFeatureCount()
returns feature count after commit
This class keeps data about a rules for rule-based renderer.
void restoreOverrideCursor()
void * internalPointer() const
QModelIndex parent() const
QGis::GeometryType geometryType() const
Returns point, line or polygon.
QMap< QgsRuleBasedRendererV2::Rule *, QgsRuleBasedRendererV2Count > mFeatureCountMap
void setMimeData(QMimeData *src, Mode mode)
QModelIndex parent() const
void removeRule(const QModelIndex &index)
static QgsRendererV2Widget * create(QgsVectorLayer *layer, QgsStyleV2 *style, QgsFeatureRendererV2 *renderer)
bool atEnd() const
static void refineRuleRanges(Rule *initialRule, QgsGraduatedSymbolRendererV2 *r)
take a rule and create a list of new rules based on the ranges from graduated symbol renderer ...
QString dump(int offset=0) const
virtual void accept()
QgsRendererRulePropsDialog(QgsRuleBasedRendererV2::Rule *rule, QgsVectorLayer *layer, QgsStyleV2 *style, QWidget *parent=0)
void currentRuleChanged(const QModelIndex &current=QModelIndex(), const QModelIndex &previous=QModelIndex())
QString getText(QWidget *parent, const QString &title, const QString &label, QLineEdit::EchoMode mode, const QString &text, bool *ok, QFlags< Qt::WindowType > flags, QFlags< Qt::InputMethodHint > inputMethodHints)
QModelIndex createIndex(int row, int column, void *ptr) const
virtual bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override
int key() const
void setShortcut(const QKeySequence &shortcut)
QMimeData * mimeData(const QModelIndexList &indexes) const override
void setItalic(bool enable)
void beginInsertRows(const QModelIndex &parent, int first, int last)
bool isNull() const
QString & replace(int position, int n, QChar after)
void setForceOrderingEnabled(bool enabled)
QVariant value(const QString &key, const QVariant &defaultValue) const
QStringList mimeTypes() const override
Contains information about the context of a rendering operation.
void insertRule(const QModelIndex &parent, int before, QgsRuleBasedRendererV2::Rule *newrule)
static QgsSymbolV2 * defaultSymbol(QGis::GeometryType geomType)
return new default symbol for specified geometry type
QByteArray saveGeometry() const
typedef DropActions
const QgsRangeList & ranges() const
QAction * addMenu(QMenu *menu)
When drawing a vector layer with rule-based renderer, it goes through the rules and draws features wi...
QgsRuleBasedRendererV2::Rule * ruleForIndex(const QModelIndex &index) const
void setWindowTitle(const QString &)
QDomElement firstChildElement(const QString &tagName) const
virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
provide model index for parent's child item
virtual int columnCount(const QModelIndex &=QModelIndex()) const override
QgsRuleBasedRendererV2::RuleList selectedRules()
virtual void startRender(QgsRenderContext &context, const QgsFields &fields) override
StandardButton critical(QWidget *parent, const QString &title, const QString &text, QFlags< QMessageBox::StandardButton > buttons, StandardButton defaultButton)
int column() const
Base class for renderer settings widgets.
QgsRuleBasedRendererV2::Rule * mRule
void setDescription(QString description)
void setSymbol(QgsSymbolV2 *sym)
set a new symbol (or NULL). Deletes old symbol.
StandardButton warning(QWidget *parent, const QString &title, const QString &text, QFlags< QMessageBox::StandardButton > buttons, StandardButton defaultButton)
static QgsRuleBasedRendererV2 * convertFromRenderer(const QgsFeatureRendererV2 *renderer)
creates a QgsRuleBasedRendererV2 from an existing renderer.
QString tagName() const
void setData(const QString &mimeType, const QByteArray &data)
const QgsFields & pendingFields() const
returns field list in the to-be-committed state
bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex()) override
const_iterator constEnd() const
void insertChild(int i, Rule *rule)
add child rule, take ownership, sets this as parent
QDomElement createElement(const QString &tagName)
bool nextFeature(QgsFeature &f)
const_iterator constBegin() const
bool isValid() const
Geometry is not required. It may still be returned if e.g. required for a filter condition.
void setScaleMinDenom(int scaleMinDenom)
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QObject * parent() const
Represents a vector layer which manages a vector based data sets.
QString arg(qlonglong a, int fieldWidth, int base, const QChar &fillChar) const
QString toString() const
void setFilterExpression(QString filterExp)
int count(const Key &key) const
A generic dialog for building expression strings.
void willAddRules(const QModelIndex &parent, int count)
bool setContent(const QByteArray &data, bool namespaceProcessing, QString *errorMsg, int *errorLine, int *errorColumn)
static void refineRuleScales(Rule *initialRule, QList< int > scales)
take a rule and create a list of new rules with intervals of scales given by the passed scale denomin...
typedef ItemFlags