summaryrefslogtreecommitdiffstats
path: root/src/corelib/itemmodels/qrangemodel.cpp
blob: f533605c7215a5a32fc5be4bc1a85706d2826550 (plain)
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Qt-Security score:significant reason:default

#include "qrangemodel.h"
#include <QtCore/qsize.h>

#include <QtCore/private/qabstractitemmodel_p.h>

#include <variant>

QT_BEGIN_NAMESPACE

class QRangeModelPrivate : QAbstractItemModelPrivate
{
    Q_DECLARE_PUBLIC(QRangeModel)

public:
    explicit QRangeModelPrivate(std::unique_ptr<QRangeModelImplBase, QRangeModelImplBase::Deleter> impl)
        : impl(std::move(impl))
    {}

    std::unique_ptr<QRangeModelImplBase, QRangeModelImplBase::Deleter> impl;
    friend class QRangeModelImplBase;

    static QRangeModelPrivate *get(QRangeModel *model) { return model->d_func(); }
    static const QRangeModelPrivate *get(const QRangeModel *model) { return model->d_func(); }

    mutable QHash<int, QByteArray> m_roleNames;
    QRangeModel::AutoConnectPolicy m_autoConnectPolicy = QRangeModel::AutoConnectPolicy::None;
    bool m_dataChangedDispatchBlocked = false;

    static void emitDataChanged(const QModelIndex &index, int role)
    {
        const auto *model = static_cast<const QRangeModel *>(index.model());
        if (!get(model)->m_dataChangedDispatchBlocked) {
            const auto *emitter = QRangeModelImplBase::getImplementation(model);
            const_cast<QRangeModelImplBase *>(emitter)->dataChanged(index, index, {role});
        }
    }
};

struct PropertyChangedHandler
{
    PropertyChangedHandler(const QPersistentModelIndex &index, int role)
        : storage{Data{index, role}}
    {}

    // move-only
    ~PropertyChangedHandler() = default;
    PropertyChangedHandler(PropertyChangedHandler &&other) noexcept
        : connection(std::move(other.connection)), storage(std::move(other.storage))
    {
        Q_ASSERT(std::holds_alternative<Data>(storage));
        // A moved-from handler is essentially a reference to the moved-to
        // handler (which lives inside QSlotObject/QCallableObject). This
        // way we can update the stored handler with the created connection.
        other.storage = this;
    }
    PropertyChangedHandler &operator=(PropertyChangedHandler &&) = delete;
    PropertyChangedHandler(const PropertyChangedHandler &) = delete;
    PropertyChangedHandler &operator=(const PropertyChangedHandler &) = delete;

    // we can assign a connection to a moved-from handler to update the
    // handler stored in the QSlotObject/QCallableObject.
    PropertyChangedHandler &operator=(const QMetaObject::Connection &connection) noexcept
    {
        Q_ASSERT(std::holds_alternative<PropertyChangedHandler *>(storage));
        std::get<PropertyChangedHandler *>(storage)->connection = connection;
        return *this;
    }

    void operator()();

private:
    QMetaObject::Connection connection;
    struct Data
    {
        QPersistentModelIndex index;
        int role = -1;
    };
    std::variant<PropertyChangedHandler *, Data> storage;
};

void PropertyChangedHandler::operator()()
{
    Q_ASSERT(std::holds_alternative<Data>(storage));
    const auto &data = std::get<Data>(storage);
    if (!data.index.isValid()) {
        if (!QObject::disconnect(connection))
            qWarning() << "Failed to break connection for" << Qt::ItemDataRole(data.role);
    } else {
        QRangeModelPrivate::emitDataChanged(data.index, data.role);
    }
}

struct ConstPropertyChangedHandler
{
    ConstPropertyChangedHandler(const QModelIndex &index, int role)
        : index(index), role(role)
    {}

    // move-only
    ~ConstPropertyChangedHandler() = default;
    ConstPropertyChangedHandler(ConstPropertyChangedHandler &&other) noexcept = default;

    void operator()() { QRangeModelPrivate::emitDataChanged(index, role); }

private:
    QModelIndex index;
    int role = -1;
};

QRangeModel::QRangeModel(QRangeModelImplBase *impl, QObject *parent)
    : QAbstractItemModel(*new QRangeModelPrivate({impl, {}}), parent)
{
}

QRangeModelImplBase *QRangeModelImplBase::getImplementation(QRangeModel *model)
{
    return model->d_func()->impl.get();
}

const QRangeModelImplBase *QRangeModelImplBase::getImplementation(const QRangeModel *model)
{
    return model->d_func()->impl.get();
}

QScopedValueRollback<bool> QRangeModelImplBase::blockDataChangedDispatch()
{
    return QScopedValueRollback(m_rangeModel->d_func()->m_dataChangedDispatchBlocked, true);
}

/*!
    \internal

    Using \a metaObject, return a mapping of roles to the matching QMetaProperties.
*/
QHash<int, QMetaProperty> QRangeModelImplBase::roleProperties(const QAbstractItemModel &model,
                                                              const QMetaObject &metaObject)
{
    const auto roles = model.roleNames();
    QHash<int, QMetaProperty> result;
    for (auto &&[role, roleName] : roles.asKeyValueRange()) {
        if (role == Qt::RangeModelDataRole)
            continue;
        result[role] = metaObject.property(metaObject.indexOfProperty(roleName));
    }
    return result;
}

template <auto Handler>
static bool connectPropertiesHelper(const QModelIndex &index, QObject *item, QObject *context,
                                    const QHash<int, QMetaProperty> &properties)
{
    if (!item)
        return false;
    for (auto &&[role, property] : properties.asKeyValueRange()) {
        if (property.hasNotifySignal()) {
            if (!Handler(index, item, context, role, property))
                return false;
        } else {
            qWarning() << "Property" << property.name() << "for" << Qt::ItemDataRole(role)
                                     << "has no notify signal";
        }
    }
    return true;
}

bool QRangeModelImplBase::connectProperty(const QModelIndex &index, QObject *item, QObject *context,
                                          int role, const QMetaProperty &property)
{
    if (!item)
        return false;
    PropertyChangedHandler handler{index, role};
    auto connection = property.enclosingMetaObject()->connect(item, property.notifySignal(),
                                                              context, std::move(handler));
    if (!connection) {
        qWarning() << "Failed to connect to" << item << property.name();
        return false;
    } else {
        // handler is now in moved-from state, and acts like a reference to
        // the handler that is stored in the QSlotObject/QCallableObject.
        // This assignment updates the stored handler's connection with the
        // QMetaObject::Connection handle, and should look harmless for
        // static analyzers.
        handler = connection;
    }
    return true;
}

bool QRangeModelImplBase::connectProperties(const QModelIndex &index, QObject *item, QObject *context,
                                            const QHash<int, QMetaProperty> &properties)
{
    return connectPropertiesHelper<QRangeModelImplBase::connectProperty>(index, item, context, properties);
}

bool QRangeModelImplBase::connectPropertyConst(const QModelIndex &index, QObject *item, QObject *context,
                                               int role, const QMetaProperty &property)
{
    if (!item)
        return false;
    ConstPropertyChangedHandler handler{index, role};
    if (!property.enclosingMetaObject()->connect(item, property.notifySignal(),
                                                 context, std::move(handler))) {
        qWarning() << "Failed to connect to" << item << property.name();
        return false;
    } else {
        return true;
    }
}

bool QRangeModelImplBase::connectPropertiesConst(const QModelIndex &index, QObject *item, QObject *context,
                                                 const QHash<int, QMetaProperty> &properties)
{
    return connectPropertiesHelper<QRangeModelImplBase::connectPropertyConst>(index, item, context, properties);
}

/*!
    \class QRangeModel
    \inmodule QtCore
    \since 6.10
    \ingroup model-view
    \brief QRangeModel implements QAbstractItemModel for any C++ range.
    \reentrant

    QRangeModel can make the data in any sequentially iterable C++ type
    available to the \l{Model/View Programming}{model/view framework} of Qt.
    This makes it easy to display existing data structures in the Qt Widgets
    and Qt Quick item views, and to allow the user of the application to
    manipulate the data using a graphical user interface.

    To use QRangeModel, instantiate it with a C++ range and set it as
    the model of one or more views:

    \snippet qrangemodel/main.cpp array

    \section1 Constructing the model

    The range can be any C++ type for which the standard methods
    \c{std::begin} and \c{std::end} are implemented, and for which the
    returned iterator type satisfies \c{std::forward_iterator}. Certain model
    operations will perform better if \c{std::size} is available, and if the
    iterator satisfies \c{std::random_access_iterator}.

    The range must be provided when constructing the model; there is no API to
    set the range later, and there is no API to retrieve the range from the
    model. The range can be provided by value, reference wrapper, or pointer.
    How the model was constructed defines whether changes through the model API
    will modify the original data.

    When constructed by value, the model makes a copy of the range, and
    QAbstractItemModel APIs that modify the model, such as setData() or
    insertRows(), have no impact on the original range.

    \snippet qrangemodel/main.cpp value

    As there is no API to retrieve the range again, constructing the model from
    a range by value is mostly only useful for displaying read-only data.
    Changes to the data can be monitored using the signals emitted by the
    model, such as \l{QAbstractItemModel}{dataChanged()}.

    To make modifications of the model affect the original range, provide the
    range either by pointer:

    \snippet qrangemodel/main.cpp pointer

    or through a reference wrapper:

    \snippet qrangemodel/main.cpp reference_wrapper

    In this case, QAbstractItemModel APIs that modify the model also modify the
    range. Methods that modify the structure of the range, such as insertRows()
    or removeColumns(), use standard C++ container APIs \c{resize()},
    \c{insert()}, \c{erase()}, in addition to dereferencing a mutating iterator
    to set or clear the data.

    \note Once the model has been constructed and passed on to a view, the
    range that the model operates on must no longer be modified directly. Views
    on the model wouldn't be informed about the changes, and structural changes
    are likely to corrupt instances of QPersistentModelIndex that the model
    maintains.

    The caller must make sure that the range's lifetime exceeds the lifetime of
    the model.

    Use smart pointers to make sure that the range is only deleted when all
    clients are done with it.

    \snippet qrangemodel/main.cpp smart_pointer

    QRangeModel supports both shared and unique pointers.

    \section2 Read-only or mutable

    For ranges that are const objects, for which access always yields constant
    values, or where the required container APIs are not available,
    QRangeModel implements write-access APIs to do nothing and return
    \c{false}. In the example using \c{std::array}, the model cannot add or
    remove rows, as the number of entries in a C++ array is fixed. But the
    values can be changed using setData(), and the user can trigger editing of
    the values in the list view. By making the array const, the values also
    become read-only.

    \snippet qrangemodel/main.cpp const_array

    The values are also read-only if the element type is const, like in

    \snippet qrangemodel/main.cpp const_values

    In the above examples using \c{std::vector}, the model can add or remove
    rows, and the data can be changed. Passing the range as a constant
    reference will make the model read-only.

    \snippet qrangemodel/main.cpp const_ref

    \note If the values in the range are const, then it's also not possible
    to remove or insert columns and rows through the QAbstractItemModel API.
    For more granular control, implement \l{the C++ tuple protocol}.

    \section1 Rows and columns

    The elements in the range are interpreted as rows of the model. Depending
    on the type of these row elements, QRangeModel exposes the range as a
    list, a table, or a tree.

    If the row elements are simple values, then the range gets represented as a
    list.

    \snippet qrangemodel/main.cpp list_of_int

    If the type of the row elements is an iterable range, such as a vector,
    list, or array, then the range gets represented as a table.

    \snippet qrangemodel/main.cpp grid_of_numbers

    If the row type provides the standard C++ container APIs \c{resize()},
    \c{insert()}, \c{erase()}, then columns can be added and removed via
    insertColumns() and removeColumns(). All rows are required to have
    the same number of columns.

    \section2 Structs and gadgets as rows

    If the row type implements \l{the C++ tuple protocol}, then the range gets
    represented as a table with a fixed number of columns.

    \snippet qrangemodel/main.cpp pair_int_QString

    An easier and more flexible alternative to implementing the tuple protocol
    for a C++ type is to use Qt's \l{Meta-Object System}{meta-object system} to
    declare a type with \l{Qt's Property System}{properties}. This can be a
    value type that is declared as a \l{Q_GADGET}{gadget}, or a QObject subclass.

    \snippet qrangemodel/main.cpp gadget

    Using QObject subclasses allows properties to be \l{Qt Bindable Properties}
    {bindable}, or to have change notification signals. However, using QObject
    instances for items has significant memory overhead.

    Using Qt gadgets or objects is more convenient and can be more flexible
    than implementing the tuple protocol. Those types are also directly
    accessible from within QML. However, the access through \l{the property system}
    comes with some runtime overhead. For performance critical models, consider
    implementing the tuple protocol for compile-time generation of the access
    code.

    \section2 Multi-role items

    The type of the items that the implementations of data(), setData(),
    clearItemData() etc. operate on can be the same across the entire model -
    like in the \c{gridOfNumbers} example above. But the range can also have
    different item types for different columns, like in the \c{numberNames}
    case.

    By default, the value gets used for the Qt::DisplayRole and Qt::EditRole
    roles. Most views expect the value to be
    \l{QVariant::canConvert}{convertible to and from a QString} (but a custom
    delegate might provide more flexibility).

    \section3 Associative containers with multiple roles

    If the item is an associative container that uses \c{int},
    \l{Qt::ItemDataRole}, or QString as the key type, and QVariant as the
    mapped type, then QRangeModel interprets that container as the storage
    of the data for multiple roles. The data() and setData() functions return
    and modify the mapped value in the container, and setItemData() modifies all
    provided values, itemData() returns all stored values, and clearItemData()
    clears the entire container.

    \snippet qrangemodel/main.cpp color_map

    The most efficient data type to use as the key is Qt::ItemDataRole or
    \c{int}. When using \c{int}, itemData() returns the container as is, and
    doesn't have to create a copy of the data.

    \section3 Gadgets and Objects as multi-role items

    Gadgets and QObject types can also be represented as multi-role items. The
    \l{The Property System}{properties} of those items will be used for the
    role for which the \l{roleNames()}{name of a role} matches. If all items
    hold the same type of gadget or QObject, then the \l{roleNames()}
    implementation in QRangeModel will return the list of properties of that
    type.

    \snippet qrangemodel/main.cpp color_gadget_decl
    \snippet qrangemodel/main.cpp color_gadget_impl
    \snippet qrangemodel/main.cpp color_gadget_end

    When used in a table, this is the default representation for gadgets:

    \snippet qrangemodel/main.cpp color_gadget_table

    When used in a list, these types are however by default represented as
    multi-column rows, with each property represented as a separate column. To
    force a gadget to be represented as a multi-role item in a list, declare
    the gadget as a multi-role type by specializing QRoleModel::RowOptions,
    with a \c{static constexpr auto rowCategory} member variable set to
    MultiRoleItem.

    \snippet qrangemodel/main.cpp color_gadget_decl
    \dots
    \snippet qrangemodel/main.cpp color_gadget_end
    \snippet qrangemodel/main.cpp color_gadget_multi_role_gadget

    You can also wrap such types into a single-element tuple, turning the list
    into a table with a single column:

    \snippet qrangemodel/main.cpp color_gadget_single_column

    In this case, note that direct access to the elements in the list data
    needs to use \c{std::get}:

    \snippet qrangemodel/main.cpp color_gadget_single_column_access_get

    or alternatively a structured binding:

    \snippet qrangemodel/main.cpp color_gadget_single_column_access_sb

    \section2 Rows as values or pointers

    In the examples so far, we have always used QRangeModel with ranges that
    hold values. QRangeModel can also operate on ranges that hold pointers,
    including smart pointers. This allows QRangeModel to operate on ranges of
    polymorph types, such as QObject subclasses.

    \snippet qrangemodel/main.cpp object_0
    \dots
    \snippet qrangemodel/main.cpp object_1

    \snippet qrangemodel/main.cpp vector_of_objects_0
    \dots
    \snippet qrangemodel/main.cpp vector_of_objects_1
    \snippet qrangemodel/main.cpp vector_of_objects_2

    As with values, the type of the row defines whether the range is
    represented as a list, table, or tree. Rows that are QObjects will present
    each property as a column, unless the QRangeModel::RowOptions template is
    specialized to declare the type as a multi-role item.

    \snippet qrangemodel/main.cpp vector_of_multirole_objects_0
    \snippet qrangemodel/main.cpp vector_of_multirole_objects_1
    \dots
    \snippet qrangemodel/main.cpp vector_of_multirole_objects_2

    \note If the range holds raw pointers, then you have to construct
    QRangeModel from a pointer or reference wrapper of the range. Otherwise the
    ownership of the data becomes ambiguous, and a copy of the range would
    still be operating on the same actual row data, resulting in unexpected
    side effects.

    \section2 Subclassing QRangeModel

    Subclassing QRangeModel makes it possible to add convenient APIs that take
    the data type and structure of the range into account.

    \snippet qrangemodel/main.cpp subclass_header

    When doing so, add the range as a private member, and call the QRangeModel
    constructor with a reference wrapper or pointer to that member. This
    properly encapsulates the data and avoids direct access.

    \snippet qrangemodel/main.cpp subclass_API

    Add member functions to provide type-safe access to the data, using the
    QAbstractItemModel API to perform any operation that modifies the range.
    Read-only access can directly operate on the data structure.

    \section1 Trees of data

    QRangeModel can represent a data structure as a tree model. Such a
    tree data structure needs to be homomorphic: on all levels of the tree, the
    list of child rows needs to use the exact same representation as the tree
    itself. In addition, the row type needs be of a static size: either a gadget
    or QObject type, or a type that implements \l{the C++ tuple protocol}.

    To represent such data as a tree, QRangeModel has to be able to traverse the
    data structure: for any given row, the model needs to be able to retrieve
    the parent row, and the optional span of children. These traversal functions
    can be provided implicitly through the row type, or through an explicit
    protocol type.

    \section2 Implicit tree traversal protocol

    \snippet qrangemodel/main.cpp tree_protocol_0

    The tree itself is a vector of \c{TreeRow} values. See \l{Tree Rows as
    pointers or values} for the considerations on whether to use values or
    pointers of items for the rows.

    \snippet qrangemodel/main.cpp tree_protocol_1

    The row class can be of any fixed-size type described above: a type that
    implements the tuple protocol, a gadget, or a QObject. In this example, we
    use a gadget.

    Each row item needs to maintain a pointer to the parent row, as well as an
    optional range of child rows. That range has to be identical to the range
    structure used for the tree itself.

    Making the row type default constructible is optional, and allows the model
    to construct new row data elements, for instance in the insertRow() or
    moveRows() implementations.

    \snippet qrangemodel/main.cpp tree_protocol_2

    The tree traversal protocol can then be implemented as member functions of
    the row data type. A const \c{parentRow()} function has to return a pointer
    to a row item; and the \c{childRows()} function has to return a reference
    to a const \c{std::optional} that can hold the optional child range.

    These two functions are sufficient for the model to navigate the tree as a
    read-only data structure. To allow the user to edit data in a view, and the
    model to implement mutating model APIs such as insertRows(), removeRows(),
    and moveRows(), we have to implement additional functions for write-access:

    \snippet qrangemodel/main.cpp tree_protocol_3

    The model calls the \c{setParentRow()} function and mutable \c{childRows()}
    overload to move or insert rows into an existing tree branch, and to update
    the parent pointer should the old value have become invalid. The non-const
    overload of \c{childRows()} provides in addition write-access to the row
    data.

    \note The model performs setting the parent of a row, removing that row
    from the old parent, and adding it to the list of the new parent's children,
    as separate steps. This keeps the protocol interface small.

    \dots
    \snippet qrangemodel/main.cpp tree_protocol_4

    The rest of the class implementation is not relevant for the model, but
    a \c{addChild()} helper provides us with a convenient way to construct the
    initial state of the tree.

    \snippet qrangemodel/main.cpp tree_protocol_5

    A QRangeModel instantiated with an instance of such a range will
    represent the data as a tree.

    \snippet qrangemodel/main.cpp tree_protocol_6

    \section2 Tree traversal protocol in a separate class

    The tree traversal protocol can also be implemented in a separate class.

    \snippet qrangemodel/main.cpp explicit_tree_protocol_0

    Pass an instance of this protocol implementation to the QRangeModel
    constructor:

    \snippet qrangemodel/main.cpp explicit_tree_protocol_1

    \section2 Tree Rows as pointers or values

    The row type of the data range can be either a value, or a pointer. In
    the code above we have been using the tree rows as values in a vector,
    which avoids that we have to deal with explicit memory management. However,
    a vector as a contiguous block of memory invalidates all iterators and
    references when it has to reallocate the storage, or when inserting or
    removing elements. This impacts the pointer to the parent item, which is
    the location of the parent row within the vector. Making sure that this
    parent (and QPersistentModelIndex instances referring to items within it)
    stays valid can incurr substantial performance overhead. The
    QRangeModel implementation has to assume that all references into the
    range become invalid when modifying the range.

    Alternatively, we can also use a range of row pointers as the tree type:

    \snippet qrangemodel/main.cpp tree_of_pointers_0

    In this case, we have to allocate all TreeRow instances explicitly using
    operator \c{new}, and implement the destructor to \c{delete} all items in
    the vector of children.

    \snippet qrangemodel/main.cpp tree_of_pointers_1
    \snippet qrangemodel/main.cpp tree_of_pointers_2

    Before we can construct a model that represents this data as a tree, we need
    to also implement the tree traversal protocol.

    \snippet qrangemodel/main.cpp tree_of_pointers_3

    An explicit protocol implementation for mutable trees of pointers has to
    provide two additional member functions, \c{newRow()} and
    \c{deleteRow(RowType *)}.

    \snippet qrangemodel/main.cpp tree_of_pointers_4

    The model will call those functions when creating new rows in insertRows(),
    and when removing rows in removeRows(). In addition, if the model has
    ownership of the data, then it will also delete all top-level rows upon
    destruction. Note how in this example, we move the tree into the model, so
    we must no longer perform any operations on it. QRangeModel, when
    constructed by moving tree-data with row-pointers into it, will take
    ownership of the data, and delete the row pointers in it's destructor.

    Using pointers as rows comes with some memory allocation and management
    overhead. However, the references to the row items remain stable, even when
    they are moved around in the range, or when the range reallocates. This can
    significantly reduce the cost of making modifications to the model's
    structure when using insertRows(), removeRows(), or moveRows().

    Each choice has different performance and memory overhead trade-offs. The
    best option depends on the exact use case and data structure used.

    \section2 The C++ tuple protocol

    As seen in the \c{numberNames} example above, the row type can be a tuple,
    and in fact any type that implements the tuple protocol. This protocol is
    implemented by specializing \c{std::tuple_size} and \c{std::tuple_element},
    and overloading the unqualified \c{get} function. Do so for your custom row
    type to make existing structured data available to the model/view framework
    in Qt.

    \snippet qrangemodel/main.cpp tuple_protocol

    In the above implementation, the \c{title} and \c{author} values of the
    \c{Book} type are returned as \c{const}, so the model flags items in those
    two columns as read-only. The user won't be able to trigger editing, and
    setData() does nothing and returns false. For \c{summary} and \c{rating}
    the implementation returns the same value category as the book, so when
    \c{get} is called with a mutable reference to a \c{Book}, then it will
    return a mutable reference of the respective variable. The model makes
    those columns editable, both for the user and for programmatic access.

    \note The implementation of \c{get} above requires C++23.

    \sa {Model/View Programming}
*/

/*!
    \class QRangeModel::RowOptions
    \inmodule QtCore
    \ingroup model-view
    \brief The RowOptions template provides a customization point to control
           how QRangeModel represents types used as rows.
    \since 6.10

    Specialize this template for the type used in your range, and add the
    relevant members.

    \table
    \header
        \li Member
        \li Values
    \row
        \li static constexpr RowCategory rowCategory
        \li RowCategory
    \endtable

    \snippet qrangemodel/main.cpp color_gadget_decl
    \dots
    \snippet qrangemodel/main.cpp color_gadget_end
    \snippet qrangemodel/main.cpp color_gadget_multi_role_gadget

*/

/*!
    \enum QRangeModel::RowCategory

    This enum describes how QRangeModel should present the elements of the
    range it was constructed with.

    \value Default
           QRangeModel decides how to present the rows.
    \value MultiRoleItem
           QRangeModel will present items with a meta object as multi-role
           items, also when used in a one-dimensional range.

    Specialize the RowOptions template for your type, and add a public member
    variable \c{static constexpr auto rowCategory} with one of the values from
    this enum.

    \sa RowOptions
*/

/*!
    \class QRangeModel::ItemAccess
    \inmodule QtCore
    \ingroup model-view
    \brief The ItemAccess template provides a customization point to control
           how QRangeModel accesses role data of individual items.
    \since 6.11

    Specialize this template for the type used in your data structure, and
    implement \c{readRole()} and \c{writeRole()} members to access the role-
    specific data of your type.

    \code
    template <>
    struct QRangeModel::ItemAccess<ItemType>
    {
        static QVariant readRole(const ItemType &item, int role)
        {
            switch (role) {
                // ...
            }
            return {};
        }

        static bool writeRole(ItemType &item, const QVariant &data, int role)
        {
            bool ok = false;
            switch (role) {
                // ...
            }

            return ok;
        }
    };
    \endcode

    A specialization of this type will take precedence over any predefined
    behavior. Do not specialize this template for types you do not own.
*/

/*!
    \fn template <typename Range, QRangeModelDetails::if_table_range<Range>> QRangeModel::QRangeModel(Range &&range, QObject *parent)
    \fn template <typename Range, QRangeModelDetails::if_tree_range<Range>> QRangeModel::QRangeModel(Range &&range, QObject *parent)
    \fn template <typename Range, typename Protocol, QRangeModelDetails::if_tree_range<Range, Protocol>> QRangeModel::QRangeModel(Range &&range, Protocol &&protocol, QObject *parent)

    Constructs a QRangeModel instance that operates on the data in \a range.
    The \a range has to be a sequential range for which \c{std::begin} and
    \c{std::end} are available. If \a protocol is provided, then the model
    will represent the range as a tree using the protocol implementation. The
    model instance becomes a child of \a parent.

    The \a range can be a pointer or reference wrapper, in which case mutating
    model APIs (such as \l{setData()} or \l{insertRow()}) will modify the data
    in the referenced range instance. If \a range is a value (or moved into the
    model), then connect to the signals emitted by the model to respond to
    changes to the data.

    QRangeModel will not access the \a range while being constructed. This
    makes it legal to pass a pointer or reference to a range object that is not
    fully constructed yet to this constructor, for example when \l{Subclassing
    QRangeModel}{subclassing QRangeModel}.

    If the \a range was moved into the model, then the range and all data in it
    will be destroyed upon destruction of the model.

    \note While the model does not take ownership of the range object otherwise,
    you must not modify the \a range directly once the model has been constructed
    and  and passed on to a view. Such modifications will not emit signals
    necessary to keep model users (other models or views) synchronized with the
    model, resulting in inconsistent results, undefined behavior, and crashes.
*/

/*!
    Destroys the QRangeModel.

    The range that the model was constructed from is not accessed, and only
    destroyed if the model was constructed from a moved-in range.
*/
QRangeModel::~QRangeModel() = default;

/*!
    \reimp

    Returns the index of the model item at \a row and \a column in \a parent.

    Passing a valid parent produces an invalid index for models that operate on
    list and table ranges.

    \sa parent()
*/
QModelIndex QRangeModel::index(int row, int column, const QModelIndex &parent) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::Index>(row, column, parent);
}

/*!
    \reimp

    Returns the parent of the item at the \a child index.

    This function always produces an invalid index for models that operate on
    list and table ranges. For models operation on a tree, this function
    returns the index for the row item returned by the parent() implementation
    of the tree traversal protocol.

    \sa index(), hasChildren()
*/
QModelIndex QRangeModel::parent(const QModelIndex &child) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::Parent>(child);
}

/*!
    \reimp

    Returns the sibling at \a row and \a column for the item at \a index, or an
    invalid QModelIndex if there is no sibling at that location.

    This implementation is significantly faster than going through the parent()
    of the \a index.

    \sa index(), QModelIndex::row(), QModelIndex::column()
*/
QModelIndex QRangeModel::sibling(int row, int column, const QModelIndex &index) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::Sibling>(row, column, index);
}

/*!
    \reimp

    Returns the number of rows under the given \a parent. This is the number of
    items in the root range for an invalid \a parent index.

    If the \a parent index is valid, then this function always returns 0 for
    models that operate on list and table ranges. For trees, this returns the
    size of the range returned by the childRows() implementation of the tree
    traversal protocol.

    \sa columnCount(), insertRows(), hasChildren()
*/
int QRangeModel::rowCount(const QModelIndex &parent) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::RowCount>(parent);
}

/*!
    \reimp

    Returns the number of columns of the model. This function returns the same
    value for all \a parent indexes.

    For models operating on a statically sized row type, this returned value is
    always the same throughout the lifetime of the model. For models operating
    on dynamically sized row type, the model returns the number of items in the
    first row, or 0 if the model has no rows.

    \sa rowCount, insertColumns()
*/
int QRangeModel::columnCount(const QModelIndex &parent) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::ColumnCount>(parent);
}

/*!
    \reimp

    Returns the item flags for the given \a index.

    The implementation returns a combination of flags that enables the item
    (\c ItemIsEnabled) and allows it to be selected (\c ItemIsSelectable). For
    models operating on a range with mutable data, it also sets the flag
    that allows the item to be editable (\c ItemIsEditable).

    \sa Qt::ItemFlags
*/
Qt::ItemFlags QRangeModel::flags(const QModelIndex &index) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::Flags>(index);
}

/*!
    \reimp

    Returns the data for the given \a role and \a section in the header with
    the specified \a orientation.

    For horizontal headers, the section number corresponds to the column
    number. Similarly, for vertical headers, the section number corresponds to
    the row number.

    For the horizontal header and the Qt::DisplayRole \a role, models that
    operate on a range that uses an array as the row type return \a section. If
    the row type is a tuple, then the implementation returns the name of the
    type at \a section. For rows that are a gadget or QObject type, this
    function returns the name of the property at the index of \a section.

    For the vertical header, this function always returns the result of the
    default implementation in QAbstractItemModel.

    \sa Qt::ItemDataRole, setHeaderData(), QHeaderView
*/
QVariant QRangeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::HeaderData>(section, orientation, role);
}

/*!
    \reimp
*/
bool QRangeModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &data,
                                int role)
{
    return QAbstractItemModel::setHeaderData(section, orientation, data, role);
}

/*!
    \reimp

    Returns the data stored under the given \a role for the value in the
    range referred to by the \a index.

    If the item type for that index is an associative container that maps from
    either \c{int}, Qt::ItemDataRole, or QString to a QVariant, then the role
    data is looked up in that container and returned.

    If the item is a gadget or QObject, then the implementation returns the
    value of the item's property matching the \a role entry in the roleNames()
    mapping.

    Otherwise, the implementation returns a QVariant constructed from the item
    via \c{QVariant::fromValue()} for \c{Qt::DisplayRole} or \c{Qt::EditRole}.
    For other roles, the implementation returns an \b invalid
    (default-constructed) QVariant.

    \sa Qt::ItemDataRole, setData(), headerData()
*/
QVariant QRangeModel::data(const QModelIndex &index, int role) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::Data>(index, role);
}

/*!
    \reimp

    Sets the \a role data for the item at \a index to \a data.

    If the item type for that \a index is an associative container that maps
    from either \c{int}, Qt::ItemDataRole, or QString to a QVariant, then
    \a data is stored in that container for the key specified by \a role.

    If the item is a gadget or QObject, then \a data is written to the item's
    property matching the \a role entry in the the roleNames() mapping. The
    function returns \c{true} if a property was found and if \a data stored a
    value that could be converted to the required type, otherwise returns
    \c{false}.

    Otherwise, this implementation assigns the value in \a data to the item at
    the \a index in the range for \c{Qt::DisplayRole} and \c{Qt::EditRole},
    and returns \c{true}. For other roles, the implementation returns
    \c{false}.

//! [read-only-setData]
    For models operating on a read-only range, or on a read-only column in
    a row type that implements \l{the C++ tuple protocol}, this implementation
    returns \c{false} immediately.
//! [read-only-setData]
*/
bool QRangeModel::setData(const QModelIndex &index, const QVariant &data, int role)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::SetData>(index, data, role);
}

/*!
    \reimp

    Returns a map with values for all predefined roles in the model for the
    item at the given \a index.

    If the item type for that \a index is an associative container that maps
    from either \c{int}, Qt::ItemDataRole, or QString to a QVariant, then the
    data from that container is returned.

    If the item type is a gadget or QObject subclass, then the values of those
    properties that match a \l{roleNames()}{role name} are returned.

    If the item is not an associative container, gadget, or QObject subclass,
    then this calls the base class implementation.

    \sa setItemData(), Qt::ItemDataRole, data()
*/
QMap<int, QVariant> QRangeModel::itemData(const QModelIndex &index) const
{
    Q_D(const QRangeModel);
    return d->impl->call<QRangeModelImplBase::ItemData>(index);
}

/*!
    \reimp

    If the item type for that \a index is an associative container that maps
    from either \c{int} or Qt::ItemDataRole to a QVariant, then the entries in
    \a data are stored in that container. If the associative container maps from
    QString to QVariant, then only those values in \a data are stored for which
    there is a mapping in the \l{roleNames()}{role names} table.

    If the item type is a gadget or QObject subclass, then those properties that
    match a \l{roleNames()}{role name} are set to the corresponding value in
    \a data.

    Roles for which there is no entry in \a data are not modified.

    For item types that can be copied, this implementation is transactional,
    and returns true if all the entries from \a data could be stored. If any
    entry could not be updated, then the original container is not modified at
    all, and the function returns false.

    If the item is not an associative container, gadget, or QObject subclass,
    then this calls the base class implementation, which calls setData() for
    each entry in \a data.

    \sa itemData(), setData(), Qt::ItemDataRole
*/
bool QRangeModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &data)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::SetItemData>(index, data);
}

/*!
    \reimp

    Replaces the value stored in the range at \a index with a default-
    constructed value.

    \include qrangemodel.cpp read-only-setData
*/
bool QRangeModel::clearItemData(const QModelIndex &index)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::ClearItemData>(index);
}

/*
//! [column-change-requirement]
    \note A dynamically sized row type needs to provide a \c{\1} member function.

    For models operating on a read-only range, or on a range with a
    statically sized row type (such as a tuple, array, or struct), this
    implementation does nothing and returns \c{false} immediately. This is
    always the case for tree models.
//! [column-change-requirement]
*/

/*!
    \reimp

    Inserts \a count empty columns before the item at \a column in all rows
    of the range at \a parent. Returns \c{true} if successful; otherwise
    returns \c{false}.

    \include qrangemodel.cpp {column-change-requirement} {insert(const_iterator, size_t, value_type)}
*/
bool QRangeModel::insertColumns(int column, int count, const QModelIndex &parent)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::InsertColumns>(column, count, parent);
}

/*!
    \reimp

    Removes \a count columns from the item at \a column on in all rows of the
    range at \a parent. Returns \c{true} if successful, otherwise returns
    \c{false}.

    \include qrangemodel.cpp {column-change-requirement} {erase(const_iterator, size_t)}
*/
bool QRangeModel::removeColumns(int column, int count, const QModelIndex &parent)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::RemoveColumns>(column, count, parent);
}

/*!
    \reimp

    Moves \a count columns starting with the given \a sourceColumn under parent
    \a sourceParent to column \a destinationColumn under parent \a destinationParent.

    Returns \c{true} if the columns were successfully moved; otherwise returns
    \c{false}.
*/
bool QRangeModel::moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count,
                                    const QModelIndex &destinationParent, int destinationColumn)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::MoveColumns>(
                         sourceParent, sourceColumn, count,
                         destinationParent, destinationColumn);
}

/*
//! [row-change-requirement]
    \note The range needs to be dynamically sized and provide a \c{\1}
    member function.

    For models operating on a read-only or statically-sized range (such as
    an array), this implementation does nothing and returns \c{false}
    immediately.
//! [row-change-requirement]
*/

/*!
    \reimp

    Inserts \a count empty rows before the given \a row into the range at
    \a parent. Returns \c{true} if successful; otherwise returns \c{false}.

    \include qrangemodel.cpp {row-change-requirement} {insert(const_iterator, size_t, value_type)}

    \note For ranges with a dynamically sized column type, the column needs
    to provide a \c{resize(size_t)} member function.
*/
bool QRangeModel::insertRows(int row, int count, const QModelIndex &parent)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::InsertRows>(row, count, parent);
}

/*!
    \reimp

    Removes \a count rows from the range at \a parent, starting with the
    given \a row. Returns \c{true} if successful, otherwise returns \c{false}.

    \include qrangemodel.cpp {row-change-requirement} {erase(const_iterator, size_t)}
*/
bool QRangeModel::removeRows(int row, int count, const QModelIndex &parent)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::RemoveRows>(row, count, parent);
}

/*!
    \reimp

    Moves \a count rows starting with the given \a sourceRow under parent
    \a sourceParent to row \a destinationRow under parent \a destinationParent.

    Returns \c{true} if the rows were successfully moved; otherwise returns
    \c{false}.
*/
bool QRangeModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count,
                                 const QModelIndex &destinationParent, int destinationRow)
{
    Q_D(QRangeModel);
    return d->impl->call<QRangeModelImplBase::MoveRows>(
                         sourceParent, sourceRow, count,
                         destinationParent, destinationRow);
}

/*!
    \reimp
*/
bool QRangeModel::canFetchMore(const QModelIndex &parent) const
{
    return QAbstractItemModel::canFetchMore(parent);
}

/*!
    \reimp
*/
void QRangeModel::fetchMore(const QModelIndex &parent)
{
    QAbstractItemModel::fetchMore(parent);
}

/*!
    \reimp
*/
bool QRangeModel::hasChildren(const QModelIndex &parent) const
{
    return QAbstractItemModel::hasChildren(parent);
}

/*!
    \reimp
*/
QModelIndex QRangeModel::buddy(const QModelIndex &index) const
{
    return QAbstractItemModel::buddy(index);
}

/*!
    \reimp
*/
bool QRangeModel::canDropMimeData(const QMimeData *data, Qt::DropAction action,
                                        int row, int column, const QModelIndex &parent) const
{
    return QAbstractItemModel::canDropMimeData(data, action, row, column, parent);
}

/*!
    \reimp
*/
bool QRangeModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
                                     int row, int column, const QModelIndex &parent)
{
    return QAbstractItemModel::dropMimeData(data, action, row, column, parent);
}

/*!
    \reimp
*/
QMimeData *QRangeModel::mimeData(const QModelIndexList &indexes) const
{
    return QAbstractItemModel::mimeData(indexes);
}

/*!
    \reimp
*/
QStringList QRangeModel::mimeTypes() const
{
    return QAbstractItemModel::mimeTypes();
}

/*!
    \reimp
*/
QModelIndexList QRangeModel::match(const QModelIndex &start, int role, const QVariant &value,
                                         int hits, Qt::MatchFlags flags) const
{
    return QAbstractItemModel::match(start, role, value, hits, flags);
}

/*!
    \reimp
*/
void QRangeModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
{
    Q_D(const QRangeModel);
    d->impl->call<QRangeModelImplBase::MultiData>(index, roleDataSpan);
}


/*!
    \property QRangeModel::roleNames
    \brief the role names for the model.

    If all columns in the range are of the same type, and if that type provides
    a meta object (i.e., it is a gadget, or a QObject subclass), then this
    property holds the names of the properties of that type, mapped to values of
    Qt::ItemDataRole values from Qt::UserRole and up. In addition, a role
    "modelData" provides access to the gadget or QObject instance.

    Override this default behavior by setting this property explicitly to a non-
    empty mapping. Setting this property to an empty mapping, or using
    resetRoleNames(), restores the default behavior.

    \sa QAbstractItemModel::roleNames()
*/

QHash<int, QByteArray> QRangeModelImplBase::roleNamesForMetaObject(const QAbstractItemModel &model,
                                                                   const QMetaObject &metaObject)
{
    const auto defaults = model.QAbstractItemModel::roleNames();
    QHash<int, QByteArray> result = {{Qt::RangeModelDataRole, "modelData"}};
    int offset = metaObject.propertyOffset();
    for (int i = offset; i < metaObject.propertyCount(); ++i) {
        const auto name = metaObject.property(i).name();
        const int defaultRole = defaults.key(name, -1);
        if (defaultRole != -1) {
            ++offset;
            result[defaultRole] = name;
        } else {
            result[Qt::UserRole + i - offset] = name;
        }
    }
    return result;
}

QHash<int, QByteArray> QRangeModelImplBase::roleNamesForSimpleType()
{
    // just a plain value
    return QHash<int, QByteArray>{
        {Qt::DisplayRole, "display"},
        {Qt::EditRole, "edit"},
        {Qt::RangeModelDataRole, "modelData"},
    };
}

/*!
    \reimp

    \note Overriding this function in a QRangeModel subclass is possible,
    but might break the behavior of the property.
*/
QHash<int, QByteArray> QRangeModel::roleNames() const
{
    Q_D(const QRangeModel);
    if (d->m_roleNames.isEmpty())
        d->m_roleNames = d->impl->call<QRangeModelImplBase::RoleNames>();

    return d->m_roleNames;
}

void QRangeModel::setRoleNames(const QHash<int, QByteArray> &names)
{
    Q_D(QRangeModel);
    if (d->m_roleNames == names)
        return;
    beginResetModel();
    d->impl->call<QRangeModelImplBase::InvalidateCaches>();
    if (d->m_autoConnectPolicy != AutoConnectPolicy::None)
        d->impl->call<QRangeModelImplBase::SetAutoConnectPolicy>();

    d->m_roleNames = names;
    endResetModel();
    Q_EMIT roleNamesChanged();
}

void QRangeModel::resetRoleNames()
{
    setRoleNames({});
}

/*!
    \enum QRangeModel::AutoConnectPolicy
    \since 6.11

    This enum defines if and when QRangeModel auto-connects changed-signals for
    properties to the \l{QAbstractItemModel::}{dataChanged()} signal of the
    model. Only properties that match one of the \l{roleNames()}{role names}
    are connected.

    \value None     No connections are made automatically.
    \value Full     The signals for all relevant properties are connected
                    automatically, for all QObject items. This includes QObject
                    items that are added to newly inserted rows and columns.
    \value OnRead   Signals for relevant properties are connected the first time
                    the model reads the property.

    The memory overhead of making automatic connections can be substantial. A
    Full auto-connection does not require any book-keeping in addition to the
    connection itself, but each connection takes memory, and connecting all
    properties of all objects can be very costly, especially if only a few
    properties of a subset of objects will ever change.

    The OnRead connection policy will not connect to objects or properties that
    are never read from (for instance, never rendered in a view), but remembering
    which connections have been made requires some book-keeping overhead, and
    unpredictable memory growth over time. For instance, scrolling down a long
    list of items can easily result in thousands of new connections being made.

    \sa autoConnectPolicy, roleNames()
*/

/*!
    \property QRangeModel::autoConnectPolicy
    \brief if and when the model auto-connects to property changed notifications.

    If QRangeModel operates on a data structure that holds the same type of
    QObject subclass as its item type, then it can automatically connect the
    properties of the QObjects to the dataChanged() signal. This is done for
    those properties that match one of the \l{roleNames()}{role names}.

    By default, the value of this property is \l{QRangeModel::AutoConnectPolicy::}
    {None}, so no such connections are made. Changing the value of this property
    always breaks all existing connections.

    \note Connections are not broken or created if QObjects in the data
    structure that QRangeModel operates on are swapped out.

    \sa roleNames()
*/

QRangeModel::AutoConnectPolicy QRangeModel::autoConnectPolicy() const
{
    Q_D(const QRangeModel);
    return d->m_autoConnectPolicy;
}

void QRangeModel::setAutoConnectPolicy(QRangeModel::AutoConnectPolicy policy)
{
    Q_D(QRangeModel);
    if (d->m_autoConnectPolicy == policy)
        return;

    d->m_autoConnectPolicy = policy;
    d->impl->call<QRangeModelImplBase::SetAutoConnectPolicy>();
    Q_EMIT autoConnectPolicyChanged();
}

/*!
    \reimp
*/
void QRangeModel::sort(int column, Qt::SortOrder order)
{
    return QAbstractItemModel::sort(column, order);
}

/*!
    \reimp
*/
QSize QRangeModel::span(const QModelIndex &index) const
{
    return QAbstractItemModel::span(index);
}

/*!
    \reimp
*/
Qt::DropActions QRangeModel::supportedDragActions() const
{
    return QAbstractItemModel::supportedDragActions();
}

/*!
    \reimp
*/
Qt::DropActions QRangeModel::supportedDropActions() const
{
    return QAbstractItemModel::supportedDropActions();
}

/*!
    \reimp
*/
void QRangeModel::resetInternalData()
{
    QAbstractItemModel::resetInternalData();
}

/*!
    \reimp
*/
bool QRangeModel::event(QEvent *event)
{
    return QAbstractItemModel::event(event);
}

/*!
    \reimp
*/
bool QRangeModel::eventFilter(QObject *object, QEvent *event)
{
    return QAbstractItemModel::eventFilter(object, event);
}

QT_END_NAMESPACE

#include "moc_qrangemodel.cpp"