Bonjour tout le monde.

Pour un besoin personnel, j'ai mis en place une classe héritant de QFileSystemModel, en rendant la première colonne Checkable.
Hors, premièrement ça ne me plaisait pas de mélanger ce comportement (ajout de checkbox) à celui de base (parcourt du système de fichiers), la transformant un peu trop en "super class".
Deuxièmement, je me suis dit que si pour un autre modèle je voulais aussi ajouter des checkbox, je devrais recommencer à zéro. Si je voulais ajouter un autre comportement en plus de rendre le modèle checkable, je devrais retravailler ma classe en profondeur.

Bref, ça ne me plaisait pas!

J'ai donc déporté toute cette partie dans un ProxyModel, histoire de rendre le tout modulable.
Premièrement, j'ai mis en place AbstractRoleProxyModel, pour mutualiser les tratements communs aux différentes classes de rôles (pour le moment, juste Checkable)
Ensuite j'ai porté ma partie Checkable dans un proxy héritant de AbstractRoleProxyModel

Je suis ouvert à toute remarque/conseil/correction avis


Place au code...



Headers

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
///
/// \file : AbstractRoleProxyModel.h
///
#ifndef ABSTRACTROLEPROXYMODEL_H
#define ABSTRACTROLEPROXYMODEL_H
 
#include <QIdentityProxyModel>
#include <QHash>
#include <QByteArray>
 
class AbstractRoleProxyModel : public QIdentityProxyModel
{
    Q_OBJECT
public:
    explicit AbstractRoleProxyModel(QObject *parent = 0);
    virtual QHash<int, QByteArray> proxyRoleNames() const = 0;
    QHash<int, QByteArray> roleNames() const;
signals:
 
public slots:
 
};
 
#endif // ABSTRACTROLEPROXYMODEL_H
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
 
///
/// \file : CheckableRoleProxyModel.cpp
///
 
///
/// CheckableRoleProxyModel: a Qt proxy model to add the checkable role
/// to your models
///
/// Copyright (C) 2013  Pascal Blétard <bletard.p@live.fr>
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/// GNU General Public License for more details.
/// You should have received a copy of the GNU General Public License
/// along with this program.  If not, see <http://www.gnu.org/licenses/>.
///
/// \date 06/08/2013
/// \version 0.1
/// \author Pascal Blétard
///
 
#ifndef CHECKABLEROLEPROXYMODEL_H
#define CHECKABLEROLEPROXYMODEL_H
 
#include "AbstractRoleProxyModel.h"
#include <QSet>
#include <QHash>
#include <QMap>
#include <QDebug>
 
class CheckableRoleProxyModel : public AbstractRoleProxyModel
{
    Q_OBJECT
 
 
 
public:
 
 
 
    CheckableRoleProxyModel(QObject *parent = 0);
 
 
    ///
    /// \brief The Priority enum
    ///
    /// \see checkablePriority()
    /// \see setCheckablePriority()
    ///
    enum Priority {
        Indices, Columns, Rows
    };
 
 
    ///
    /// \brief   Returns the item flags for the given index in the model.
    ///
    /// The flags are an \c OR combination of this values:
    /// \htmlonly
    /// <table>
    /// <tr><td>Qt::NoItemFlags          </td><td>   0   </td><td>   It does not have any properties set.                </td></tr>
    /// <tr><td>Qt::ItemIsSelectable     </td><td>   1   </td><td>   It can be selected.                                 </td></tr>
    /// <tr><td>Qt::ItemIsEditable       </td><td>   2   </td><td>   It can be edited.                                   </td></tr>
    /// <tr><td>Qt::ItemIsDragEnabled    </td><td>   4   </td><td>   It can be dragged.                                  </td></tr>
    /// <tr><td>Qt::ItemIsDropEnabled    </td><td>   8   </td><td>   It can be used as a drop target.                    </td></tr>
    /// <tr><td>Qt::ItemIsUserCheckable  </td><td>   16  </td><td>   It can be checked or unchecked by the user.         </td></tr>
    /// <tr><td>Qt::ItemIsEnabled        </td><td>   32  </td><td>   The user can interact with the item.                </td></tr>
    /// <tr><td>Qt::ItemIsTristate       </td><td>   64  </td><td>   The item is checkable with three separate states.   </td></tr>
    /// <tr><td>Qt::ItemNeverHasChildren </td><td>   128 </td><td>   The item never has child items.                     </td></tr>
    /// </table>
    /// \endhtmlonly
    ///
    Qt::ItemFlags flags(const QModelIndex& index) const;
 
 
 
    ///
    /// \brief  Returns the data for the model item index with the given role
    /// \param  index
    /// \param  role
    /// \return The requested data if successful; otherwise an invalid QVariant() empty data
    ///
    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
 
 
    ///
    /// \brief  Sets the data for the model item index with the given role
    ///         to the data referenced by the value.
    ///
    /// The dataChanged() signal should be emitted if the data was successfully set.
    ///
    /// \param  index
    /// \param  value
    /// \param  role
    /// \return Returns true if successful; otherwise returns false.
    ///
    bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
 
 
 
    ///
    /// \brief  Returns a map with values for all predefined roles in the model for the item at the given index.
    /// \param  index
    /// \param  role
    /// \return All predefiened datas if successful; otherwise an invalid QVariant() empty data
    ///
    QMap<int, QVariant> itemData(const QModelIndex& index) const;
 
 
 
    // want to be implements? How it work...
    //bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles);
 
 
 
    ///
    /// \brief Returns the proxies role names.
    ///
    /// Returns a pairs list of Qt::ItemDataRole with their labels,
    /// used in the proxy.
    ///
    /// \return
    ///
    QHash<int, QByteArray> proxyRoleNames() const;
 
 
 
    ///
    /// \brief  Retrieves if an index is checkable or not.
    ///
    /// By default, class verifies first if index is checkable,
    /// then if column is checkable and finally if row is checkable.
    /// This behavior can be changed by use of setCheckablePriority()
    ///
    /// \see    checkablePriority()
    /// \see    setCheckablePriority()
    /// \see    indexCheckable()
    /// \see    columnCheckable()
    /// \see    rowCheckable()
    /// \param  index
    /// \return
    ///
    bool checkable(const QModelIndex& index) const;
 
 
 
    ///
    /// \brief  Retrieves if an index is checkable or not.
    ///
    /// Only seek in parameters of index, regardless of settings of column or of row
    ///
    /// \note   To verify if an index is really Checkable, use checkable()
    /// \see    checkable()
    /// \see    setIndexCheckable()
    /// \see    columnCheckable()
    /// \see    rowCheckable()
    /// \param  index
    /// \return Returns true if index is Checkable; otherwise returns false.
    ///
    bool indexCheckable(const QModelIndex& index) const;
 
 
 
    ///
    /// \brief  Retrieves if the column of an index is checkable or not.
    ///
    /// Only seek in parameters of the indice's column, regardless of settings of index or of row
    ///
    /// \note   To verify if an index is really Checkable, use checkable()
    /// \see    checkable()
    /// \see    setColumnCheckable()
    /// \see    indexCheckable()
    /// \see    rowCheckable()
    /// \param  index
    /// \return Returns true if the indice's column is Checkable; otherwise returns false.
    ///
    bool columnCheckable(const QModelIndex& index) const;
 
 
 
    ///
    /// \brief  Retrieves if the column is checkable or not.
    ///
    /// Only seek in parameters of the column, regardless of settings of index or of row
    ///
    /// \note   To verify if an index is really Checkable, use checkable()
    /// \see    checkable()
    /// \see    setColumnCheckable()
    /// \see    indexCheckable()
    /// \see    rowCheckable()
    /// \param  index
    /// \return Returns true if the column is Checkable; otherwise returns false.
    ///
    inline bool columnCheckable(int column) const
    {
        return m_checkable_columns.value(column, false);
    }
 
 
 
    ///
    /// \brief  Retrieves if the row of an index is checkable or not.
    ///
    /// Only seek in parameters of the indice's row, regardless of settings of index or of column
    ///
    /// \note   In case of a tree type model,
    ///         all children's indices with this row's number are checkable.
    /// \note   To verify if an index is really Checkable, use checkable()
    /// \see    checkable()
    /// \see    setRowCheckable()
    /// \see    indexCheckable()
    /// \see    columnCheckable()
    /// \param  index
    /// \return Returns true if the indice's row is Checkable; otherwise returns false.
    ///
    bool rowCheckable(const QModelIndex& index) const;
 
 
 
    ///
    /// \brief  Retrieves if the row is checkable or not.
    ///
    /// Only seek in parameters of the row, regardless of settings of index or of column
    ///
    /// \note   In case of a tree type model,
    ///         all children's indices with this row's number are checkable.
    /// \note   To verify if an index is really Checkable, use checkable()
    /// \see    checkable()
    /// \see    setRowCheckable()
    /// \see    indexCheckable()
    /// \see    columnCheckable()
    /// \param  index
    /// \return Returns true if the row is Checkable; otherwise returns false.
    ///
    inline bool rowCheckable(int row) const
    {
        return m_checkable_rows.value(row, false);
    }
 
 
    ///
    /// \brief  Sets an precise index Checkable or not.
    ///
    /// \see    checkable()
    /// \see    indexCheckable()
    /// \see    setColumnCheckable()
    /// \see    setRowCheckable()
    /// \param  index The index sets to be Checkable
    /// \param  checkable Does the column is Checkable or not
    /// \return Returns true if successful; otherwise returns false
    ///
    bool setIndexCheckable(const QModelIndex& index, bool checkable = true, Qt::CheckState state = Qt::Unchecked);
 
 
 
    ///
    /// \brief  Sets column of an index Checkable or not.
    ///
    /// \see    checkable()
    /// \see    columnCheckable()
    /// \see    setIndexCheckable()
    /// \see    setRowCheckable()
    /// \param  index The index whose column is set to Checkable
    /// \param  checkable Does the column is Checkable or not
    /// \return Returns true if successful; otherwise returns false
    ///
    bool setColumnCheckable(const QModelIndex& index, bool checkable = true);
 
 
 
    ///
    /// \brief  Sets column Checkable or not.
    ///
    /// \see    checkable()
    /// \see    columnCheckable()
    /// \see    setIndexCheckable()
    /// \see    setRowCheckable()
    /// \param  column The number of the column to set Checkable
    /// \param  checkable Does the column is Checkable or not
    /// \return Returns true if successful; otherwise returns false
    ///
    bool setColumnCheckable(int column = 0, bool checkable = true);
 
 
 
    ///
    /// \brief  Sets row of an index Checkable or not.
    ///
    /// \note   In case of a tree type model,
    ///         all indices with the same row's number become checkable.
    /// \see    checkable()
    /// \see    rowCheckable()
    /// \see    setIndexCheckable()
    /// \see    setColumnCheckable()
    /// \param  index The index whose row is set to Checkable
    /// \param  checkable Does the row is Checkable or not
    /// \return Returns true if successful; otherwise returns false
    ///
    bool setRowCheckable(const QModelIndex& index, bool checkable = true);
 
 
 
    ///
    /// \brief  Sets row Checkable or not.
    ///
    /// \note   In case of a tree type model,
    ///         all indices with this row's number become checkable.
    /// \see    checkable()
    /// \see    rowCheckable()
    /// \see    setIndexCheckable()
    /// \see    setColumnCheckable()
    /// \param  row The number of the row to set Checkable
    /// \param  checkable Does the row is Checkable or not
    /// \return Returns true if successful; otherwise returns false
    ///
    bool setRowCheckable(int row, bool checkable = true);
 
 
 
    ///
    /// \brief  Returns the order of priorities used by the class
    ///         to see if an index is Checkable or not.
    ///
    /// By default, class verifies first if index is checkable,
    /// then if column is checkable and finally if row is checkable.
    /// This behavior can be changed by use of setCheckablePriority()
    ///
    /// \see    Priority
    /// \see    setCheckablePriority()
    /// \see    checkable()
    /// \return
    ///
    inline QSet<Priority> checkablePriority() const
    {
        return m_priorities;
    }
 
 
 
    ///
    /// \brief Sets the order of priorities used by the class
    ///        to see if an index is Checkable or not.
    ///
    /// By default, class verifies first if index is checkable,
    /// then if column is checkable and finally if row is checkable.
    /// This behavior can be changed by use of setCheckablePriority()
    ///
    /// If a column was set as prioritary and is Checkable,
    /// every indices of the column will be consid as Checkable
    /// regardless of index/row settings.
    ///
    /// \note   You can't send twice the same Priority.
    /// \see    Priority
    /// \see    checkablePriority()
    /// \see    checkable()
    /// \param first Priority The first to verify
    /// \param second Priority Second to verify
    /// \param third Priority Third and last to verify
    /// \return Returns true if successful; otherwise returns false.
    ///
    bool setCheckablePriority(Priority first,Priority second,Priority third);
 
 
 
    ///
    /// \brief Sets the order of priorities used by the class
    ///        to see if an index is Checkable or not.
    ///
    /// By default, class verifies first if index is checkable,
    /// then if column is checkable and finally if row is checkable.
    /// This behavior can be changed by use of setCheckablePriority()
    ///
    /// If a column was set as prioritary and is Checkable,
    /// every indices of the column will be consid as Checkable
    /// regardless of index/row settings.
    ///
    /// \note   You can't send twice the same Priority.
    /// \see    Priority
    /// \see    checkablePriority()
    /// \see    checkable()
    /// \param  priorities \c QSet of the third priorities
    /// \return Returns true if successful; otherwise returns false.
    ///
    bool setCheckablePriority(QSet<Priority> priorities);
 
 
 
    ///
    /// \brief  Retrieves if Unchecked parents of the Checked indices
    ///         must be PartiallyChecked or not.
    /// \note   Only consistent with a tree type model
    /// \return
    ///
    inline bool partiallyCheckParents() const
    {
        return m_partially_check_parents;
    }
 
 
 
    ///
    /// \brief  Sets if Unchecked parents of the Checked indices
    ///         must be PartiallyChecked or not.
    /// \note   Only consistent with a tree type model
    /// \return
    ///
    void setPartiallyCheckParents(bool partially_check_parents);
 
 
 
    ///
    /// \brief   Turns an index as checked
    ///
    /// If  \c partiallyCheckParents(true) was called,
    /// parents are partially checked too if they aren't already checked.
    ///
    /// \see     partiallyCheckParents()
    /// \see     setPartiallyCheckParents()
    /// \see     uncheck()
    /// \see     toggleCheck()
    /// \see     checked()
    /// \param   index The\c QModelIndex of the item in the model to uncheck
    /// \return  Returns true if successful; otherwise returns false.
    ///
    inline bool check(QModelIndex index)
    {
        return setData(index, Qt::Checked, Qt::CheckStateRole);
    }
 
 
 
    ///
    /// \brief   Turns an index as unchecked
    ///
    /// If  \c partiallyCheckParents(true) was called, parents partially checked
    /// who haven't another checked childs are unchecked too.
    ///
    /// \see     partiallyCheckParents()
    /// \see     setPartiallyCheckParents()
    /// \see     check()
    /// \see     toggleCheck()
    /// \see     checked()
    /// \param   index The\c QModelIndex of the item in the model to uncheck
    /// \return  Returns true if successful; otherwise returns false.
    ///
    inline bool uncheck(QModelIndex index)
    {
        return setData(index, Qt::Unchecked, Qt::CheckStateRole);
    }
 
 
 
    ///
    /// Toggles an index between the checked and unchecked state
    ///
    /// If the \c CheckableRoleProxyModel::_partiallyCheckParents flag is active,
    /// parent's checked states follow rules explained for check() and uncheck().
    ///
    /// \see     partiallyCheckParents()
    /// \see     setPartiallyCheckParents()
    /// \see     check()
    /// \see     uncheck()
    /// \see     checked()
    /// \param   index The\c QModelIndex of the item in the model to toggle checked state.
    /// \return  Returns true if successful; otherwise returns false.
    ///
    bool toggleCheck(QModelIndex index);
 
 
 
    ///
    /// Retrieves the checked state of an index
    ///
    /// \see     check()
    /// \see     uncheck()
    /// \see     toggleCheck()
    /// \param   index The\c QModelIndex of the item in the model to retrieve checked state.
    /// \return  Returns true if is checked; otherwise returns false.
    ///
    bool checked(QModelIndex index) const;
 
 
 
 
    ///
    /// Returns a list with all checked indices
    ///
    /// \return  Returns a \c QSet<QModelIndex> filled with Checked indices;
    ///          otherwise if there is no index Checked an empty \c QSet<QModelIndex>
    ///
    inline QSet<QModelIndex> checkedIndices()
    {
        return m_checked;
    }
 
 
 
signals:
 
 
 
    ///
    /// \brief  This signal is emitted whenever the checked state has toggled.
    ///
    /// \see    checkStateChanged()
    /// \see    check()
    /// \see    uncheck()
    /// \see    toggleCheck()
    /// \see    checked()
    /// \param  index The toggled index
    ///
    void checkStateChanged(const QModelIndex index);
 
 
 
    ///
    /// \brief  This signal is emitted whenever the checked state has toggled.
    ///
    /// \see    checkStateChanged()
    /// \see    check()
    /// \see    uncheck()
    /// \see    toggleCheck()
    /// \see    checked()
    /// \param  index QModelIndex The toggled index
    /// \param  state Qt::CheckState The new state
    ///
    void checkStateChanged(const QModelIndex index, const int state);
 
 
 
private:
 
 
 
    ///
    /// \internal Recursivly sets the PartiallyChecked state on parents when
    ///           an index was Checked.
    ///
    /// This function is called only if partiallyCheckParents(true) was called
    /// on a tree type model.
    ///
    /// \see partiallyCheckParents()
    /// \see setPartiallyCheckParents()
    /// \see check()
    /// \see toggleCheck
    ///
    void _partiallyCheckParents(const QModelIndex index);
 
 
 
    ///
    /// \internal Recursivly unsets the PartiallyChecked state on parents when
    ///           an index was Unchecked.
    ///
    /// This function is called only if partiallyCheckParents(true) was called
    /// on a tree type model.
    ///
    /// \see partiallyCheckParents()
    /// \see setPartiallyCheckParents()
    /// \see check()
    /// \see toggleCheck
    ///
    void _partiallyUncheckParents(const QModelIndex index);
 
 
 
    ///
    /// \internal Pairs of indices/booleans which define
    ///           if index is checkable or not.
    ///
    QHash<QModelIndex, bool> m_checkable_index;
 
    ///
    /// \internal Pairs of columns number/booleans which define
    ///           if column is checkable or not.
    ///
    QHash<int, bool> m_checkable_columns;
 
    ///
    /// \internal Pairs of rows number/booleans which define
    ///           if row is checkable or not.
    ///
    /// In case of a tree type model, all children's indices
    /// with this row's number become checkable.
    ///
    QHash<int, bool> m_checkable_rows;
 
    ///
    /// \internal A list of all checked indices (refers to the proxy).
    ///
    QSet<QModelIndex> m_checked;
 
    ///
    /// \internal A list of all partially checked indices.
    ///
    /// Empty if partiallyCheckParents(true) wasn't called
    /// or if Model isn't a tree type model.
    ///
    QSet<QModelIndex> m_partially_checked;
 
    ///
    /// \internal The priorities order  for determine if a index is checkable or not.
    ///
    QSet<Priority> m_priorities;
 
    ///
    /// \internal Determines if unchecked parents must be partially checked
    ///           if they have some checked children.
    ///
    bool m_partially_check_parents;
};
 
#endif // CHECKABLEROLEPROXYMODEL_H
Sources

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
///
/// \file : AbstractRoleProxyModel.cpp
///
 
#include "AbstractRoleProxyModel.h"
 
AbstractRoleProxyModel::AbstractRoleProxyModel(QObject *parent) :
    QIdentityProxyModel(parent)
{
}
 
QHash<int, QByteArray> AbstractRoleProxyModel::roleNames() const
{
    if (sourceModel()) {
        QHash<int, QByteArray> source_role_names = sourceModel()->roleNames();
        QHash<int, QByteArray> proxy_role_names = proxyRoleNames();
 
        foreach (int role, proxy_role_names.keys()) {
            source_role_names.insert(role, proxy_role_names[role]);
        }
        return source_role_names;
    }
    return proxyRoleNames();
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
 
///
/// \file : CheckableRoleProxyModel.cpp
/// 
 
#include "CheckableRoleProxyModel.h"
 
 
// ----------------------
// ---- Constructors ----
// ----------------------
 
 
 
CheckableRoleProxyModel::CheckableRoleProxyModel(QObject *parent) :
    AbstractRoleProxyModel(parent)
{
    m_priorities.insert(Indices);
    m_priorities.insert(Columns);
    m_priorities.insert(Rows);
 
    m_partially_check_parents = false;
}
 
 
 
// ----------------------
// ---- Reimplements ----
// ----------------------
 
 
 
Qt::ItemFlags CheckableRoleProxyModel::
flags(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return Qt::NoItemFlags;
    }
    QModelIndex source_index = mapToSource(index);
     Qt::ItemFlags flag = sourceModel()->flags(source_index);
 
    //set flag to have only first column checkable for the whole list
    if (checkable(index)) {
        flag |= Qt::ItemIsUserCheckable;
    }
    return flag;
}
 
 
 
QVariant CheckableRoleProxyModel::
data(const QModelIndex& index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }
    QModelIndex source_index = mapToSource(index);
    // If index is checkable
    if (role == Qt::CheckStateRole && checkable(index)) {
        // item checked only if we have stored its path
        if (m_checked.contains(source_index)) {
            return QVariant(Qt::Checked);
        }
        if (m_partially_check_parents && m_partially_checked.contains(source_index)) {
            return QVariant(Qt::PartiallyChecked);
        }
        return QVariant(Qt::Unchecked);
     }
    return sourceModel()->data(source_index, role);
}
 
 
 
QMap<int, QVariant> CheckableRoleProxyModel::
itemData(const QModelIndex& index) const
{
    QModelIndex source_index = mapToSource(index);
    QMap<int, QVariant> map = sourceModel()->itemData(source_index);
    QVariant index_data = data(index, Qt::CheckStateRole);
    map.insert(Qt::CheckStateRole, index_data);
    return map;
}
 
 
 
bool CheckableRoleProxyModel::
setData(const QModelIndex& index, const QVariant& value, int role)
{
    if (!index.isValid()) {
        return false;
    }
    QModelIndex source_index = mapToSource(index);
    if (role == Qt::CheckStateRole && checkable(index)) {
        switch(value.toInt()) {
            // save checked paths
            case Qt::Checked:
                if (!m_checked.contains(source_index)) {
                    m_checked.insert(source_index);
                }
                if (m_partially_check_parents) {
                    _partiallyCheckParents(source_index);
                }
                break;
 
            // remove unchecked paths
            case Qt::Unchecked:
                // current index is checked? Damned! Go die in hell!
                if (m_checked.contains(source_index)) {
                    m_checked.remove(source_index);
                }
                //
                if (m_partially_check_parents) {
                    _partiallyUncheckParents(source_index);
                }
                break;
        }
        emit checkStateChanged(source_index);
        emit checkStateChanged(source_index, value.toInt());
        QVector<int> roles;
        roles.append(role);
        emit dataChanged(index, index, roles);
        return true;
    }
    return sourceModel()->setData(source_index, value, role);
}
 
 
 
QHash<int, QByteArray> CheckableRoleProxyModel::
proxyRoleNames() const
{
    QHash<int, QByteArray> roles;
    roles.insert(Qt::CheckStateRole, QByteArray("checkState"));
    return roles;
}
 
 
 
// ------------------
// ---- Features ----
// ------------------
 
bool CheckableRoleProxyModel::
checkable(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return false;
    }
    foreach(Priority priority, m_priorities) {
        switch (priority) {
            case Indices : {
                if (m_checkable_index.contains(index)) {
                    return indexCheckable(index);
                }
                break;
            }
            case Columns : {
                if (m_checkable_columns.contains(index.column())) {
                    return columnCheckable(index.column());
                }
                break;
            }
            case Rows : {
                if (m_checkable_rows.contains(index.row())) {
                    return rowCheckable(index.row());
                }
            }
        }
    }
    return false;
}
 
 
 
bool CheckableRoleProxyModel::
indexCheckable(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return false;
    }
    return m_checkable_index.value(index, false);
}
 
 
 
bool CheckableRoleProxyModel::
columnCheckable(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return false;
    }
    return columnCheckable(index.column());
}
 
 
 
bool CheckableRoleProxyModel::
rowCheckable(const QModelIndex& index) const
{
    if (!index.isValid()) {
        return false;
    }
    return rowCheckable(index.row());
}
 
 
 
bool CheckableRoleProxyModel::
setIndexCheckable(const QModelIndex& index, bool checkable, Qt::CheckState state)
{
    if (!index.isValid()) {
        return false;
    }
    m_checkable_index.insert(index, checkable);
 
    if (state == Qt::Checked) {
        check(index);
    }
    return true;
}
 
 
 
bool CheckableRoleProxyModel::
setColumnCheckable(const QModelIndex& index, bool checkable)
{
    if (!index.isValid()) {
        return false;
    }
    return setColumnCheckable(index.column(), checkable);
}
 
 
 
bool CheckableRoleProxyModel::
setColumnCheckable(int column, bool checkable)
{
    if (column <0) {
        return false;
    }
    m_checkable_columns.insert(column, checkable);
    return true;
}
 
 
 
bool CheckableRoleProxyModel::
setRowCheckable(const QModelIndex& index, bool checkable)
{
    if (!index.isValid()) {
        return false;
    }
    return setRowCheckable(index.row(), checkable);
}
 
 
 
bool CheckableRoleProxyModel::
setRowCheckable(int row, bool checkable)
{
    if (row < 0) {
        return false;
    }
    m_checkable_rows.insert(row, checkable);
    return true;
}
 
 
 
bool CheckableRoleProxyModel::
setCheckablePriority(Priority first,Priority second,Priority third)
{
    QSet<Priority> priorities;
    priorities.insert(first);
    priorities.insert(second);
    priorities.insert(third);
    return setCheckablePriority(priorities);
}
 
 
 
bool CheckableRoleProxyModel::
setCheckablePriority(QSet<Priority> priorities)
{
    if (priorities.size() == 3) {
        m_priorities = priorities;
        return true;
    }
    return false;
}
 
 
 
void CheckableRoleProxyModel::
setPartiallyCheckParents(bool partially_check_parents)
{
    // only if setting have changed
    if (m_partially_check_parents != partially_check_parents) {
        m_partially_check_parents = partially_check_parents;
        if (partially_check_parents) {
            // partially check parents for each checked index
            foreach(QModelIndex index, m_checked) {
                _partiallyCheckParents(index);
            }
        }
        else {
            m_partially_checked.clear();
        }
        emit layoutChanged();
    }
}
 
 
 
bool CheckableRoleProxyModel::
toggleCheck(const QModelIndex index)
{
    if (checked(index)) {
        return uncheck(index);
    }
    return check(index);
}
 
 
 
bool CheckableRoleProxyModel::
checked(const QModelIndex index) const
{
    return (Qt::Checked == (Qt::CheckState)index.data(Qt::CheckStateRole).toInt());
}
 
// -------------------
// ----- Private -----
// -------------------
 
 
void CheckableRoleProxyModel::
_partiallyCheckParents(const QModelIndex index)
{
    // source's parent exists?
    QModelIndex source_parent = index.parent();
    if (source_parent.isValid()) {
 
        // if proxy parent index is checkable but not partially checked
        QModelIndex proxy_parent = mapFromSource(source_parent);
        bool partially_checked = m_partially_checked.contains(source_parent);
 
        if (checkable(proxy_parent) && !partially_checked) {
            // partially check parent and notify it
            m_partially_checked.insert(source_parent);
            emit dataChanged(proxy_parent, proxy_parent);
        }
        // if parent is checkable (or not), maybe his ancestors are
        _partiallyCheckParents(source_parent);
    }
}
 
 
 
void CheckableRoleProxyModel::
_partiallyUncheckParents(const QModelIndex index)
{
    // source parent exists?
    QModelIndex source_parent = index.parent();
    if (source_parent.isValid()) {
 
        // if proxy parent index is checkable and partially checked
        QModelIndex proxy_parent = mapFromSource(source_parent);
        bool partially_checked = m_partially_checked.contains(source_parent);
 
        if (checkable(proxy_parent) && partially_checked) {
            bool childChecked = false;
            // check if parent have another checked childs
            for (int i = 0; source_parent.child(i,0).isValid(); ++i) {
                partially_checked = m_partially_checked.contains(source_parent.child(i,0));
                bool checked = m_checked.contains(source_parent.child(i,0));
                if(partially_checked || checked) {
                    childChecked = true;
                    break;
                }
            }
            // If not, uncheck it
            if (!childChecked) {
                m_partially_checked.remove(source_parent);
                emit dataChanged(proxy_parent, proxy_parent);
            }
            //todo: verify not after }
            _partiallyUncheckParents(source_parent);
 
        }
    }
}
Exemple

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
///
/// \file : FileSystemModel.h
///
 
#ifndef FILESYSTEMMODEL_H
#define FILESYSTEMMODEL_H
 
#include <QFileSystemModel>
 
class FileSystemModel : public QFileSystemModel
{
    Q_OBJECT
public:
 
    ///
    /// Returns true if parent has any children or has the Qt::ItemNeverHasChildren flag set;
    /// otherwise returns false.
    ///
    /// Use rowCount() on the parent to find out the number of children.
    ///
    /// \remarks Reimplemented to avoid empty directories to be collapsables
    ///          and to implement the \c Qt::ItemNeverHasChildren flag.
    /// \see     rowCount()
    /// \see     child()
    ///
    ///
    bool hasChildren(const QModelIndex &parent) const;
};
 
#endif // FILESYSTEMMODEL_H
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
///
/// \file : Window.h
///
 
#ifndef WINDOW_H
#define WINDOW_H
 
#include <QWidget>
#include <QTreeView>
#include <QGridLayout>
 
#include "../src/FileSystemModel.h"
#include "../src/CheckableRoleProxyModel.h"
 
class Window : public QWidget
{
    Q_OBJECT
 
public:
    Window(QWidget *parent = 0);
};
 
#endif // WINDOW_H
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
///
/// \file : FileSystemModel.cpp
///
 
#include "FileSystemModel.h"
 
bool FileSystemModel::hasChildren(const QModelIndex &parent) const
{
    // return false if item cant have children
    if (parent.flags() &  Qt::ItemNeverHasChildren) {
        return false;
    }
    // return if at least one child exists
    return QDirIterator(filePath(parent),
                        filter() | QDir::NoDotAndDotDot,
                        QDirIterator::NoIteratorFlags
                        ).hasNext();
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
///
/// \file : Windowcpp
///
 
#include "Window.h"
 
Window::Window(QWidget *parent)
    : QWidget(parent)
{
    FileSystemModel* model = new FileSystemModel();
    model->setRootPath("");
 
    CheckableRoleProxyModel* checkable = new CheckableRoleProxyModel(this);
    checkable->setColumnCheckable(0, true);
    checkable->setPartiallyCheckParents(true);
 
    checkable->setSourceModel(model);
 
    QTreeView * m_dir = new QTreeView;
    m_dir->setModel(checkable);
 
    QGridLayout * layout = new QGridLayout;
    layout->addWidget(m_dir, 0, 0, 6, 8);
    setLayout(layout);
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
///
/// \file : main.cpp
///
 
#include "Window.h"
#include <QApplication>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window w;
    w.show();
 
    return a.exec();
}