QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgscheckablecombobox.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscheckablecombobox.cpp
3 ------------------------
4 begin : March 21, 2017
5 copyright : (C) 2017 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsapplication.h"
21
22#include <QAbstractItemView>
23#include <QEvent>
24#include <QLineEdit>
25#include <QMouseEvent>
26#include <QPoint>
27#include <QString>
28
29#include "moc_qgscheckablecombobox.cpp"
30
31using namespace Qt::StringLiterals;
32
34 : QStandardItemModel( 0, 1, parent )
35{}
36
37Qt::ItemFlags QgsCheckableItemModel::flags( const QModelIndex &index ) const
38{
39 return QStandardItemModel::flags( index ) | Qt::ItemIsUserCheckable;
40}
41
42QVariant QgsCheckableItemModel::data( const QModelIndex &index, int role ) const
43{
44 QVariant value = QStandardItemModel::data( index, role );
45
46 if ( index.isValid() && role == Qt::CheckStateRole && !value.isValid() )
47 {
48 value = Qt::Unchecked;
49 }
50
51 return value;
52}
53
54bool QgsCheckableItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
55{
56 const bool ok = QStandardItemModel::setData( index, value, role );
57
58 if ( ok && role == Qt::CheckStateRole )
59 {
60 emit itemCheckStateChanged( index );
61 }
62
63 emit dataChanged( index, index );
64 return ok;
65}
66
67
69 : QStyledItemDelegate( parent )
70{}
71
72void QgsCheckBoxDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
73{
74 QStyleOptionViewItem &nonConstOpt = const_cast<QStyleOptionViewItem &>( option );
75 nonConstOpt.showDecorationSelected = false;
76 QStyledItemDelegate::paint( painter, nonConstOpt, index );
77}
78
79
81 : QComboBox( parent )
82 , mModel( new QgsCheckableItemModel( this ) )
83 , mSeparator( u", "_s )
84{
85 setModel( mModel );
86 setItemDelegate( new QgsCheckBoxDelegate( this ) );
87
88 QLineEdit *lineEdit = new QLineEdit( this );
89 lineEdit->setReadOnly( true );
90 QPalette pal = qApp->palette();
91 pal.setBrush( QPalette::Base, pal.button() );
92 lineEdit->setPalette( pal );
93 setLineEdit( lineEdit );
94 lineEdit->installEventFilter( this );
95 lineEdit->setContextMenuPolicy( Qt::CustomContextMenu );
96 connect( lineEdit, &QAbstractItemView::customContextMenuRequested, this, &QgsCheckableComboBox::showContextMenu );
97
98 mContextMenu = new QMenu( this );
99 mSelectAllAction = mContextMenu->addAction( tr( "Select All" ) );
100 mDeselectAllAction = mContextMenu->addAction( tr( "Deselect All" ) );
101 connect( mSelectAllAction, &QAction::triggered, this, &QgsCheckableComboBox::selectAllOptions );
102 connect( mDeselectAllAction, &QAction::triggered, this, &QgsCheckableComboBox::deselectAllOptions );
103
104 view()->viewport()->installEventFilter( this );
105 view()->setContextMenuPolicy( Qt::CustomContextMenu );
106 connect( view(), &QAbstractItemView::customContextMenuRequested, this, &QgsCheckableComboBox::showContextMenu );
107
108 connect( model(), &QStandardItemModel::rowsInserted, this, [this]( const QModelIndex &, int, int ) { updateDisplayText(); } );
109 connect( model(), &QStandardItemModel::rowsRemoved, this, [this]( const QModelIndex &, int, int ) { updateDisplayText(); } );
110 connect( model(), &QStandardItemModel::dataChanged, this, [this]( const QModelIndex &, const QModelIndex &, const QVector<int> & ) { updateDisplayText(); } );
111}
112
114{
115 return mSeparator;
116}
117
119{
120 if ( mSeparator != separator )
121 {
122 mSeparator = separator;
123 updateDisplayText();
124 }
125}
126
128{
129 return mDefaultText;
130}
131
132void QgsCheckableComboBox::setDefaultText( const QString &text )
133{
134 if ( mDefaultText != text )
135 {
136 mDefaultText = text;
137 updateDisplayText();
138 }
139}
140
141void QgsCheckableComboBox::addItemWithCheckState( const QString &text, Qt::CheckState state, const QVariant &userData )
142{
143 QComboBox::addItem( text, userData );
144 setItemCheckState( count() - 1, state );
145}
146
148{
149 QStringList items;
150
151 if ( auto *lModel = model() )
152 {
153 const QModelIndex index = lModel->index( 0, modelColumn(), rootModelIndex() );
154 const QModelIndexList indexes = lModel->match( index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly );
155 const auto constIndexes = indexes;
156 for ( const QModelIndex &index : constIndexes )
157 {
158 items += index.data().toString();
159 }
160 }
161
162 return items;
163}
164
166{
167 QVariantList data;
168
169 if ( auto *lModel = model() )
170 {
171 const QModelIndex index = lModel->index( 0, modelColumn(), rootModelIndex() );
172 const QModelIndexList indexes = lModel->match( index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly );
173 const auto constIndexes = indexes;
174 for ( const QModelIndex &index : constIndexes )
175 {
176 data += index.data( Qt::UserRole ).toString();
177 }
178 }
179
180 return data;
181}
182
183Qt::CheckState QgsCheckableComboBox::itemCheckState( int index ) const
184{
185 return static_cast<Qt::CheckState>( itemData( index, Qt::CheckStateRole ).toInt() );
186}
187
188void QgsCheckableComboBox::setItemCheckState( int index, Qt::CheckState state )
189{
190 setItemData( index, state, Qt::CheckStateRole );
191}
192
194{
195 const QVariant value = itemData( index, Qt::CheckStateRole );
196 if ( value.isValid() )
197 {
198 const Qt::CheckState state = static_cast<Qt::CheckState>( value.toInt() );
199 setItemData( index, ( state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked ), Qt::CheckStateRole );
200 }
201 updateCheckedItems();
202}
203
205{
206 if ( !mSkipHide )
207 {
208 QComboBox::hidePopup();
209 }
210 mSkipHide = false;
211}
212
214{
215 Q_UNUSED( pos )
216
217 mContextMenu->exec( QCursor::pos() );
218}
219
221{
222 blockSignals( true );
223 for ( int i = 0; i < count(); i++ )
224 {
225 setItemData( i, Qt::Checked, Qt::CheckStateRole );
226 }
227 blockSignals( false );
228 updateCheckedItems();
229}
230
232{
233 blockSignals( true );
234 for ( int i = 0; i < count(); i++ )
235 {
236 setItemData( i, Qt::Unchecked, Qt::CheckStateRole );
237 }
238 blockSignals( false );
239 updateCheckedItems();
240}
241
242bool QgsCheckableComboBox::eventFilter( QObject *object, QEvent *event )
243{
244 if ( object == lineEdit() )
245 {
246 if ( event->type() == QEvent::MouseButtonPress && static_cast<QMouseEvent *>( event )->button() == Qt::LeftButton && object == lineEdit() )
247 {
248 mSkipHide = true;
249 showPopup();
250 }
251 }
252 else if ( ( event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease ) && object == view()->viewport() )
253 {
254 mSkipHide = true;
255
256 if ( event->type() == QEvent::MouseButtonRelease && static_cast<QMouseEvent *>( event )->button() == Qt::RightButton )
257 {
258 return true;
259 }
260
261 if ( event->type() == QEvent::MouseButtonRelease )
262 {
263 const QModelIndex index = view()->indexAt( static_cast<QMouseEvent *>( event )->pos() );
264 if ( index.isValid() )
265 {
266 QgsCheckableItemModel *myModel = qobject_cast<QgsCheckableItemModel *>( model() );
267 QStandardItem *item = myModel->itemFromIndex( index );
268 item->setCheckState( item->checkState() == Qt::Checked ? Qt::Unchecked : Qt::Checked );
269 updateCheckedItems();
270 }
271 return true;
272 }
273 }
274
275 return QComboBox::eventFilter( object, event );
276}
277
278void QgsCheckableComboBox::setCheckedItems( const QStringList &items )
279{
280 const auto constItems = items;
281 for ( const QString &text : constItems )
282 {
283 const int index = findText( text );
284 setItemCheckState( index, index != -1 ? Qt::Checked : Qt::Unchecked );
285 }
286 updateCheckedItems();
287}
288
289void QgsCheckableComboBox::resizeEvent( QResizeEvent *event )
290{
291 QComboBox::resizeEvent( event );
292 updateDisplayText();
293}
294
295void QgsCheckableComboBox::updateCheckedItems()
296{
297 const QStringList items = checkedItems();
298 updateDisplayText();
299 emit checkedItemsChanged( items );
300}
301
302void QgsCheckableComboBox::updateDisplayText()
303{
304 // There is only a line edit if the combobox is in editable state
305 if ( !lineEdit() )
306 return;
307
308 QString text;
309 const QStringList items = checkedItems();
310 if ( items.isEmpty() )
311 {
312 text = mDefaultText;
313 }
314 else
315 {
316 text = items.join( mSeparator );
317 }
318
319 const QRect rect = lineEdit()->rect();
320 const QFontMetrics fontMetrics( font() );
321 text = fontMetrics.elidedText( text, Qt::ElideRight, rect.width() );
322 setEditText( text );
323}
QStyledItemDelegate subclass for QgsCheckableComboBox.
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Renders the delegate using the given painter and style option for the item specified by index.
QgsCheckBoxDelegate(QObject *parent=nullptr)
Constructor for QgsCheckBoxDelegate.
void setSeparator(const QString &separator)
Set separator used to separate items in the display text.
void setItemCheckState(int index, Qt::CheckState state)
Sets the item check state to state.
void deselectAllOptions()
Removes selection from all items.
void selectAllOptions()
Selects all items.
void checkedItemsChanged(const QStringList &items)
Emitted whenever the checked items list changed.
void setCheckedItems(const QStringList &items)
Set items which should be checked/selected.
void toggleItemCheckState(int index)
Toggles the item check state.
bool eventFilter(QObject *object, QEvent *event) override
Filters events to enable context menu.
QgsCheckableComboBox(QWidget *parent=nullptr)
Constructor for QgsCheckableComboBox.
QVariantList checkedItemsData() const
Returns userData (stored in the Qt::UserRole) associated with currently checked items.
QgsCheckableItemModel * mModel
QgsCheckableItemModel * model() const
Returns the custom item model which handles checking the items.
Qt::CheckState itemCheckState(int index) const
Returns the checked state of the item identified by index.
void addItemWithCheckState(const QString &text, Qt::CheckState state, const QVariant &userData=QVariant())
Adds an item to the combobox with the given text, check state (stored in the Qt::CheckStateRole) and ...
void showContextMenu(QPoint pos)
Display context menu which allows selecting/deselecting all items at once.
void hidePopup() override
Hides the list of items in the combobox if it is currently visible and resets the internal state.
void resizeEvent(QResizeEvent *event) override
Handler for widget resizing.
void setDefaultText(const QString &text)
Set default text which will be displayed in the widget when no items selected.
QStandardItemModel subclass which makes all items checkable by default.
void itemCheckStateChanged(const QModelIndex &index)
Emitted whenever the item's checkstate has changed.
bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override
Sets the role data for the item at index to value.
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns a combination of the item flags: items are enabled (ItemIsEnabled), selectable (ItemIsSelecta...
QgsCheckableItemModel(QObject *parent=nullptr)
Constructor for QgsCheckableItemModel.
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
Returns the data stored under the given role for the item referred to by the index.