QGIS API Documentation 3.99.0-Master (26c88405ac0)
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
28#include "moc_qgscheckablecombobox.cpp"
29
31 : QStandardItemModel( 0, 1, parent )
32{
33}
34
35Qt::ItemFlags QgsCheckableItemModel::flags( const QModelIndex &index ) const
36{
37 return QStandardItemModel::flags( index ) | Qt::ItemIsUserCheckable;
38}
39
40QVariant QgsCheckableItemModel::data( const QModelIndex &index, int role ) const
41{
42 QVariant value = QStandardItemModel::data( index, role );
43
44 if ( index.isValid() && role == Qt::CheckStateRole && !value.isValid() )
45 {
46 value = Qt::Unchecked;
47 }
48
49 return value;
50}
51
52bool QgsCheckableItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
53{
54 const bool ok = QStandardItemModel::setData( index, value, role );
55
56 if ( ok && role == Qt::CheckStateRole )
57 {
58 emit itemCheckStateChanged( index );
59 }
60
61 emit dataChanged( index, index );
62 return ok;
63}
64
65
67 : QStyledItemDelegate( parent )
68{
69}
70
71void QgsCheckBoxDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
72{
73 QStyleOptionViewItem &nonConstOpt = const_cast<QStyleOptionViewItem &>( option );
74 nonConstOpt.showDecorationSelected = false;
75 QStyledItemDelegate::paint( painter, nonConstOpt, index );
76}
77
78
80 : QComboBox( parent )
81 , mModel( new QgsCheckableItemModel( this ) )
82 , mSeparator( QStringLiteral( ", " ) )
83{
84 setModel( mModel );
85 setItemDelegate( new QgsCheckBoxDelegate( this ) );
86
87 QLineEdit *lineEdit = new QLineEdit( this );
88 lineEdit->setReadOnly( true );
89 QPalette pal = qApp->palette();
90 pal.setBrush( QPalette::Base, pal.button() );
91 lineEdit->setPalette( pal );
92 setLineEdit( lineEdit );
93 lineEdit->installEventFilter( this );
94 lineEdit->setContextMenuPolicy( Qt::CustomContextMenu );
95 connect( lineEdit, &QAbstractItemView::customContextMenuRequested, this, &QgsCheckableComboBox::showContextMenu );
96
97 mContextMenu = new QMenu( this );
98 mSelectAllAction = mContextMenu->addAction( tr( "Select All" ) );
99 mDeselectAllAction = mContextMenu->addAction( tr( "Deselect All" ) );
100 connect( mSelectAllAction, &QAction::triggered, this, &QgsCheckableComboBox::selectAllOptions );
101 connect( mDeselectAllAction, &QAction::triggered, this, &QgsCheckableComboBox::deselectAllOptions );
102
103 view()->viewport()->installEventFilter( this );
104 view()->setContextMenuPolicy( Qt::CustomContextMenu );
105 connect( view(), &QAbstractItemView::customContextMenuRequested, this, &QgsCheckableComboBox::showContextMenu );
106
107 connect( model(), &QStandardItemModel::rowsInserted, this, [this]( const QModelIndex &, int, int ) { updateDisplayText(); } );
108 connect( model(), &QStandardItemModel::rowsRemoved, this, [this]( const QModelIndex &, int, int ) { updateDisplayText(); } );
109 connect( model(), &QStandardItemModel::dataChanged, this, [this]( const QModelIndex &, const QModelIndex &, const QVector<int> & ) { updateDisplayText(); } );
110}
111
113{
114 return mSeparator;
115}
116
118{
119 if ( mSeparator != separator )
120 {
121 mSeparator = separator;
122 updateDisplayText();
123 }
124}
125
127{
128 return mDefaultText;
129}
130
131void QgsCheckableComboBox::setDefaultText( const QString &text )
132{
133 if ( mDefaultText != text )
134 {
135 mDefaultText = text;
136 updateDisplayText();
137 }
138}
139
140void QgsCheckableComboBox::addItemWithCheckState( const QString &text, Qt::CheckState state, const QVariant &userData )
141{
142 QComboBox::addItem( text, userData );
143 setItemCheckState( count() - 1, state );
144}
145
147{
148 QStringList items;
149
150 if ( auto *lModel = model() )
151 {
152 const QModelIndex index = lModel->index( 0, modelColumn(), rootModelIndex() );
153 const QModelIndexList indexes = lModel->match( index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly );
154 const auto constIndexes = indexes;
155 for ( const QModelIndex &index : constIndexes )
156 {
157 items += index.data().toString();
158 }
159 }
160
161 return items;
162}
163
165{
166 QVariantList data;
167
168 if ( auto *lModel = model() )
169 {
170 const QModelIndex index = lModel->index( 0, modelColumn(), rootModelIndex() );
171 const QModelIndexList indexes = lModel->match( index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly );
172 const auto constIndexes = indexes;
173 for ( const QModelIndex &index : constIndexes )
174 {
175 data += index.data( Qt::UserRole ).toString();
176 }
177 }
178
179 return data;
180}
181
182Qt::CheckState QgsCheckableComboBox::itemCheckState( int index ) const
183{
184 return static_cast<Qt::CheckState>( itemData( index, Qt::CheckStateRole ).toInt() );
185}
186
187void QgsCheckableComboBox::setItemCheckState( int index, Qt::CheckState state )
188{
189 setItemData( index, state, Qt::CheckStateRole );
190}
191
193{
194 const QVariant value = itemData( index, Qt::CheckStateRole );
195 if ( value.isValid() )
196 {
197 const Qt::CheckState state = static_cast<Qt::CheckState>( value.toInt() );
198 setItemData( index, ( state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked ), Qt::CheckStateRole );
199 }
200 updateCheckedItems();
201}
202
204{
205 if ( !mSkipHide )
206 {
207 QComboBox::hidePopup();
208 }
209 mSkipHide = false;
210}
211
213{
214 Q_UNUSED( pos )
215
216 mContextMenu->exec( QCursor::pos() );
217}
218
220{
221 blockSignals( true );
222 for ( int i = 0; i < count(); i++ )
223 {
224 setItemData( i, Qt::Checked, Qt::CheckStateRole );
225 }
226 blockSignals( false );
227 updateCheckedItems();
228}
229
231{
232 blockSignals( true );
233 for ( int i = 0; i < count(); i++ )
234 {
235 setItemData( i, Qt::Unchecked, Qt::CheckStateRole );
236 }
237 blockSignals( false );
238 updateCheckedItems();
239}
240
241bool QgsCheckableComboBox::eventFilter( QObject *object, QEvent *event )
242{
243 if ( object == lineEdit() )
244 {
245 if ( event->type() == QEvent::MouseButtonPress && static_cast<QMouseEvent *>( event )->button() == Qt::LeftButton && object == lineEdit() )
246 {
247 mSkipHide = true;
248 showPopup();
249 }
250 }
251 else if ( ( event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease )
252 && 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.