1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Copyright (C) 2020 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include "qabstractitemmodel.h"
42#include <private/qabstractitemmodel_p.h>
43#include <qdatastream.h>
44#include <qstringlist.h>
45#include <qsize.h>
46#include <qmimedata.h>
47#include <qdebug.h>
48#include <qlist.h>
49#if QT_CONFIG(regularexpression)
50# include <qregularexpression.h>
51#endif
52#include <qstack.h>
53#include <qbitarray.h>
54#include <qdatetime.h>
55#include <qloggingcategory.h>
56
57#include <limits.h>
58
59QT_BEGIN_NAMESPACE
60
61Q_LOGGING_CATEGORY(lcCheckIndex, "qt.core.qabstractitemmodel.checkindex")
62
63QPersistentModelIndexData *QPersistentModelIndexData::create(const QModelIndex &index)
64{
65 Q_ASSERT(index.isValid()); // we will _never_ insert an invalid index in the list
66 QPersistentModelIndexData *d = nullptr;
67 QAbstractItemModel *model = const_cast<QAbstractItemModel *>(index.model());
68 QMultiHash<QModelIndex, QPersistentModelIndexData *> &indexes = model->d_func()->persistent.indexes;
69 const auto it = indexes.constFind(index);
70 if (it != indexes.cend()) {
71 d = (*it);
72 } else {
73 d = new QPersistentModelIndexData(index);
74 indexes.insert(index, d);
75 }
76 Q_ASSERT(d);
77 return d;
78}
79
80void QPersistentModelIndexData::destroy(QPersistentModelIndexData *data)
81{
82 Q_ASSERT(data);
83 Q_ASSERT(data->ref.loadRelaxed() == 0);
84 QAbstractItemModel *model = const_cast<QAbstractItemModel *>(data->index.model());
85 // a valid persistent model index with a null model pointer can only happen if the model was destroyed
86 if (model) {
87 QAbstractItemModelPrivate *p = model->d_func();
88 Q_ASSERT(p);
89 p->removePersistentIndexData(data);
90 }
91 delete data;
92}
93
94/*!
95 \class QModelRoleData
96 \inmodule QtCore
97 \since 6.0
98 \ingroup model-view
99 \brief The QModelRoleData class holds a role and the data associated to that role.
100
101 QModelRoleData objects store an item role (which is a value from the
102 Qt::ItemDataRole enumeration, or an arbitrary integer for a custom role)
103 as well as the data associated with that role.
104
105 A QModelRoleData object is typically created by views or delegates,
106 setting which role they want to fetch the data for. The object
107 is then passed to models (see QAbstractItemModel::multiData()),
108 which populate the data corresponding to the role stored. Finally,
109 the view visualizes the data retrieved from the model.
110
111 \sa {Model/View Programming}, QModelRoleDataSpan
112*/
113
114/*!
115 \fn QModelRoleData::QModelRoleData(int role) noexcept
116
117 Constructs a QModelRoleData object for the given \a role.
118
119 \sa Qt::ItemDataRole
120*/
121
122/*!
123 \fn int QModelRoleData::role() const noexcept
124
125 Returns the role held by this object.
126
127 \sa Qt::ItemDataRole
128*/
129
130/*!
131 \fn const QVariant &QModelRoleData::data() const noexcept
132
133 Returns the data held by this object.
134
135 \sa setData()
136*/
137
138/*!
139 \fn QVariant &QModelRoleData::data() noexcept
140
141 Returns the data held by this object as a modifiable reference.
142
143 \sa setData()
144*/
145
146/*!
147 \fn template <typename T> void QModelRoleData::setData(T &&value)
148
149 Sets the data held by this object to \a value.
150 \a value must be of a datatype which can be stored in a QVariant.
151
152 \sa data(), clearData(), Q_DECLARE_METATYPE
153*/
154
155/*!
156 \fn void QModelRoleData::clearData() noexcept
157
158 Clears the data held by this object. Note that the role is
159 unchanged; only the data is cleared.
160
161 \sa data()
162*/
163
164/*!
165 \class QModelRoleDataSpan
166 \inmodule QtCore
167 \since 6.0
168 \ingroup model-view
169 \brief The QModelRoleDataSpan class provides a span over QModelRoleData objects.
170
171 A QModelRoleDataSpan is used as an abstraction over an array of
172 QModelRoleData objects.
173
174 Like a view, QModelRoleDataSpan provides a small object (pointer
175 and size) that can be passed to functions that need to examine the
176 contents of the array. A QModelRoleDataSpan can be constructed from
177 any array-like sequence (plain arrays, QVector, std::vector,
178 QVarLengthArray, and so on). Moreover, it does not own the
179 sequence, which must therefore be kept alive longer than any
180 QModelRoleDataSpan objects referencing it.
181
182 Unlike a view, QModelRoleDataSpan is a span, so it allows for
183 modifications to the underlying elements.
184
185 QModelRoleDataSpan's main use case is making it possible
186 for a model to return the data corresponding to different roles
187 in one call.
188
189 In order to draw one element from a model, a view (through its
190 delegates) will generally request multiple roles for the same index
191 by calling \c{data()} as many times as needed:
192
193 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 13
194
195 QModelRoleDataSpan allows a view to request the same data
196 using just one function call.
197
198 This is achieved by having the view prepare a suitable array of
199 QModelRoleData objects, each initialized with the role that should
200 be fetched. The array is then wrapped in a QModelRoleDataSpan
201 object, which is then passed to a model's \c{multiData()} function.
202
203 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 14
204
205 Views are encouraged to store the array of QModelRoleData objects
206 (and, possibly, the corresponding span) and re-use it in subsequent
207 calls to the model. This allows to reduce the memory allocations
208 related with creating and returning QVariant objects.
209
210 Finally, given a QModelRoleDataSpan object, the model's
211 responsibility is to fill in the data corresponding to each role in
212 the span. How this is done depends on the concrete model class.
213 Here's a sketch of a possible implementation that iterates over the
214 span and uses \c{setData()} on each element:
215
216 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 15
217
218 \sa {Model/View Programming}, QAbstractItemModel::multiData()
219*/
220
221/*!
222 \fn QModelRoleDataSpan::QModelRoleDataSpan() noexcept
223
224 Constructs an empty QModelRoleDataSpan. Its data() will be set to
225 \nullptr, and its length to zero.
226*/
227
228/*!
229 \fn QModelRoleDataSpan::QModelRoleDataSpan(QModelRoleData &modelRoleData) noexcept
230
231 Constructs an QModelRoleDataSpan spanning over \a modelRoleData,
232 seen as a 1-element array.
233*/
234
235/*!
236 \fn QModelRoleDataSpan::QModelRoleDataSpan(QModelRoleData *modelRoleData, qsizetype len)
237
238 Constructs an QModelRoleDataSpan spanning over the array beginning
239 at \a modelRoleData and with length \a len.
240
241 \note The array must be kept alive as long as this object has not
242 been destructed.
243*/
244
245/*!
246 \fn template <typename Container> QModelRoleDataSpan::QModelRoleDataSpan(Container &c) noexcept
247
248 Constructs an QModelRoleDataSpan spanning over the container \a c,
249 which can be any contiguous container of QModelRoleData objects.
250 For instance, it can be a \c{QVector<QModelRoleData>},
251 a \c{std::array<QModelRoleData, 10>} and so on.
252
253 \note The container must be kept alive as long as this object has not
254 been destructed.
255*/
256
257/*!
258 \fn qsizetype QModelRoleDataSpan::size() const noexcept
259
260 Returns the length of the span represented by this object.
261*/
262
263/*!
264 \fn qsizetype QModelRoleDataSpan::length() const noexcept
265
266 Returns the length of the span represented by this object.
267*/
268
269/*!
270 \fn QModelRoleData *QModelRoleDataSpan::data() const noexcept
271
272 Returns a pointer to the beginning of the span represented by this
273 object.
274*/
275
276/*!
277 \fn QModelRoleData *QModelRoleDataSpan::begin() const noexcept
278
279 Returns a pointer to the beginning of the span represented by this
280 object.
281*/
282
283/*!
284 \fn QModelRoleData *QModelRoleDataSpan::end() const noexcept
285
286 Returns a pointer to the imaginary element one past the end of the
287 span represented by this object.
288*/
289
290/*!
291 \fn QModelRoleData &QModelRoleDataSpan::operator[](qsizetype index) const
292
293 Returns a modifiable reference to the QModelRoleData at position
294 \a index in the span.
295
296 \note \a index must be a valid index for this span (0 <= \a index < size()).
297*/
298
299/*!
300 \fn const QVariant *QModelRoleDataSpan::dataForRole(int role) const
301
302 Returns the data associated with the first QModelRoleData in the
303 span that has its role equal to \a role. If such a QModelRoleData
304 object does not exist, the behavior is undefined.
305
306 \note Avoid calling this function from the model's side, as a
307 model cannot possibly know in advance which roles are in a given
308 QModelRoleDataSpan. This function is instead suitable for views and
309 delegates, which have control over the roles in the span.
310
311 \sa QModelRoleData::data()
312*/
313
314/*!
315 \class QPersistentModelIndex
316 \inmodule QtCore
317 \ingroup shared
318
319 \brief The QPersistentModelIndex class is used to locate data in a data model.
320
321 \ingroup model-view
322
323 A QPersistentModelIndex is a model index that can be stored by an
324 application, and later used to access information in a model.
325 Unlike the QModelIndex class, it is safe to store a
326 QPersistentModelIndex since the model will ensure that references
327 to items will continue to be valid as long as they can be accessed
328 by the model.
329
330 It is good practice to check that persistent model indexes are valid
331 before using them.
332
333 \note You cannot store a QStandardItemModel's QPersistentModelIndex
334 in one of the model's items.
335
336 \sa {Model/View Programming}, QModelIndex, QAbstractItemModel
337*/
338
339/*!
340 \fn QPersistentModelIndex::QPersistentModelIndex(QPersistentModelIndex &&other)
341
342 Move-constructs a QPersistentModelIndex instance, making it point at the same
343 object that \a other was pointing to.
344
345 \since 5.2
346*/
347
348/*!
349 \fn QPersistentModelIndex &QPersistentModelIndex::operator=(QPersistentModelIndex &&other)
350
351 Move-assigns \a other to this QPersistentModelIndex instance.
352
353 \since 5.2
354*/
355
356
357/*!
358 \fn QPersistentModelIndex::QPersistentModelIndex()
359
360 \internal
361*/
362
363QPersistentModelIndex::QPersistentModelIndex()
364 : d(nullptr)
365{
366}
367
368/*!
369 \fn QPersistentModelIndex::QPersistentModelIndex(const QPersistentModelIndex &other)
370
371 Creates a new QPersistentModelIndex that is a copy of the \a other persistent
372 model index.
373*/
374
375QPersistentModelIndex::QPersistentModelIndex(const QPersistentModelIndex &other)
376 : d(other.d)
377{
378 if (d) d->ref.ref();
379}
380
381/*!
382 Creates a new QPersistentModelIndex that is a copy of the model \a index.
383*/
384
385QPersistentModelIndex::QPersistentModelIndex(const QModelIndex &index)
386 : d(nullptr)
387{
388 if (index.isValid()) {
389 d = QPersistentModelIndexData::create(index);
390 d->ref.ref();
391 }
392}
393
394/*!
395 \fn QPersistentModelIndex::~QPersistentModelIndex()
396
397 \internal
398*/
399
400QPersistentModelIndex::~QPersistentModelIndex()
401{
402 if (d && !d->ref.deref()) {
403 QPersistentModelIndexData::destroy(d);
404 d = nullptr;
405 }
406}
407
408/*!
409 Returns \c{true} if this persistent model index is equal to the \a other
410 persistent model index; otherwise returns \c{false}.
411
412 The internal data pointer, row, column, and model values in the persistent
413 model index are used when comparing with another persistent model index.
414*/
415
416bool QPersistentModelIndex::operator==(const QPersistentModelIndex &other) const
417{
418 if (d && other.d)
419 return d->index == other.d->index;
420 return d == other.d;
421}
422
423/*!
424 \since 4.1
425
426 Returns \c{true} if this persistent model index is smaller than the \a other
427 persistent model index; otherwise returns \c{false}.
428
429 The internal data pointer, row, column, and model values in the persistent
430 model index are used when comparing with another persistent model index.
431*/
432
433bool QPersistentModelIndex::operator<(const QPersistentModelIndex &other) const
434{
435 if (d && other.d)
436 return d->index < other.d->index;
437
438 return d < other.d;
439}
440
441/*!
442 \fn bool QPersistentModelIndex::operator!=(const QPersistentModelIndex &other) const
443 \since 4.2
444
445 Returns \c{true} if this persistent model index is not equal to the \a
446 other persistent model index; otherwise returns \c{false}.
447*/
448
449/*!
450 Sets the persistent model index to refer to the same item in a model
451 as the \a other persistent model index.
452*/
453
454QPersistentModelIndex &QPersistentModelIndex::operator=(const QPersistentModelIndex &other)
455{
456 if (d == other.d)
457 return *this;
458 if (d && !d->ref.deref())
459 QPersistentModelIndexData::destroy(d);
460 d = other.d;
461 if (d) d->ref.ref();
462 return *this;
463}
464/*!
465 \fn void QPersistentModelIndex::swap(QPersistentModelIndex &other)
466 \since 5.0
467
468 Swaps this persistent modelindex with \a other. This function is
469 very fast and never fails.
470*/
471
472/*!
473 Sets the persistent model index to refer to the same item in a model
474 as the \a other model index.
475*/
476
477QPersistentModelIndex &QPersistentModelIndex::operator=(const QModelIndex &other)
478{
479 if (d && !d->ref.deref())
480 QPersistentModelIndexData::destroy(d);
481 if (other.isValid()) {
482 d = QPersistentModelIndexData::create(other);
483 if (d) d->ref.ref();
484 } else {
485 d = nullptr;
486 }
487 return *this;
488}
489
490/*!
491 \fn QPersistentModelIndex::operator const QModelIndex&() const
492
493 Cast operator that returns a const QModelIndex&.
494*/
495
496QPersistentModelIndex::operator const QModelIndex&() const
497{
498 static const QModelIndex invalid;
499 if (d)
500 return d->index;
501 return invalid;
502}
503
504/*!
505 Returns \c{true} if this persistent model index refers to the same location as
506 the \a other model index; otherwise returns \c{false}.
507
508 The internal data pointer, row, column, and model values in the persistent
509 model index are used when comparing with another model index.
510*/
511
512bool QPersistentModelIndex::operator==(const QModelIndex &other) const
513{
514 if (d)
515 return d->index == other;
516 return !other.isValid();
517}
518
519/*!
520 \fn bool QPersistentModelIndex::operator!=(const QModelIndex &other) const
521
522 Returns \c{true} if this persistent model index does not refer to the same
523 location as the \a other model index; otherwise returns \c{false}.
524*/
525
526bool QPersistentModelIndex::operator!=(const QModelIndex &other) const
527{
528 if (d)
529 return d->index != other;
530 return other.isValid();
531}
532
533/*!
534 \fn int QPersistentModelIndex::row() const
535
536 Returns the row this persistent model index refers to.
537*/
538
539int QPersistentModelIndex::row() const
540{
541 if (d)
542 return d->index.row();
543 return -1;
544}
545
546/*!
547 \fn int QPersistentModelIndex::column() const
548
549 Returns the column this persistent model index refers to.
550*/
551
552int QPersistentModelIndex::column() const
553{
554 if (d)
555 return d->index.column();
556 return -1;
557}
558
559/*!
560 \fn void *QPersistentModelIndex::internalPointer() const
561
562 \internal
563
564 Returns a \c{void} \c{*} pointer used by the model to associate the index with
565 the internal data structure.
566*/
567
568void *QPersistentModelIndex::internalPointer() const
569{
570 if (d)
571 return d->index.internalPointer();
572 return nullptr;
573}
574
575/*!
576 \fn const void *QPersistentModelIndex::constInternalPointer() const
577 \since 6.0
578 \internal
579
580 Returns a \c{const void} \c{*} pointer used by the model to
581 associate the index with the internal data structure.
582*/
583
584const void *QPersistentModelIndex::constInternalPointer() const
585{
586 if (d)
587 return d->index.constInternalPointer();
588 return nullptr;
589}
590
591/*!
592 \fn quintptr QPersistentModelIndex::internalId() const
593
594 \internal
595
596 Returns a \c{quintptr} used by the model to associate the index with
597 the internal data structure.
598*/
599
600quintptr QPersistentModelIndex::internalId() const
601{
602 if (d)
603 return d->index.internalId();
604 return 0;
605}
606
607/*!
608 Returns the parent QModelIndex for this persistent index, or an invalid
609 QModelIndex if it has no parent.
610
611 \sa sibling(), model()
612*/
613QModelIndex QPersistentModelIndex::parent() const
614{
615 if (d)
616 return d->index.parent();
617 return QModelIndex();
618}
619
620/*!
621 Returns the sibling at \a row and \a column or an invalid QModelIndex if
622 there is no sibling at this position.
623
624 \sa parent()
625*/
626
627QModelIndex QPersistentModelIndex::sibling(int row, int column) const
628{
629 if (d)
630 return d->index.sibling(row, column);
631 return QModelIndex();
632}
633
634/*!
635 Returns the data for the given \a role for the item referred to by the
636 index.
637
638 \sa Qt::ItemDataRole, QAbstractItemModel::setData()
639*/
640QVariant QPersistentModelIndex::data(int role) const
641{
642 if (d)
643 return d->index.data(role);
644 return QVariant();
645}
646
647
648/*!
649 Populates the given \a roleDataSpan for the item referred to by the
650 index.
651
652 \since 6.0
653 \sa Qt::ItemDataRole, QAbstractItemModel::setData()
654*/
655void QPersistentModelIndex::multiData(QModelRoleDataSpan roleDataSpan) const
656{
657 if (d)
658 d->index.multiData(roleDataSpan);
659}
660
661/*!
662 \since 4.2
663
664 Returns the flags for the item referred to by the index.
665*/
666Qt::ItemFlags QPersistentModelIndex::flags() const
667{
668 if (d)
669 return d->index.flags();
670 return { };
671}
672
673/*!
674 Returns the model that the index belongs to.
675*/
676const QAbstractItemModel *QPersistentModelIndex::model() const
677{
678 if (d)
679 return d->index.model();
680 return nullptr;
681}
682
683/*!
684 \fn bool QPersistentModelIndex::isValid() const
685
686 Returns \c{true} if this persistent model index is valid; otherwise returns
687 \c{false}.
688
689 A valid index belongs to a model, and has non-negative row and column
690 numbers.
691
692 \sa model(), row(), column()
693*/
694
695bool QPersistentModelIndex::isValid() const
696{
697 return d && d->index.isValid();
698}
699
700#ifndef QT_NO_DEBUG_STREAM
701QDebug operator<<(QDebug dbg, const QModelIndex &idx)
702{
703 QDebugStateSaver saver(dbg);
704 dbg.nospace() << "QModelIndex(" << idx.row() << ',' << idx.column()
705 << ',' << idx.internalPointer() << ',' << idx.model() << ')';
706 return dbg;
707}
708
709QDebug operator<<(QDebug dbg, const QPersistentModelIndex &idx)
710{
711 if (idx.d)
712 dbg << idx.d->index;
713 else
714 dbg << QModelIndex();
715 return dbg;
716}
717#endif
718
719class QEmptyItemModel : public QAbstractItemModel
720{
721public:
722 explicit QEmptyItemModel(QObject *parent = nullptr) : QAbstractItemModel(parent) {}
723 QModelIndex index(int, int, const QModelIndex &) const override { return QModelIndex(); }
724 QModelIndex parent(const QModelIndex &) const override { return QModelIndex(); }
725 int rowCount(const QModelIndex &) const override { return 0; }
726 int columnCount(const QModelIndex &) const override { return 0; }
727 bool hasChildren(const QModelIndex &) const override { return false; }
728 QVariant data(const QModelIndex &, int) const override { return QVariant(); }
729};
730
731Q_GLOBAL_STATIC(QEmptyItemModel, qEmptyModel)
732
733
734QAbstractItemModelPrivate::QAbstractItemModelPrivate()
735 : QObjectPrivate()
736{
737}
738
739QAbstractItemModelPrivate::~QAbstractItemModelPrivate()
740{
741}
742
743QAbstractItemModel *QAbstractItemModelPrivate::staticEmptyModel()
744{
745 return qEmptyModel();
746}
747
748void QAbstractItemModelPrivate::invalidatePersistentIndexes()
749{
750 for (QPersistentModelIndexData *data : qAsConst(persistent.indexes))
751 data->index = QModelIndex();
752 persistent.indexes.clear();
753}
754
755/*!
756 \internal
757 Clean the QPersistentModelIndex relative to the index if there is one.
758 To be used before an index is invalided
759*/
760void QAbstractItemModelPrivate::invalidatePersistentIndex(const QModelIndex &index) {
761 const auto it = persistent.indexes.constFind(index);
762 if (it != persistent.indexes.cend()) {
763 QPersistentModelIndexData *data = *it;
764 persistent.indexes.erase(it);
765 data->index = QModelIndex();
766 }
767}
768
769using DefaultRoleNames = QHash<int, QByteArray>;
770Q_GLOBAL_STATIC_WITH_ARGS(DefaultRoleNames, qDefaultRoleNames, (
771 {
772 { Qt::DisplayRole, "display" },
773 { Qt::DecorationRole, "decoration" },
774 { Qt::EditRole, "edit" },
775 { Qt::ToolTipRole, "toolTip" },
776 { Qt::StatusTipRole, "statusTip" },
777 { Qt::WhatsThisRole, "whatsThis" },
778 }))
779
780const QHash<int,QByteArray> &QAbstractItemModelPrivate::defaultRoleNames()
781{
782 return *qDefaultRoleNames();
783}
784
785bool QAbstractItemModelPrivate::isVariantLessThan(const QVariant &left, const QVariant &right,
786 Qt::CaseSensitivity cs, bool isLocaleAware)
787{
788 if (left.userType() == QMetaType::UnknownType)
789 return false;
790 if (right.userType() == QMetaType::UnknownType)
791 return true;
792 switch (left.userType()) {
793 case QMetaType::Int:
794 return left.toInt() < right.toInt();
795 case QMetaType::UInt:
796 return left.toUInt() < right.toUInt();
797 case QMetaType::LongLong:
798 return left.toLongLong() < right.toLongLong();
799 case QMetaType::ULongLong:
800 return left.toULongLong() < right.toULongLong();
801 case QMetaType::Float:
802 return left.toFloat() < right.toFloat();
803 case QMetaType::Double:
804 return left.toDouble() < right.toDouble();
805 case QMetaType::QChar:
806 return left.toChar() < right.toChar();
807 case QMetaType::QDate:
808 return left.toDate() < right.toDate();
809 case QMetaType::QTime:
810 return left.toTime() < right.toTime();
811 case QMetaType::QDateTime:
812 return left.toDateTime() < right.toDateTime();
813 case QMetaType::QString:
814 default:
815 if (isLocaleAware)
816 return left.toString().localeAwareCompare(right.toString()) < 0;
817 else
818 return left.toString().compare(right.toString(), cs) < 0;
819 }
820}
821
822
823static uint typeOfVariant(const QVariant &value)
824{
825 //return 0 for integer, 1 for floating point and 2 for other
826 switch (value.userType()) {
827 case QMetaType::Bool:
828 case QMetaType::Int:
829 case QMetaType::UInt:
830 case QMetaType::LongLong:
831 case QMetaType::ULongLong:
832 case QMetaType::QChar:
833 case QMetaType::Short:
834 case QMetaType::UShort:
835 case QMetaType::UChar:
836 case QMetaType::ULong:
837 case QMetaType::Long:
838 return 0;
839 case QMetaType::Double:
840 case QMetaType::Float:
841 return 1;
842 default:
843 return 2;
844 }
845}
846
847/*!
848 \internal
849 Return \c{true} if \a value contains a numerical type.
850
851 This function is used by our Q{Tree,Widget,Table}WidgetModel classes to sort.
852*/
853bool QAbstractItemModelPrivate::variantLessThan(const QVariant &v1, const QVariant &v2)
854{
855 switch(qMax(typeOfVariant(v1), typeOfVariant(v2)))
856 {
857 case 0: //integer type
858 return v1.toLongLong() < v2.toLongLong();
859 case 1: //floating point
860 return v1.toReal() < v2.toReal();
861 default:
862 return v1.toString().localeAwareCompare(v2.toString()) < 0;
863 }
864}
865
866void QAbstractItemModelPrivate::removePersistentIndexData(QPersistentModelIndexData *data)
867{
868 if (data->index.isValid()) {
869 int removed = persistent.indexes.remove(data->index);
870 Q_ASSERT_X(removed == 1, "QPersistentModelIndex::~QPersistentModelIndex",
871 "persistent model indexes corrupted"); //maybe the index was somewhat invalid?
872 // This assert may happen if the model use changePersistentIndex in a way that could result on two
873 // QPersistentModelIndex pointing to the same index.
874 Q_UNUSED(removed);
875 }
876 // make sure our optimization still works
877 for (int i = persistent.moved.count() - 1; i >= 0; --i) {
878 int idx = persistent.moved.at(i).indexOf(data);
879 if (idx >= 0)
880 persistent.moved[i].remove(idx);
881 }
882 // update the references to invalidated persistent indexes
883 for (int i = persistent.invalidated.count() - 1; i >= 0; --i) {
884 int idx = persistent.invalidated.at(i).indexOf(data);
885 if (idx >= 0)
886 persistent.invalidated[i].remove(idx);
887 }
888
889}
890
891void QAbstractItemModelPrivate::rowsAboutToBeInserted(const QModelIndex &parent,
892 int first, int last)
893{
894 Q_Q(QAbstractItemModel);
895 Q_UNUSED(last);
896 QList<QPersistentModelIndexData *> persistent_moved;
897 if (first < q->rowCount(parent)) {
898 for (auto *data : qAsConst(persistent.indexes)) {
899 const QModelIndex &index = data->index;
900 if (index.row() >= first && index.isValid() && index.parent() == parent) {
901 persistent_moved.append(data);
902 }
903 }
904 }
905 persistent.moved.push(persistent_moved);
906}
907
908void QAbstractItemModelPrivate::rowsInserted(const QModelIndex &parent,
909 int first, int last)
910{
911 const QList<QPersistentModelIndexData *> persistent_moved = persistent.moved.pop();
912 const int count = (last - first) + 1; // it is important to only use the delta, because the change could be nested
913 for (auto *data : persistent_moved) {
914 QModelIndex old = data->index;
915 persistent.indexes.erase(persistent.indexes.constFind(old));
916 data->index = q_func()->index(old.row() + count, old.column(), parent);
917 if (data->index.isValid()) {
918 persistent.insertMultiAtEnd(data->index, data);
919 } else {
920 qWarning() << "QAbstractItemModel::endInsertRows: Invalid index (" << old.row() + count << ',' << old.column() << ") in model" << q_func();
921 }
922 }
923}
924
925void QAbstractItemModelPrivate::itemsAboutToBeMoved(const QModelIndex &srcParent, int srcFirst, int srcLast, const QModelIndex &destinationParent, int destinationChild, Qt::Orientation orientation)
926{
927 QList<QPersistentModelIndexData *> persistent_moved_explicitly;
928 QList<QPersistentModelIndexData *> persistent_moved_in_source;
929 QList<QPersistentModelIndexData *> persistent_moved_in_destination;
930
931 const bool sameParent = (srcParent == destinationParent);
932 const bool movingUp = (srcFirst > destinationChild);
933
934 for (auto *data : qAsConst(persistent.indexes)) {
935 const QModelIndex &index = data->index;
936 const QModelIndex &parent = index.parent();
937 const bool isSourceIndex = (parent == srcParent);
938 const bool isDestinationIndex = (parent == destinationParent);
939
940 int childPosition;
941 if (orientation == Qt::Vertical)
942 childPosition = index.row();
943 else
944 childPosition = index.column();
945
946 if (!index.isValid() || !(isSourceIndex || isDestinationIndex ) )
947 continue;
948
949 if (!sameParent && isDestinationIndex) {
950 if (childPosition >= destinationChild)
951 persistent_moved_in_destination.append(data);
952 continue;
953 }
954
955 if (sameParent && movingUp && childPosition < destinationChild)
956 continue;
957
958 if (sameParent && !movingUp && childPosition < srcFirst )
959 continue;
960
961 if (!sameParent && childPosition < srcFirst)
962 continue;
963
964 if (sameParent && (childPosition > srcLast) && (childPosition >= destinationChild ))
965 continue;
966
967 if ((childPosition <= srcLast) && (childPosition >= srcFirst)) {
968 persistent_moved_explicitly.append(data);
969 } else {
970 persistent_moved_in_source.append(data);
971 }
972 }
973 persistent.moved.push(persistent_moved_explicitly);
974 persistent.moved.push(persistent_moved_in_source);
975 persistent.moved.push(persistent_moved_in_destination);
976}
977
978/*!
979 \internal
980
981 Moves persistent indexes \a indexes by amount \a change. The change will be either a change in row value or a change in
982 column value depending on the value of \a orientation. The indexes may also be moved to a different parent if \a parent
983 differs from the existing parent for the index.
984*/
985void QAbstractItemModelPrivate::movePersistentIndexes(const QList<QPersistentModelIndexData *> &indexes, int change,
986 const QModelIndex &parent, Qt::Orientation orientation)
987{
988 for (auto *data : indexes) {
989 int row = data->index.row();
990 int column = data->index.column();
991
992 if (Qt::Vertical == orientation)
993 row += change;
994 else
995 column += change;
996
997 persistent.indexes.erase(persistent.indexes.constFind(data->index));
998 data->index = q_func()->index(row, column, parent);
999 if (data->index.isValid()) {
1000 persistent.insertMultiAtEnd(data->index, data);
1001 } else {
1002 qWarning() << "QAbstractItemModel::endMoveRows: Invalid index (" << row << "," << column << ") in model" << q_func();
1003 }
1004 }
1005}
1006
1007void QAbstractItemModelPrivate::itemsMoved(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild, Qt::Orientation orientation)
1008{
1009 const QList<QPersistentModelIndexData *> moved_in_destination = persistent.moved.pop();
1010 const QList<QPersistentModelIndexData *> moved_in_source = persistent.moved.pop();
1011 const QList<QPersistentModelIndexData *> moved_explicitly = persistent.moved.pop();
1012
1013 const bool sameParent = (sourceParent == destinationParent);
1014 const bool movingUp = (sourceFirst > destinationChild);
1015
1016 const int explicit_change = (!sameParent || movingUp) ? destinationChild - sourceFirst : destinationChild - sourceLast - 1 ;
1017 const int source_change = (!sameParent || !movingUp) ? -1*(sourceLast - sourceFirst + 1) : sourceLast - sourceFirst + 1 ;
1018 const int destination_change = sourceLast - sourceFirst + 1;
1019
1020 movePersistentIndexes(moved_explicitly, explicit_change, destinationParent, orientation);
1021 movePersistentIndexes(moved_in_source, source_change, sourceParent, orientation);
1022 movePersistentIndexes(moved_in_destination, destination_change, destinationParent, orientation);
1023}
1024
1025void QAbstractItemModelPrivate::rowsAboutToBeRemoved(const QModelIndex &parent,
1026 int first, int last)
1027{
1028 QList<QPersistentModelIndexData *> persistent_moved;
1029 QList<QPersistentModelIndexData *> persistent_invalidated;
1030 // find the persistent indexes that are affected by the change, either by being in the removed subtree
1031 // or by being on the same level and below the removed rows
1032 for (auto *data : qAsConst(persistent.indexes)) {
1033 bool level_changed = false;
1034 QModelIndex current = data->index;
1035 while (current.isValid()) {
1036 QModelIndex current_parent = current.parent();
1037 if (current_parent == parent) { // on the same level as the change
1038 if (!level_changed && current.row() > last) // below the removed rows
1039 persistent_moved.append(data);
1040 else if (current.row() <= last && current.row() >= first) // in the removed subtree
1041 persistent_invalidated.append(data);
1042 break;
1043 }
1044 current = current_parent;
1045 level_changed = true;
1046 }
1047 }
1048
1049 persistent.moved.push(persistent_moved);
1050 persistent.invalidated.push(persistent_invalidated);
1051}
1052
1053void QAbstractItemModelPrivate::rowsRemoved(const QModelIndex &parent,
1054 int first, int last)
1055{
1056 const QList<QPersistentModelIndexData *> persistent_moved = persistent.moved.pop();
1057 const int count = (last - first) + 1; // it is important to only use the delta, because the change could be nested
1058 for (auto *data : persistent_moved) {
1059 QModelIndex old = data->index;
1060 persistent.indexes.erase(persistent.indexes.constFind(old));
1061 data->index = q_func()->index(old.row() - count, old.column(), parent);
1062 if (data->index.isValid()) {
1063 persistent.insertMultiAtEnd(data->index, data);
1064 } else {
1065 qWarning() << "QAbstractItemModel::endRemoveRows: Invalid index (" << old.row() - count << ',' << old.column() << ") in model" << q_func();
1066 }
1067 }
1068 const QList<QPersistentModelIndexData *> persistent_invalidated = persistent.invalidated.pop();
1069 for (auto *data : persistent_invalidated) {
1070 auto pit = persistent.indexes.constFind(data->index);
1071 if (pit != persistent.indexes.cend())
1072 persistent.indexes.erase(pit);
1073 data->index = QModelIndex();
1074 }
1075}
1076
1077void QAbstractItemModelPrivate::columnsAboutToBeInserted(const QModelIndex &parent,
1078 int first, int last)
1079{
1080 Q_Q(QAbstractItemModel);
1081 Q_UNUSED(last);
1082 QList<QPersistentModelIndexData *> persistent_moved;
1083 if (first < q->columnCount(parent)) {
1084 for (auto *data : qAsConst(persistent.indexes)) {
1085 const QModelIndex &index = data->index;
1086 if (index.column() >= first && index.isValid() && index.parent() == parent)
1087 persistent_moved.append(data);
1088 }
1089 }
1090 persistent.moved.push(persistent_moved);
1091}
1092
1093void QAbstractItemModelPrivate::columnsInserted(const QModelIndex &parent,
1094 int first, int last)
1095{
1096 const QList<QPersistentModelIndexData *> persistent_moved = persistent.moved.pop();
1097 const int count = (last - first) + 1; // it is important to only use the delta, because the change could be nested
1098 for (auto *data : persistent_moved) {
1099 QModelIndex old = data->index;
1100 persistent.indexes.erase(persistent.indexes.constFind(old));
1101 data->index = q_func()->index(old.row(), old.column() + count, parent);
1102 if (data->index.isValid()) {
1103 persistent.insertMultiAtEnd(data->index, data);
1104 } else {
1105 qWarning() << "QAbstractItemModel::endInsertColumns: Invalid index (" << old.row() << ',' << old.column() + count << ") in model" << q_func();
1106 }
1107 }
1108}
1109
1110void QAbstractItemModelPrivate::columnsAboutToBeRemoved(const QModelIndex &parent,
1111 int first, int last)
1112{
1113 QList<QPersistentModelIndexData *> persistent_moved;
1114 QList<QPersistentModelIndexData *> persistent_invalidated;
1115 // find the persistent indexes that are affected by the change, either by being in the removed subtree
1116 // or by being on the same level and to the right of the removed columns
1117 for (auto *data : qAsConst(persistent.indexes)) {
1118 bool level_changed = false;
1119 QModelIndex current = data->index;
1120 while (current.isValid()) {
1121 QModelIndex current_parent = current.parent();
1122 if (current_parent == parent) { // on the same level as the change
1123 if (!level_changed && current.column() > last) // right of the removed columns
1124 persistent_moved.append(data);
1125 else if (current.column() <= last && current.column() >= first) // in the removed subtree
1126 persistent_invalidated.append(data);
1127 break;
1128 }
1129 current = current_parent;
1130 level_changed = true;
1131 }
1132 }
1133
1134 persistent.moved.push(persistent_moved);
1135 persistent.invalidated.push(persistent_invalidated);
1136
1137}
1138
1139void QAbstractItemModelPrivate::columnsRemoved(const QModelIndex &parent,
1140 int first, int last)
1141{
1142 const QList<QPersistentModelIndexData *> persistent_moved = persistent.moved.pop();
1143 const int count = (last - first) + 1; // it is important to only use the delta, because the change could be nested
1144 for (auto *data : persistent_moved) {
1145 QModelIndex old = data->index;
1146 persistent.indexes.erase(persistent.indexes.constFind(old));
1147 data->index = q_func()->index(old.row(), old.column() - count, parent);
1148 if (data->index.isValid()) {
1149 persistent.insertMultiAtEnd(data->index, data);
1150 } else {
1151 qWarning() << "QAbstractItemModel::endRemoveColumns: Invalid index (" << old.row() << ',' << old.column() - count << ") in model" << q_func();
1152 }
1153 }
1154 const QList<QPersistentModelIndexData *> persistent_invalidated = persistent.invalidated.pop();
1155 for (auto *data : persistent_invalidated) {
1156 auto index = persistent.indexes.constFind(data->index);
1157 if (index != persistent.indexes.constEnd())
1158 persistent.indexes.erase(index);
1159 data->index = QModelIndex();
1160 }
1161}
1162
1163/*!
1164 \since 4.8
1165
1166 This slot is called just after the internal data of a model is cleared
1167 while it is being reset.
1168
1169 This slot is provided the convenience of subclasses of concrete proxy
1170 models, such as subclasses of QSortFilterProxyModel which maintain extra
1171 data.
1172
1173 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 12
1174
1175 \note Due to a mistake, this slot is missing in Qt 5.0.
1176
1177 \sa modelAboutToBeReset(), modelReset()
1178*/
1179void QAbstractItemModel::resetInternalData()
1180{
1181
1182}
1183
1184/*!
1185 \class QModelIndex
1186 \inmodule QtCore
1187
1188 \brief The QModelIndex class is used to locate data in a data model.
1189
1190 \ingroup model-view
1191
1192
1193 This class is used as an index into item models derived from
1194 QAbstractItemModel. The index is used by item views, delegates, and
1195 selection models to locate an item in the model.
1196
1197 New QModelIndex objects are created by the model using the
1198 QAbstractItemModel::createIndex() function. An \e invalid model index can
1199 be constructed with the QModelIndex constructor. Invalid indexes are often
1200 used as parent indexes when referring to top-level items in a model.
1201
1202 Model indexes refer to items in models, and contain all the information
1203 required to specify their locations in those models. Each index is located
1204 in a given row and column, and may have a parent index; use row(),
1205 column(), and parent() to obtain this information. Each top-level item in a
1206 model is represented by a model index that does not have a parent index -
1207 in this case, parent() will return an invalid model index, equivalent to an
1208 index constructed with the zero argument form of the QModelIndex()
1209 constructor.
1210
1211 To obtain a model index that refers to an existing item in a model, call
1212 QAbstractItemModel::index() with the required row and column values, and
1213 the model index of the parent. When referring to top-level items in a
1214 model, supply QModelIndex() as the parent index.
1215
1216 The model() function returns the model that the index references as a
1217 QAbstractItemModel. The child() function is used to examine items held
1218 under the index in the model. The sibling() function allows you to traverse
1219 items in the model on the same level as the index.
1220
1221 \note Model indexes should be used immediately and then discarded. You
1222 should not rely on indexes to remain valid after calling model functions
1223 that change the structure of the model or delete items. If you need to
1224 keep a model index over time use a QPersistentModelIndex.
1225
1226 \sa {Model/View Programming}, QPersistentModelIndex, QAbstractItemModel
1227*/
1228
1229/*!
1230 \fn QModelIndex::QModelIndex()
1231
1232 Creates a new empty model index. This type of model index is used to
1233 indicate that the position in the model is invalid.
1234
1235 \sa isValid(), QAbstractItemModel
1236*/
1237
1238/*!
1239 \fn QModelIndex::QModelIndex(int row, int column, void *data, const QAbstractItemModel *model)
1240
1241 \internal
1242
1243 Creates a new model index at the given \a row and \a column,
1244 pointing to some \a data.
1245*/
1246
1247/*!
1248 \fn int QModelIndex::row() const
1249
1250 Returns the row this model index refers to.
1251*/
1252
1253
1254/*!
1255 \fn int QModelIndex::column() const
1256
1257 Returns the column this model index refers to.
1258*/
1259
1260
1261/*!
1262 \fn void *QModelIndex::internalPointer() const
1263
1264 Returns a \c{void} \c{*} pointer used by the model to associate
1265 the index with the internal data structure.
1266
1267 \sa QAbstractItemModel::createIndex()
1268*/
1269
1270/*!
1271 \fn const void *QModelIndex::constInternalPointer() const
1272
1273 Returns a \c{const void} \c{*} pointer used by the model to associate
1274 the index with the internal data structure.
1275
1276 \sa QAbstractItemModel::createIndex()
1277*/
1278
1279/*!
1280 \fn quintptr QModelIndex::internalId() const
1281
1282 Returns a \c{quintptr} used by the model to associate
1283 the index with the internal data structure.
1284
1285 \sa QAbstractItemModel::createIndex()
1286*/
1287
1288/*!
1289 \fn bool QModelIndex::isValid() const
1290
1291 Returns \c{true} if this model index is valid; otherwise returns \c{false}.
1292
1293 A valid index belongs to a model, and has non-negative row and column
1294 numbers.
1295
1296 \sa model(), row(), column()
1297*/
1298
1299/*!
1300 \fn const QAbstractItemModel *QModelIndex::model() const
1301
1302 Returns a pointer to the model containing the item that this index
1303 refers to.
1304
1305 A const pointer to the model is returned because calls to non-const
1306 functions of the model might invalidate the model index and possibly
1307 crash your application.
1308*/
1309
1310/*!
1311 \fn QModelIndex QModelIndex::sibling(int row, int column) const
1312
1313 Returns the sibling at \a row and \a column. If there is no sibling at this
1314 position, an invalid QModelIndex is returned.
1315
1316 \sa parent(), siblingAtColumn(), siblingAtRow()
1317*/
1318
1319/*!
1320 \fn QModelIndex QModelIndex::siblingAtColumn(int column) const
1321
1322 Returns the sibling at \a column for the current row. If there is no sibling
1323 at this position, an invalid QModelIndex is returned.
1324
1325 \sa sibling(), siblingAtRow()
1326 \since 5.11
1327*/
1328
1329/*!
1330 \fn QModelIndex QModelIndex::siblingAtRow(int row) const
1331
1332 Returns the sibling at \a row for the current column. If there is no sibling
1333 at this position, an invalid QModelIndex is returned.
1334
1335 \sa sibling(), siblingAtColumn()
1336 \since 5.11
1337*/
1338
1339/*!
1340 \fn QVariant QModelIndex::data(int role) const
1341
1342 Returns the data for the given \a role for the item referred to by the
1343 index.
1344*/
1345
1346/*!
1347 \fn void QModelIndex::multiData(QModelRoleDataSpan roleDataSpan) const
1348 \since 6.0
1349
1350 Populates the given \a roleDataSpan for the item referred to by the
1351 index.
1352*/
1353
1354/*!
1355 \fn Qt::ItemFlags QModelIndex::flags() const
1356 \since 4.2
1357
1358 Returns the flags for the item referred to by the index.
1359*/
1360
1361/*!
1362 \fn bool QModelIndex::operator==(const QModelIndex &other) const
1363
1364 Returns \c{true} if this model index refers to the same location as the
1365 \a other model index; otherwise returns \c{false}.
1366
1367 The internal data pointer, row, column, and model values are used when
1368 comparing with another model index.
1369*/
1370
1371
1372/*!
1373 \fn bool QModelIndex::operator!=(const QModelIndex &other) const
1374
1375 Returns \c{true} if this model index does not refer to the same location as
1376 the \a other model index; otherwise returns \c{false}.
1377*/
1378
1379
1380/*!
1381 \fn QModelIndex QModelIndex::parent() const
1382
1383 Returns the parent of the model index, or QModelIndex() if it has no
1384 parent.
1385
1386 \sa sibling(), model()
1387*/
1388
1389/*!
1390 \class QAbstractItemModel
1391 \inmodule QtCore
1392
1393 \brief The QAbstractItemModel class provides the abstract interface for
1394 item model classes.
1395
1396 \ingroup model-view
1397
1398
1399 The QAbstractItemModel class defines the standard interface that item
1400 models must use to be able to interoperate with other components in the
1401 model/view architecture. It is not supposed to be instantiated directly.
1402 Instead, you should subclass it to create new models.
1403
1404 The QAbstractItemModel class is one of the \l{Model/View Classes}
1405 and is part of Qt's \l{Model/View Programming}{model/view framework}. It
1406 can be used as the underlying data model for the item view elements in
1407 QML or the item view classes in the Qt Widgets module.
1408
1409 If you need a model to use with an item view such as QML's List View
1410 element or the C++ widgets QListView or QTableView, you should consider
1411 subclassing QAbstractListModel or QAbstractTableModel instead of this class.
1412
1413 The underlying data model is exposed to views and delegates as a hierarchy
1414 of tables. If you do not make use of the hierarchy, then the model is a
1415 simple table of rows and columns. Each item has a unique index specified by
1416 a QModelIndex.
1417
1418 \image modelindex-no-parent.png
1419
1420 Every item of data that can be accessed via a model has an associated model
1421 index. You can obtain this model index using the index() function. Each
1422 index may have a sibling() index; child items have a parent() index.
1423
1424 Each item has a number of data elements associated with it and they can be
1425 retrieved by specifying a role (see \l Qt::ItemDataRole) to the model's
1426 data() function. Data for all available roles can be obtained at the same
1427 time using the itemData() function.
1428
1429 Data for each role is set using a particular \l Qt::ItemDataRole. Data for
1430 individual roles are set individually with setData(), or they can be set
1431 for all roles with setItemData().
1432
1433 Items can be queried with flags() (see \l Qt::ItemFlag) to see if they can
1434 be selected, dragged, or manipulated in other ways.
1435
1436 If an item has child objects, hasChildren() returns \c{true} for the
1437 corresponding index.
1438
1439 The model has a rowCount() and a columnCount() for each level of the
1440 hierarchy. Rows and columns can be inserted and removed with insertRows(),
1441 insertColumns(), removeRows(), and removeColumns().
1442
1443 The model emits signals to indicate changes. For example, dataChanged() is
1444 emitted whenever items of data made available by the model are changed.
1445 Changes to the headers supplied by the model cause headerDataChanged() to
1446 be emitted. If the structure of the underlying data changes, the model can
1447 emit layoutChanged() to indicate to any attached views that they should
1448 redisplay any items shown, taking the new structure into account.
1449
1450 The items available through the model can be searched for particular data
1451 using the match() function.
1452
1453 To sort the model, you can use sort().
1454
1455
1456 \section1 Subclassing
1457
1458 \note Some general guidelines for subclassing models are available in the
1459 \l{Model Subclassing Reference}.
1460
1461 When subclassing QAbstractItemModel, at the very least you must implement
1462 index(), parent(), rowCount(), columnCount(), and data(). These functions
1463 are used in all read-only models, and form the basis of editable models.
1464
1465 You can also reimplement hasChildren() to provide special behavior for
1466 models where the implementation of rowCount() is expensive. This makes it
1467 possible for models to restrict the amount of data requested by views, and
1468 can be used as a way to implement lazy population of model data.
1469
1470 To enable editing in your model, you must also implement setData(), and
1471 reimplement flags() to ensure that \c ItemIsEditable is returned. You can
1472 also reimplement headerData() and setHeaderData() to control the way the
1473 headers for your model are presented.
1474
1475 The dataChanged() and headerDataChanged() signals must be emitted
1476 explicitly when reimplementing the setData() and setHeaderData() functions,
1477 respectively.
1478
1479 Custom models need to create model indexes for other components to use. To
1480 do this, call createIndex() with suitable row and column numbers for the
1481 item, and an identifier for it, either as a pointer or as an integer value.
1482 The combination of these values must be unique for each item. Custom models
1483 typically use these unique identifiers in other reimplemented functions to
1484 retrieve item data and access information about the item's parents and
1485 children. See the \l{Simple Tree Model Example} for more information about
1486 unique identifiers.
1487
1488 It is not necessary to support every role defined in Qt::ItemDataRole.
1489 Depending on the type of data contained within a model, it may only be
1490 useful to implement the data() function to return valid information for
1491 some of the more common roles. Most models provide at least a textual
1492 representation of item data for the Qt::DisplayRole, and well-behaved
1493 models should also provide valid information for the Qt::ToolTipRole and
1494 Qt::WhatsThisRole. Supporting these roles enables models to be used with
1495 standard Qt views. However, for some models that handle highly-specialized
1496 data, it may be appropriate to provide data only for user-defined roles.
1497
1498 Models that provide interfaces to resizable data structures can provide
1499 implementations of insertRows(), removeRows(), insertColumns(),and
1500 removeColumns(). When implementing these functions, it is important to
1501 notify any connected views about changes to the model's dimensions both
1502 \e before and \e after they occur:
1503
1504 \list
1505 \li An insertRows() implementation must call beginInsertRows() \e before
1506 inserting new rows into the data structure, and endInsertRows()
1507 \e{immediately afterwards}.
1508 \li An insertColumns() implementation must call beginInsertColumns()
1509 \e before inserting new columns into the data structure, and
1510 endInsertColumns() \e{immediately afterwards}.
1511 \li A removeRows() implementation must call beginRemoveRows() \e before
1512 the rows are removed from the data structure, and endRemoveRows()
1513 \e{immediately afterwards}.
1514 \li A removeColumns() implementation must call beginRemoveColumns()
1515 \e before the columns are removed from the data structure, and
1516 endRemoveColumns() \e{immediately afterwards}.
1517 \endlist
1518
1519 The \e private signals that these functions emit give attached components
1520 the chance to take action before any data becomes unavailable. The
1521 encapsulation of the insert and remove operations with these begin and end
1522 functions also enables the model to manage \l{QPersistentModelIndex}
1523 {persistent model indexes} correctly. \b{If you want selections to be
1524 handled properly, you must ensure that you call these functions.} If you
1525 insert or remove an item with children, you do not need to call these
1526 functions for the child items. In other words, the parent item will take
1527 care of its child items.
1528
1529 To create models that populate incrementally, you can reimplement
1530 fetchMore() and canFetchMore(). If the reimplementation of fetchMore() adds
1531 rows to the model, \l{QAbstractItemModel::}{beginInsertRows()} and
1532 \l{QAbstractItemModel::}{endInsertRows()} must be called.
1533
1534 \sa {Model Classes}, {Model Subclassing Reference}, QModelIndex,
1535 QAbstractItemView, {Using drag and drop with item views},
1536 {Simple DOM Model Example}, {Simple Tree Model Example},
1537 {Editable Tree Model Example}, {Fetch More Example}
1538*/
1539
1540/*!
1541 \fn QModelIndex QAbstractItemModel::index(int row, int column, const QModelIndex &parent) const = 0
1542
1543 Returns the index of the item in the model specified by the given \a row,
1544 \a column and \a parent index.
1545
1546 When reimplementing this function in a subclass, call createIndex() to
1547 generate model indexes that other components can use to refer to items in
1548 your model.
1549
1550 \sa createIndex()
1551*/
1552
1553/*!
1554 \fn bool QAbstractItemModel::insertColumn(int column, const QModelIndex &parent)
1555
1556 Inserts a single column before the given \a column in the child items of
1557 the \a parent specified.
1558
1559 Returns \c{true} if the column is inserted; otherwise returns \c{false}.
1560
1561 \sa insertColumns(), insertRow(), removeColumn()
1562*/
1563
1564/*!
1565 \fn bool QAbstractItemModel::insertRow(int row, const QModelIndex &parent)
1566
1567 Inserts a single row before the given \a row in the child items of the
1568 \a parent specified.
1569
1570 \note This function calls the virtual method insertRows.
1571
1572 Returns \c{true} if the row is inserted; otherwise returns \c{false}.
1573
1574 \sa insertRows(), insertColumn(), removeRow()
1575*/
1576
1577/*!
1578 \fn QModelIndex QAbstractItemModel::parent(const QModelIndex &index) const = 0
1579
1580 Returns the parent of the model item with the given \a index. If the item
1581 has no parent, an invalid QModelIndex is returned.
1582
1583 A common convention used in models that expose tree data structures is that
1584 only items in the first column have children. For that case, when
1585 reimplementing this function in a subclass the column of the returned
1586 QModelIndex would be 0.
1587
1588 When reimplementing this function in a subclass, be careful to avoid
1589 calling QModelIndex member functions, such as QModelIndex::parent(), since
1590 indexes belonging to your model will simply call your implementation,
1591 leading to infinite recursion.
1592
1593 \sa createIndex()
1594*/
1595
1596/*!
1597 \fn bool QAbstractItemModel::removeColumn(int column, const QModelIndex &parent)
1598
1599 Removes the given \a column from the child items of the \a parent
1600 specified.
1601
1602 Returns \c{true} if the column is removed; otherwise returns \c{false}.
1603
1604 \sa removeColumns(), removeRow(), insertColumn()
1605*/
1606
1607/*!
1608 \fn bool QAbstractItemModel::removeRow(int row, const QModelIndex &parent)
1609
1610 Removes the given \a row from the child items of the \a parent specified.
1611
1612 Returns \c{true} if the row is removed; otherwise returns \c{false}.
1613
1614 This is a convenience function that calls removeRows(). The
1615 QAbstractItemModel implementation of removeRows() does nothing.
1616
1617 \sa removeRows(), removeColumn(), insertRow()
1618*/
1619
1620/*!
1621 \fn bool QAbstractItemModel::moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)
1622
1623 On models that support this, moves \a sourceRow from \a sourceParent to \a destinationChild under
1624 \a destinationParent.
1625
1626 Returns \c{true} if the rows were successfully moved; otherwise returns
1627 \c{false}.
1628
1629 \sa moveRows(), moveColumn()
1630*/
1631
1632/*!
1633 \fn bool QAbstractItemModel::moveColumn(const QModelIndex &sourceParent, int sourceColumn, const QModelIndex &destinationParent, int destinationChild)
1634
1635 On models that support this, moves \a sourceColumn from \a sourceParent to \a destinationChild under
1636 \a destinationParent.
1637
1638 Returns \c{true} if the columns were successfully moved; otherwise returns
1639 \c{false}.
1640
1641 \sa moveColumns(), moveRow()
1642*/
1643
1644
1645/*!
1646 \fn void QAbstractItemModel::headerDataChanged(Qt::Orientation orientation, int first, int last)
1647
1648 This signal is emitted whenever a header is changed. The \a orientation
1649 indicates whether the horizontal or vertical header has changed. The
1650 sections in the header from the \a first to the \a last need to be updated.
1651
1652 When reimplementing the setHeaderData() function, this signal must be
1653 emitted explicitly.
1654
1655 If you are changing the number of columns or rows you do not need to emit
1656 this signal, but use the begin/end functions (refer to the section on
1657 subclassing in the QAbstractItemModel class description for details).
1658
1659 \sa headerData(), setHeaderData(), dataChanged()
1660*/
1661
1662
1663/*!
1664 \enum QAbstractItemModel::LayoutChangeHint
1665
1666 This enum describes the way the model changes layout.
1667
1668 \value NoLayoutChangeHint No hint is available.
1669 \value VerticalSortHint Rows are being sorted.
1670 \value HorizontalSortHint Columns are being sorted.
1671
1672 Note that VerticalSortHint and HorizontalSortHint carry the meaning that
1673 items are being moved within the same parent, not moved to a different
1674 parent in the model, and not filtered out or in.
1675*/
1676
1677/*!
1678 \fn void QAbstractItemModel::layoutAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)
1679 \since 5.0
1680
1681 This signal is emitted just before the layout of a model is changed.
1682 Components connected to this signal use it to adapt to changes in the
1683 model's layout.
1684
1685 Subclasses should update any persistent model indexes after emitting
1686 layoutAboutToBeChanged().
1687
1688 The optional \a parents parameter is used to give a more specific notification
1689 about what parts of the layout of the model are changing. An empty list indicates
1690 a change to the layout of the entire model. The order of elements in the \a parents list is not significant. The optional \a hint parameter is used
1691 to give a hint about what is happening while the model is relayouting.
1692
1693 \sa layoutChanged(), changePersistentIndex()
1694*/
1695
1696/*!
1697 \fn void QAbstractItemModel::layoutChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(), QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint)
1698 \since 5.0
1699
1700 This signal is emitted whenever the layout of items exposed by the model
1701 has changed; for example, when the model has been sorted. When this signal
1702 is received by a view, it should update the layout of items to reflect this
1703 change.
1704
1705 When subclassing QAbstractItemModel or QAbstractProxyModel, ensure that you
1706 emit layoutAboutToBeChanged() before changing the order of items or
1707 altering the structure of the data you expose to views, and emit
1708 layoutChanged() after changing the layout.
1709
1710 The optional \a parents parameter is used to give a more specific notification
1711 about what parts of the layout of the model are changing. An empty list indicates
1712 a change to the layout of the entire model. The order of elements in the \a parents list is not significant. The optional \a hint parameter is used
1713 to give a hint about what is happening while the model is relayouting.
1714
1715 Subclasses should update any persistent model indexes before emitting
1716 layoutChanged(). In other words, when the structure changes:
1717
1718 \list
1719 \li emit layoutAboutToBeChanged
1720 \li Remember the QModelIndex that will change
1721 \li Update your internal data
1722 \li Call changePersistentIndex()
1723 \li emit layoutChanged
1724 \endlist
1725
1726 \sa layoutAboutToBeChanged(), dataChanged(), headerDataChanged(), modelReset(),
1727 changePersistentIndex()
1728*/
1729
1730/*!
1731 Constructs an abstract item model with the given \a parent.
1732*/
1733QAbstractItemModel::QAbstractItemModel(QObject *parent)
1734 : QObject(*new QAbstractItemModelPrivate, parent)
1735{
1736}
1737
1738/*!
1739 \internal
1740*/
1741QAbstractItemModel::QAbstractItemModel(QAbstractItemModelPrivate &dd, QObject *parent)
1742 : QObject(dd, parent)
1743{
1744}
1745
1746/*!
1747 Destroys the abstract item model.
1748*/
1749QAbstractItemModel::~QAbstractItemModel()
1750{
1751 d_func()->invalidatePersistentIndexes();
1752}
1753
1754
1755/*!
1756 \fn int QAbstractItemModel::rowCount(const QModelIndex &parent) const
1757
1758 Returns the number of rows under the given \a parent. When the parent is
1759 valid it means that rowCount is returning the number of children of parent.
1760
1761 \note When implementing a table based model, rowCount() should return 0
1762 when the parent is valid.
1763
1764 \sa columnCount()
1765*/
1766
1767/*!
1768 \fn int QAbstractItemModel::columnCount(const QModelIndex &parent) const
1769
1770 Returns the number of columns for the children of the given \a parent.
1771
1772 In most subclasses, the number of columns is independent of the \a parent.
1773
1774 For example:
1775
1776 \snippet ../widgets/itemviews/simpledommodel/dommodel.cpp 2
1777
1778 \note When implementing a table based model, columnCount() should return 0
1779 when the parent is valid.
1780
1781 \sa rowCount()
1782*/
1783
1784/*!
1785 \fn void QAbstractItemModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles = QList<int>())
1786
1787 This signal is emitted whenever the data in an existing item changes.
1788
1789 If the items are of the same parent, the affected ones are those between
1790 \a topLeft and \a bottomRight inclusive. If the items do not have the same
1791 parent, the behavior is undefined.
1792
1793 When reimplementing the setData() function, this signal must be emitted
1794 explicitly.
1795
1796 The optional \a roles argument can be used to specify which data roles have actually
1797 been modified. An empty vector in the roles argument means that all roles should be
1798 considered modified. The order of elements in the roles argument does not have any
1799 relevance.
1800
1801 \sa headerDataChanged(), setData(), layoutChanged()
1802*/
1803
1804/*!
1805 \fn void QAbstractItemModel::rowsInserted(const QModelIndex &parent, int first, int last)
1806
1807 This signal is emitted after rows have been inserted into the
1808 model. The new items are those between \a first and \a last
1809 inclusive, under the given \a parent item.
1810
1811 \note Components connected to this signal use it to adapt to changes in the
1812 model's dimensions. It can only be emitted by the QAbstractItemModel
1813 implementation, and cannot be explicitly emitted in subclass code.
1814
1815 \sa insertRows(), beginInsertRows()
1816*/
1817
1818/*!
1819 \fn void QAbstractItemModel::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
1820
1821 This signal is emitted just before rows are inserted into the model. The
1822 new items will be positioned between \a start and \a end inclusive, under
1823 the given \a parent item.
1824
1825 \note Components connected to this signal use it to adapt to changes
1826 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1827 implementation, and cannot be explicitly emitted in subclass code.
1828
1829 \sa insertRows(), beginInsertRows()
1830*/
1831
1832/*!
1833 \fn void QAbstractItemModel::rowsRemoved(const QModelIndex &parent, int first, int last)
1834
1835 This signal is emitted after rows have been removed from the model. The
1836 removed items are those between \a first and \a last inclusive, under the
1837 given \a parent item.
1838
1839 \note Components connected to this signal use it to adapt to changes
1840 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1841 implementation, and cannot be explicitly emitted in subclass code.
1842
1843 \sa removeRows(), beginRemoveRows()
1844*/
1845
1846/*!
1847 \fn void QAbstractItemModel::rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
1848
1849 This signal is emitted just before rows are removed from the model. The
1850 items that will be removed are those between \a first and \a last inclusive,
1851 under the given \a parent item.
1852
1853 \note Components connected to this signal use it to adapt to changes
1854 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1855 implementation, and cannot be explicitly emitted in subclass code.
1856
1857 \sa removeRows(), beginRemoveRows()
1858*/
1859
1860/*!
1861 \fn void QAbstractItemModel::rowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row)
1862 \since 4.6
1863
1864 This signal is emitted after rows have been moved within the
1865 model. The items between \a start and \a end
1866 inclusive, under the given \a parent item have been moved to \a destination
1867 starting at the row \a row.
1868
1869 \b{Note:} Components connected to this signal use it to adapt to changes
1870 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1871 implementation, and cannot be explicitly emitted in subclass code.
1872
1873 \sa beginMoveRows()
1874*/
1875
1876/*!
1877 \fn void QAbstractItemModel::rowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
1878 \since 4.6
1879
1880 This signal is emitted just before rows are moved within the
1881 model. The items that will be moved are those between \a sourceStart and \a sourceEnd
1882 inclusive, under the given \a sourceParent item. They will be moved to \a destinationParent
1883 starting at the row \a destinationRow.
1884
1885 \b{Note:} Components connected to this signal use it to adapt to changes
1886 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1887 implementation, and cannot be explicitly emitted in subclass code.
1888
1889 \sa beginMoveRows()
1890*/
1891
1892/*!
1893 \fn void QAbstractItemModel::columnsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column)
1894 \since 4.6
1895
1896 This signal is emitted after columns have been moved within the
1897 model. The items between \a start and \a end
1898 inclusive, under the given \a parent item have been moved to \a destination
1899 starting at the column \a column.
1900
1901 \b{Note:} Components connected to this signal use it to adapt to changes
1902 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1903 implementation, and cannot be explicitly emitted in subclass code.
1904
1905 \sa beginMoveRows()
1906*/
1907
1908/*!
1909 \fn void QAbstractItemModel::columnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationColumn)
1910 \since 4.6
1911
1912 This signal is emitted just before columns are moved within the
1913 model. The items that will be moved are those between \a sourceStart and \a sourceEnd
1914 inclusive, under the given \a sourceParent item. They will be moved to \a destinationParent
1915 starting at the column \a destinationColumn.
1916
1917 \b{Note:} Components connected to this signal use it to adapt to changes
1918 in the model's dimensions. It can only be emitted by the QAbstractItemModel
1919 implementation, and cannot be explicitly emitted in subclass code.
1920
1921 \sa beginMoveRows()
1922*/
1923
1924/*!
1925 \fn void QAbstractItemModel::columnsInserted(const QModelIndex &parent, int first, int last)
1926
1927 This signal is emitted after columns have been inserted into the model. The
1928 new items are those between \a first and \a last inclusive, under the given
1929 \a parent item.
1930
1931 \note Components connected to this signal use it to adapt to changes in the
1932 model's dimensions. It can only be emitted by the QAbstractItemModel
1933 implementation, and cannot be explicitly emitted in subclass code.
1934
1935 \sa insertColumns(), beginInsertColumns()
1936*/
1937
1938/*!
1939 \fn void QAbstractItemModel::columnsAboutToBeInserted(const QModelIndex &parent, int first, int last)
1940
1941 This signal is emitted just before columns are inserted into the model. The
1942 new items will be positioned between \a first and \a last inclusive, under
1943 the given \a parent item.
1944
1945 \note Components connected to this signal use it to adapt to changes in the
1946 model's dimensions. It can only be emitted by the QAbstractItemModel
1947 implementation, and cannot be explicitly emitted in subclass code.
1948
1949 \sa insertColumns(), beginInsertColumns()
1950*/
1951
1952/*!
1953 \fn void QAbstractItemModel::columnsRemoved(const QModelIndex &parent, int first, int last)
1954
1955 This signal is emitted after columns have been removed from the model.
1956 The removed items are those between \a first and \a last inclusive,
1957 under the given \a parent item.
1958
1959 \note Components connected to this signal use it to adapt to changes in
1960 the model's dimensions. It can only be emitted by the QAbstractItemModel
1961 implementation, and cannot be explicitly emitted in subclass code.
1962
1963 \sa removeColumns(), beginRemoveColumns()
1964*/
1965
1966/*!
1967 \fn void QAbstractItemModel::columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
1968
1969 This signal is emitted just before columns are removed from the model. The
1970 items to be removed are those between \a first and \a last inclusive, under
1971 the given \a parent item.
1972
1973 \note Components connected to this signal use it to adapt to changes in the
1974 model's dimensions. It can only be emitted by the QAbstractItemModel
1975 implementation, and cannot be explicitly emitted in subclass code.
1976
1977 \sa removeColumns(), beginRemoveColumns()
1978*/
1979
1980/*!
1981 Returns \c{true} if the model returns a valid QModelIndex for \a row and
1982 \a column with \a parent, otherwise returns \c{false}.
1983*/
1984bool QAbstractItemModel::hasIndex(int row, int column, const QModelIndex &parent) const
1985{
1986 if (row < 0 || column < 0)
1987 return false;
1988 return row < rowCount(parent) && column < columnCount(parent);
1989}
1990
1991
1992/*!
1993 Returns \c{true} if \a parent has any children; otherwise returns \c{false}.
1994
1995 Use rowCount() on the parent to find out the number of children.
1996
1997 Note that it is undefined behavior to report that a particular index hasChildren
1998 with this method if the same index has the flag Qt::ItemNeverHasChildren set.
1999
2000 \sa parent(), index()
2001*/
2002bool QAbstractItemModel::hasChildren(const QModelIndex &parent) const
2003{
2004 return (rowCount(parent) > 0) && (columnCount(parent) > 0);
2005}
2006
2007/*!
2008 \fn QModelIndex QAbstractItemModel::sibling(int row, int column, const QModelIndex &index) const
2009
2010 Returns the sibling at \a row and \a column for the item at \a index, or an
2011 invalid QModelIndex if there is no sibling at that location.
2012
2013 sibling() is just a convenience function that finds the item's parent, and
2014 uses it to retrieve the index of the child item in the specified \a row and
2015 \a column.
2016
2017 This method can optionally be overridden for implementation-specific optimization.
2018
2019 \sa index(), QModelIndex::row(), QModelIndex::column()
2020*/
2021QModelIndex QAbstractItemModel::sibling(int row, int column, const QModelIndex &idx) const
2022{
2023 return (row == idx.row() && column == idx.column()) ? idx : index(row, column, parent(idx));
2024}
2025
2026
2027/*!
2028 Returns a map with values for all predefined roles in the model for the
2029 item at the given \a index.
2030
2031 Reimplement this function if you want to extend the default behavior of
2032 this function to include custom roles in the map.
2033
2034 \sa Qt::ItemDataRole, data()
2035*/
2036QMap<int, QVariant> QAbstractItemModel::itemData(const QModelIndex &index) const
2037{
2038 QMap<int, QVariant> roles;
2039 for (int i = 0; i < Qt::UserRole; ++i) {
2040 QVariant variantData = data(index, i);
2041 if (variantData.isValid())
2042 roles.insert(i, variantData);
2043 }
2044 return roles;
2045}
2046
2047/*!
2048 Sets the \a role data for the item at \a index to \a value.
2049
2050 Returns \c{true} if successful; otherwise returns \c{false}.
2051
2052 The dataChanged() signal should be emitted if the data was successfully
2053 set.
2054
2055 The base class implementation returns \c{false}. This function and data() must
2056 be reimplemented for editable models.
2057
2058 \sa Qt::ItemDataRole, data(), itemData()
2059*/
2060bool QAbstractItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
2061{
2062 Q_UNUSED(index);
2063 Q_UNUSED(value);
2064 Q_UNUSED(role);
2065 return false;
2066}
2067
2068/*!
2069 \since 6.0
2070 Removes the data stored in all the roles for the given \a index.
2071 Returns \c{true} if successful; otherwise returns \c{false}.
2072 The dataChanged() signal should be emitted if the data was successfully
2073 removed.
2074 The base class implementation returns \c{false}
2075 \sa data(), itemData(), setData(), setItemData()
2076*/
2077bool QAbstractItemModel::clearItemData(const QModelIndex &index)
2078{
2079 Q_UNUSED(index);
2080 return false;
2081}
2082
2083/*!
2084 \fn QVariant QAbstractItemModel::data(const QModelIndex &index, int role) const = 0
2085
2086 Returns the data stored under the given \a role for the item referred to
2087 by the \a index.
2088
2089 \note If you do not have a value to return, return an \b invalid
2090 QVariant instead of returning 0.
2091
2092 \sa Qt::ItemDataRole, setData(), headerData()
2093*/
2094
2095/*!
2096 Sets the role data for the item at \a index to the associated value in
2097 \a roles, for every Qt::ItemDataRole.
2098
2099 Returns \c{true} if successful; otherwise returns \c{false}.
2100
2101 Roles that are not in \a roles will not be modified.
2102
2103 \sa setData(), data(), itemData()
2104*/
2105bool QAbstractItemModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)
2106{
2107 // ### Qt 6: Consider change the semantics of this function,
2108 // or deprecating/removing it altogether.
2109 //
2110 // For instance, it should try setting *all* the data
2111 // in \a roles, and not bail out at the first setData that returns
2112 // false. It should also have a transactional approach.
2113 for (auto it = roles.begin(), e = roles.end(); it != e; ++it) {
2114 if (!setData(index, it.value(), it.key()))
2115 return false;
2116 }
2117 return true;
2118}
2119
2120/*!
2121 Returns the list of allowed MIME types. By default, the built-in
2122 models and views use an internal MIME type:
2123 \c{application/x-qabstractitemmodeldatalist}.
2124
2125 When implementing drag and drop support in a custom model, if you
2126 will return data in formats other than the default internal MIME
2127 type, reimplement this function to return your list of MIME types.
2128
2129 If you reimplement this function in your custom model, you must
2130 also reimplement the member functions that call it: mimeData() and
2131 dropMimeData().
2132
2133 \sa mimeData(), dropMimeData()
2134*/
2135QStringList QAbstractItemModel::mimeTypes() const
2136{
2137 QStringList types;
2138 types << QStringLiteral("application/x-qabstractitemmodeldatalist");
2139 return types;
2140}
2141
2142/*!
2143 Returns an object that contains serialized items of data corresponding to
2144 the list of \a indexes specified. The format used to describe the encoded
2145 data is obtained from the mimeTypes() function. This default implementation
2146 uses the default MIME type returned by the default implementation of
2147 mimeTypes(). If you reimplement mimeTypes() in your custom model to return
2148 more MIME types, reimplement this function to make use of them.
2149
2150 If the list of \a indexes is empty, or there are no supported MIME types,
2151 \nullptr is returned rather than a serialized empty list.
2152
2153 \sa mimeTypes(), dropMimeData()
2154*/
2155QMimeData *QAbstractItemModel::mimeData(const QModelIndexList &indexes) const
2156{
2157 if (indexes.count() <= 0)
2158 return nullptr;
2159 QStringList types = mimeTypes();
2160 if (types.isEmpty())
2161 return nullptr;
2162 QMimeData *data = new QMimeData();
2163 QString format = types.at(0);
2164 QByteArray encoded;
2165 QDataStream stream(&encoded, QDataStream::WriteOnly);
2166 encodeData(indexes, stream);
2167 data->setData(format, encoded);
2168 return data;
2169}
2170
2171/*!
2172 Returns \c{true} if a model can accept a drop of the \a data. This
2173 default implementation only checks if \a data has at least one format
2174 in the list of mimeTypes() and if \a action is among the
2175 model's supportedDropActions().
2176
2177 Reimplement this function in your custom model, if you want to
2178 test whether the \a data can be dropped at \a row, \a column,
2179 \a parent with \a action. If you don't need that test, it is not
2180 necessary to reimplement this function.
2181
2182 \sa dropMimeData(), {Using drag and drop with item views}
2183 */
2184bool QAbstractItemModel::canDropMimeData(const QMimeData *data, Qt::DropAction action,
2185 int row, int column,
2186 const QModelIndex &parent) const
2187{
2188 Q_UNUSED(row);
2189 Q_UNUSED(column);
2190 Q_UNUSED(parent);
2191
2192 if (!(action & supportedDropActions()))
2193 return false;
2194
2195 const QStringList modelTypes = mimeTypes();
2196 for (int i = 0; i < modelTypes.count(); ++i) {
2197 if (data->hasFormat(modelTypes.at(i)))
2198 return true;
2199 }
2200 return false;
2201}
2202
2203/*!
2204 Handles the \a data supplied by a drag and drop operation that ended with
2205 the given \a action.
2206
2207 Returns \c{true} if the data and action were handled by the model; otherwise
2208 returns \c{false}.
2209
2210 The specified \a row, \a column and \a parent indicate the location of an
2211 item in the model where the operation ended. It is the responsibility of
2212 the model to complete the action at the correct location.
2213
2214 For instance, a drop action on an item in a QTreeView can result in new
2215 items either being inserted as children of the item specified by \a row,
2216 \a column, and \a parent, or as siblings of the item.
2217
2218 When \a row and \a column are -1 it means that the dropped data should be
2219 considered as dropped directly on \a parent. Usually this will mean
2220 appending the data as child items of \a parent. If \a row and \a column are
2221 greater than or equal zero, it means that the drop occurred just before the
2222 specified \a row and \a column in the specified \a parent.
2223
2224 The mimeTypes() member is called to get the list of acceptable MIME types.
2225 This default implementation assumes the default implementation of mimeTypes(),
2226 which returns a single default MIME type. If you reimplement mimeTypes() in
2227 your custom model to return multiple MIME types, you must reimplement this
2228 function to make use of them.
2229
2230 \sa supportedDropActions(), canDropMimeData(), {Using drag and drop with item views}
2231*/
2232bool QAbstractItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
2233 int row, int column, const QModelIndex &parent)
2234{
2235 // check if the action is supported
2236 if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
2237 return false;
2238 // check if the format is supported
2239 QStringList types = mimeTypes();
2240 if (types.isEmpty())
2241 return false;
2242 QString format = types.at(0);
2243 if (!data->hasFormat(format))
2244 return false;
2245 if (row > rowCount(parent))
2246 row = rowCount(parent);
2247 if (row == -1)
2248 row = rowCount(parent);
2249 if (column == -1)
2250 column = 0;
2251 // decode and insert
2252 QByteArray encoded = data->data(format);
2253 QDataStream stream(&encoded, QDataStream::ReadOnly);
2254 return decodeData(row, column, parent, stream);
2255}
2256
2257/*!
2258 \since 4.2
2259
2260 Returns the drop actions supported by this model.
2261
2262 The default implementation returns Qt::CopyAction. Reimplement this
2263 function if you wish to support additional actions. You must also
2264 reimplement the dropMimeData() function to handle the additional
2265 operations.
2266
2267 \sa dropMimeData(), Qt::DropActions, {Using drag and drop with item
2268 views}
2269*/
2270Qt::DropActions QAbstractItemModel::supportedDropActions() const
2271{
2272 return Qt::CopyAction;
2273}
2274
2275/*!
2276 Returns the actions supported by the data in this model.
2277
2278 The default implementation returns supportedDropActions(). Reimplement
2279 this function if you wish to support additional actions.
2280
2281 supportedDragActions() is used by QAbstractItemView::startDrag() as the
2282 default values when a drag occurs.
2283
2284 \sa Qt::DropActions, {Using drag and drop with item views}
2285*/
2286Qt::DropActions QAbstractItemModel::supportedDragActions() const
2287{
2288 return supportedDropActions();
2289}
2290
2291/*!
2292 \note The base class implementation of this function does nothing and
2293 returns \c{false}.
2294
2295 On models that support this, inserts \a count rows into the model before
2296 the given \a row. Items in the new row will be children of the item
2297 represented by the \a parent model index.
2298
2299 If \a row is 0, the rows are prepended to any existing rows in the parent.
2300
2301 If \a row is rowCount(), the rows are appended to any existing rows in the
2302 parent.
2303
2304 If \a parent has no children, a single column with \a count rows is
2305 inserted.
2306
2307 Returns \c{true} if the rows were successfully inserted; otherwise returns
2308 \c{false}.
2309
2310 If you implement your own model, you can reimplement this function if you
2311 want to support insertions. Alternatively, you can provide your own API for
2312 altering the data. In either case, you will need to call
2313 beginInsertRows() and endInsertRows() to notify other components that the
2314 model has changed.
2315
2316 \sa insertColumns(), removeRows(), beginInsertRows(), endInsertRows()
2317*/
2318bool QAbstractItemModel::insertRows(int, int, const QModelIndex &)
2319{
2320 return false;
2321}
2322
2323/*!
2324 On models that support this, inserts \a count new columns into the model
2325 before the given \a column. The items in each new column will be children
2326 of the item represented by the \a parent model index.
2327
2328 If \a column is 0, the columns are prepended to any existing columns.
2329
2330 If \a column is columnCount(), the columns are appended to any existing
2331 columns.
2332
2333 If \a parent has no children, a single row with \a count columns is
2334 inserted.
2335
2336 Returns \c{true} if the columns were successfully inserted; otherwise returns
2337 \c{false}.
2338
2339 The base class implementation does nothing and returns \c{false}.
2340
2341 If you implement your own model, you can reimplement this function if you
2342 want to support insertions. Alternatively, you can provide your own API for
2343 altering the data.
2344
2345 \sa insertRows(), removeColumns(), beginInsertColumns(), endInsertColumns()
2346*/
2347bool QAbstractItemModel::insertColumns(int, int, const QModelIndex &)
2348{
2349 return false;
2350}
2351
2352/*!
2353 On models that support this, removes \a count rows starting with the given
2354 \a row under parent \a parent from the model.
2355
2356 Returns \c{true} if the rows were successfully removed; otherwise returns
2357 \c{false}.
2358
2359 The base class implementation does nothing and returns \c{false}.
2360
2361 If you implement your own model, you can reimplement this function if you
2362 want to support removing. Alternatively, you can provide your own API for
2363 altering the data.
2364
2365 \sa removeRow(), removeColumns(), insertColumns(), beginRemoveRows(),
2366 endRemoveRows()
2367*/
2368bool QAbstractItemModel::removeRows(int, int, const QModelIndex &)
2369{
2370 return false;
2371}
2372
2373/*!
2374 On models that support this, removes \a count columns starting with the
2375 given \a column under parent \a parent from the model.
2376
2377 Returns \c{true} if the columns were successfully removed; otherwise returns
2378 \c{false}.
2379
2380 The base class implementation does nothing and returns \c{false}.
2381
2382 If you implement your own model, you can reimplement this function if you
2383 want to support removing. Alternatively, you can provide your own API for
2384 altering the data.
2385
2386 \sa removeColumn(), removeRows(), insertColumns(), beginRemoveColumns(),
2387 endRemoveColumns()
2388*/
2389bool QAbstractItemModel::removeColumns(int, int, const QModelIndex &)
2390{
2391 return false;
2392}
2393
2394/*!
2395 On models that support this, moves \a count rows starting with the given
2396 \a sourceRow under parent \a sourceParent to row \a destinationChild under
2397 parent \a destinationParent.
2398
2399 Returns \c{true} if the rows were successfully moved; otherwise returns
2400 \c{false}.
2401
2402 The base class implementation does nothing and returns \c{false}.
2403
2404 If you implement your own model, you can reimplement this function if you
2405 want to support moving. Alternatively, you can provide your own API for
2406 altering the data.
2407
2408 \sa beginMoveRows(), endMoveRows()
2409*/
2410bool QAbstractItemModel::moveRows(const QModelIndex &, int , int , const QModelIndex &, int)
2411{
2412 return false;
2413}
2414
2415/*!
2416 On models that support this, moves \a count columns starting with the given
2417 \a sourceColumn under parent \a sourceParent to column \a destinationChild under
2418 parent \a destinationParent.
2419
2420 Returns \c{true} if the columns were successfully moved; otherwise returns
2421 \c{false}.
2422
2423 The base class implementation does nothing and returns \c{false}.
2424
2425 If you implement your own model, you can reimplement this function if you
2426 want to support moving. Alternatively, you can provide your own API for
2427 altering the data.
2428
2429 \sa beginMoveColumns(), endMoveColumns()
2430*/
2431bool QAbstractItemModel::moveColumns(const QModelIndex &, int , int , const QModelIndex &, int)
2432{
2433 return false;
2434}
2435
2436/*!
2437 Fetches any available data for the items with the parent specified by the
2438 \a parent index.
2439
2440 Reimplement this if you are populating your model incrementally.
2441
2442 The default implementation does nothing.
2443
2444 \sa canFetchMore()
2445*/
2446void QAbstractItemModel::fetchMore(const QModelIndex &)
2447{
2448 // do nothing
2449}
2450
2451/*!
2452 Returns \c{true} if there is more data available for \a parent; otherwise
2453 returns \c{false}.
2454
2455 The default implementation always returns \c{false}.
2456
2457 If canFetchMore() returns \c true, the fetchMore() function should
2458 be called. This is the behavior of QAbstractItemView, for example.
2459
2460 \sa fetchMore()
2461*/
2462bool QAbstractItemModel::canFetchMore(const QModelIndex &) const
2463{
2464 return false;
2465}
2466
2467/*!
2468 Returns the item flags for the given \a index.
2469
2470 The base class implementation returns a combination of flags that enables
2471 the item (\c ItemIsEnabled) and allows it to be selected
2472 (\c ItemIsSelectable).
2473
2474 \sa Qt::ItemFlags
2475*/
2476Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex &index) const
2477{
2478 Q_D(const QAbstractItemModel);
2479 if (!d->indexValid(index))
2480 return { };
2481
2482 return Qt::ItemIsSelectable|Qt::ItemIsEnabled;
2483}
2484
2485/*!
2486 Sorts the model by \a column in the given \a order.
2487
2488 The base class implementation does nothing.
2489*/
2490void QAbstractItemModel::sort(int column, Qt::SortOrder order)
2491{
2492 Q_UNUSED(column);
2493 Q_UNUSED(order);
2494 // do nothing
2495}
2496
2497/*!
2498 Returns a model index for the buddy of the item represented by \a index.
2499 When the user wants to edit an item, the view will call this function to
2500 check whether another item in the model should be edited instead. Then, the
2501 view will construct a delegate using the model index returned by the buddy
2502 item.
2503
2504 The default implementation of this function has each item as its own buddy.
2505*/
2506QModelIndex QAbstractItemModel::buddy(const QModelIndex &index) const
2507{
2508 return index;
2509}
2510
2511/*!
2512 Returns a list of indexes for the items in the column of the \a start index
2513 where data stored under the given \a role matches the specified \a value.
2514 The way the search is performed is defined by the \a flags given. The list
2515 that is returned may be empty. Note also that the order of results in the
2516 list may not correspond to the order in the model, if for example a proxy
2517 model is used. The order of the results cannot be relied upon.
2518
2519 The search begins from the \a start index, and continues until the number
2520 of matching data items equals \a hits, the search reaches the last row, or
2521 the search reaches \a start again - depending on whether \c MatchWrap is
2522 specified in \a flags. If you want to search for all matching items, use
2523 \a hits = -1.
2524
2525 By default, this function will perform a wrapping, string-based comparison
2526 on all items, searching for items that begin with the search term specified
2527 by \a value.
2528
2529 \note The default implementation of this function only searches columns.
2530 Reimplement this function to include a different search behavior.
2531*/
2532QModelIndexList QAbstractItemModel::match(const QModelIndex &start, int role,
2533 const QVariant &value, int hits,
2534 Qt::MatchFlags flags) const
2535{
2536 QModelIndexList result;
2537 uint matchType = flags & 0x0F;
2538 Qt::CaseSensitivity cs = flags & Qt::MatchCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
2539 bool recurse = flags & Qt::MatchRecursive;
2540 bool wrap = flags & Qt::MatchWrap;
2541 bool allHits = (hits == -1);
2542 QString text; // only convert to a string if it is needed
2543#if QT_CONFIG(regularexpression)
2544 QRegularExpression rx; // only create it if needed
2545#endif
2546 const int column = start.column();
2547 QModelIndex p = parent(start);
2548 int from = start.row();
2549 int to = rowCount(p);
2550
2551 // iterates twice if wrapping
2552 for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i) {
2553 for (int r = from; (r < to) && (allHits || result.count() < hits); ++r) {
2554 QModelIndex idx = index(r, column, p);
2555 if (!idx.isValid())
2556 continue;
2557 QVariant v = data(idx, role);
2558 // QVariant based matching
2559 if (matchType == Qt::MatchExactly) {
2560 if (value == v)
2561 result.append(idx);
2562 } else { // QString or regular expression based matching
2563#if QT_CONFIG(regularexpression)
2564 if (matchType == Qt::MatchRegularExpression) {
2565 if (rx.pattern().isEmpty()) {
2566 if (value.userType() == QMetaType::QRegularExpression) {
2567 rx = value.toRegularExpression();
2568 } else {
2569 rx.setPattern(value.toString());
2570 if (cs == Qt::CaseInsensitive)
2571 rx.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
2572 }
2573 }
2574 } else if (matchType == Qt::MatchWildcard) {
2575 if (rx.pattern().isEmpty())
2576 rx.setPattern(QRegularExpression::wildcardToRegularExpression(value.toString()));
2577 if (cs == Qt::CaseInsensitive)
2578 rx.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
2579 } else
2580#endif
2581 {
2582 if (text.isEmpty()) // lazy conversion
2583 text = value.toString();
2584 }
2585
2586 QString t = v.toString();
2587 switch (matchType) {
2588#if QT_CONFIG(regularexpression)
2589 case Qt::MatchRegularExpression:
2590 Q_FALLTHROUGH();
2591 case Qt::MatchWildcard:
2592 if (t.contains(rx))
2593 result.append(idx);
2594 break;
2595#endif
2596 case Qt::MatchStartsWith:
2597 if (t.startsWith(text, cs))
2598 result.append(idx);
2599 break;
2600 case Qt::MatchEndsWith:
2601 if (t.endsWith(text, cs))
2602 result.append(idx);
2603 break;
2604 case Qt::MatchFixedString:
2605 if (t.compare(text, cs) == 0)
2606 result.append(idx);
2607 break;
2608 case Qt::MatchContains:
2609 default:
2610 if (t.contains(text, cs))
2611 result.append(idx);
2612 }
2613 }
2614 if (recurse) {
2615 const auto parent = column != 0 ? idx.sibling(idx.row(), 0) : idx;
2616 if (hasChildren(parent)) { // search the hierarchy
2617 result += match(index(0, column, parent), role,
2618 (text.isEmpty() ? value : text),
2619 (allHits ? -1 : hits - result.count()), flags);
2620 }
2621 }
2622 }
2623 // prepare for the next iteration
2624 from = 0;
2625 to = start.row();
2626 }
2627 return result;
2628}
2629
2630/*!
2631 Returns the row and column span of the item represented by \a index.
2632
2633 \note Currently, span is not used.
2634*/
2635
2636QSize QAbstractItemModel::span(const QModelIndex &) const
2637{
2638 return QSize(1, 1);
2639}
2640
2641/*!
2642 \since 4.6
2643
2644 Returns the model's role names.
2645
2646 The default role names set by Qt are:
2647
2648 \table
2649 \header
2650 \li Qt Role
2651 \li QML Role Name
2652 \row
2653 \li Qt::DisplayRole
2654 \li display
2655 \row
2656 \li Qt::DecorationRole
2657 \li decoration
2658 \row
2659 \li Qt::EditRole
2660 \li edit
2661 \row
2662 \li Qt::ToolTipRole
2663 \li toolTip
2664 \row
2665 \li Qt::StatusTipRole
2666 \li statusTip
2667 \row
2668 \li Qt::WhatsThisRole
2669 \li whatsThis
2670 \endtable
2671*/
2672QHash<int,QByteArray> QAbstractItemModel::roleNames() const
2673{
2674 return QAbstractItemModelPrivate::defaultRoleNames();
2675}
2676
2677/*!
2678 Lets the model know that it should submit cached information to permanent
2679 storage. This function is typically used for row editing.
2680
2681 Returns \c{true} if there is no error; otherwise returns \c{false}.
2682
2683 \sa revert()
2684*/
2685
2686bool QAbstractItemModel::submit()
2687{
2688 return true;
2689}
2690
2691/*!
2692 Lets the model know that it should discard cached information. This
2693 function is typically used for row editing.
2694
2695 \sa submit()
2696*/
2697
2698void QAbstractItemModel::revert()
2699{
2700 // do nothing
2701}
2702
2703/*!
2704 Returns the data for the given \a role and \a section in the header with
2705 the specified \a orientation.
2706
2707 For horizontal headers, the section number corresponds to the column
2708 number. Similarly, for vertical headers, the section number corresponds to
2709 the row number.
2710
2711 \sa Qt::ItemDataRole, setHeaderData(), QHeaderView
2712*/
2713
2714QVariant QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const
2715{
2716 Q_UNUSED(orientation);
2717 if (role == Qt::DisplayRole)
2718 return section + 1;
2719 return QVariant();
2720}
2721
2722/*!
2723 Sets the data for the given \a role and \a section in the header with the
2724 specified \a orientation to the \a value supplied.
2725
2726 Returns \c{true} if the header's data was updated; otherwise returns \c{false}.
2727
2728 When reimplementing this function, the headerDataChanged() signal must be
2729 emitted explicitly.
2730
2731 \sa Qt::ItemDataRole, headerData()
2732*/
2733
2734bool QAbstractItemModel::setHeaderData(int section, Qt::Orientation orientation,
2735 const QVariant &value, int role)
2736{
2737 Q_UNUSED(section);
2738 Q_UNUSED(orientation);
2739 Q_UNUSED(value);
2740 Q_UNUSED(role);
2741 return false;
2742}
2743
2744/*!
2745 \fn QModelIndex QAbstractItemModel::createIndex(int row, int column, const void *ptr) const
2746
2747 Creates a model index for the given \a row and \a column with the internal
2748 pointer \a ptr.
2749
2750 When using a QSortFilterProxyModel, its indexes have their own internal
2751 pointer. It is not advisable to access this internal pointer outside of the
2752 model. Use the data() function instead.
2753
2754 This function provides a consistent interface that model subclasses must
2755 use to create model indexes.
2756*/
2757
2758/*!
2759 \fn QModelIndex QAbstractItemModel::createIndex(int row, int column, quintptr id) const
2760
2761 Creates a model index for the given \a row and \a column with the internal
2762 identifier, \a id.
2763
2764 This function provides a consistent interface that model subclasses must
2765 use to create model indexes.
2766
2767 \sa QModelIndex::internalId()
2768*/
2769
2770/*!
2771 \internal
2772*/
2773void QAbstractItemModel::encodeData(const QModelIndexList &indexes, QDataStream &stream) const
2774{
2775 for (const auto &index : indexes)
2776 stream << index.row() << index.column() << itemData(index);
2777}
2778
2779/*!
2780 \internal
2781 */
2782bool QAbstractItemModel::decodeData(int row, int column, const QModelIndex &parent,
2783 QDataStream &stream)
2784{
2785 int top = INT_MAX;
2786 int left = INT_MAX;
2787 int bottom = 0;
2788 int right = 0;
2789 QList<int> rows, columns;
2790 QList<QMap<int, QVariant>> data;
2791
2792 while (!stream.atEnd()) {
2793 int r, c;
2794 QMap<int, QVariant> v;
2795 stream >> r >> c >> v;
2796 rows.append(r);
2797 columns.append(c);
2798 data.append(v);
2799 top = qMin(r, top);
2800 left = qMin(c, left);
2801 bottom = qMax(r, bottom);
2802 right = qMax(c, right);
2803 }
2804
2805 // insert the dragged items into the table, use a bit array to avoid overwriting items,
2806 // since items from different tables can have the same row and column
2807 int dragRowCount = 0;
2808 int dragColumnCount = right - left + 1;
2809
2810 // Compute the number of continuous rows upon insertion and modify the rows to match
2811 QList<int> rowsToInsert(bottom + 1);
2812 for (int i = 0; i < rows.count(); ++i)
2813 rowsToInsert[rows.at(i)] = 1;
2814 for (int i = 0; i < rowsToInsert.count(); ++i) {
2815 if (rowsToInsert.at(i) == 1){
2816 rowsToInsert[i] = dragRowCount;
2817 ++dragRowCount;
2818 }
2819 }
2820 for (int i = 0; i < rows.count(); ++i)
2821 rows[i] = top + rowsToInsert.at(rows.at(i));
2822
2823 QBitArray isWrittenTo(dragRowCount * dragColumnCount);
2824
2825 // make space in the table for the dropped data
2826 int colCount = columnCount(parent);
2827 if (colCount == 0) {
2828 insertColumns(colCount, dragColumnCount - colCount, parent);
2829 colCount = columnCount(parent);
2830 }
2831 insertRows(row, dragRowCount, parent);
2832
2833 row = qMax(0, row);
2834 column = qMax(0, column);
2835
2836 QList<QPersistentModelIndex> newIndexes(data.size());
2837 // set the data in the table
2838 for (int j = 0; j < data.size(); ++j) {
2839 int relativeRow = rows.at(j) - top;
2840 int relativeColumn = columns.at(j) - left;
2841 int destinationRow = relativeRow + row;
2842 int destinationColumn = relativeColumn + column;
2843 int flat = (relativeRow * dragColumnCount) + relativeColumn;
2844 // if the item was already written to, or we just can't fit it in the table, create a new row
2845 if (destinationColumn >= colCount || isWrittenTo.testBit(flat)) {
2846 destinationColumn = qBound(column, destinationColumn, colCount - 1);
2847 destinationRow = row + dragRowCount;
2848 insertRows(row + dragRowCount, 1, parent);
2849 flat = (dragRowCount * dragColumnCount) + relativeColumn;
2850 isWrittenTo.resize(++dragRowCount * dragColumnCount);
2851 }
2852 if (!isWrittenTo.testBit(flat)) {
2853 newIndexes[j] = index(destinationRow, destinationColumn, parent);
2854 isWrittenTo.setBit(flat);
2855 }
2856 }
2857
2858 for(int k = 0; k < newIndexes.size(); k++) {
2859 if (newIndexes.at(k).isValid())
2860 setItemData(newIndexes.at(k), data.at(k));
2861 }
2862
2863 return true;
2864}
2865
2866/*!
2867 Begins a row insertion operation.
2868
2869 When reimplementing insertRows() in a subclass, you must call this function
2870 \e before inserting data into the model's underlying data store.
2871
2872 The \a parent index corresponds to the parent into which the new rows are
2873 inserted; \a first and \a last are the row numbers that the new rows will
2874 have after they have been inserted.
2875
2876 \table 80%
2877 \row
2878 \li \inlineimage modelview-begin-insert-rows.png Inserting rows
2879 \li Specify the first and last row numbers for the span of rows you
2880 want to insert into an item in a model.
2881
2882 For example, as shown in the diagram, we insert three rows before
2883 row 2, so \a first is 2 and \a last is 4:
2884
2885 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 0
2886
2887 This inserts the three new rows as rows 2, 3, and 4.
2888 \row
2889 \li \inlineimage modelview-begin-append-rows.png Appending rows
2890 \li To append rows, insert them after the last row.
2891
2892 For example, as shown in the diagram, we append two rows to a
2893 collection of 4 existing rows (ending in row 3), so \a first is 4
2894 and \a last is 5:
2895
2896 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 1
2897
2898 This appends the two new rows as rows 4 and 5.
2899 \endtable
2900
2901 \note This function emits the rowsAboutToBeInserted() signal which
2902 connected views (or proxies) must handle before the data is inserted.
2903 Otherwise, the views may end up in an invalid state.
2904 \sa endInsertRows()
2905*/
2906void QAbstractItemModel::beginInsertRows(const QModelIndex &parent, int first, int last)
2907{
2908 Q_ASSERT(first >= 0);
2909 Q_ASSERT(first <= rowCount(parent)); // == is allowed, to insert at the end
2910 Q_ASSERT(last >= first);
2911 Q_D(QAbstractItemModel);
2912 d->changes.push(QAbstractItemModelPrivate::Change(parent, first, last));
2913 emit rowsAboutToBeInserted(parent, first, last, QPrivateSignal());
2914 d->rowsAboutToBeInserted(parent, first, last);
2915}
2916
2917/*!
2918 Ends a row insertion operation.
2919
2920 When reimplementing insertRows() in a subclass, you must call this function
2921 \e after inserting data into the model's underlying data store.
2922
2923 \sa beginInsertRows()
2924*/
2925void QAbstractItemModel::endInsertRows()
2926{
2927 Q_D(QAbstractItemModel);
2928 QAbstractItemModelPrivate::Change change = d->changes.pop();
2929 d->rowsInserted(change.parent, change.first, change.last);
2930 emit rowsInserted(change.parent, change.first, change.last, QPrivateSignal());
2931}
2932
2933/*!
2934 Begins a row removal operation.
2935
2936 When reimplementing removeRows() in a subclass, you must call this
2937 function \e before removing data from the model's underlying data store.
2938
2939 The \a parent index corresponds to the parent from which the new rows are
2940 removed; \a first and \a last are the row numbers of the rows to be
2941 removed.
2942
2943 \table 80%
2944 \row
2945 \li \inlineimage modelview-begin-remove-rows.png Removing rows
2946 \li Specify the first and last row numbers for the span of rows you
2947 want to remove from an item in a model.
2948
2949 For example, as shown in the diagram, we remove the two rows from
2950 row 2 to row 3, so \a first is 2 and \a last is 3:
2951
2952 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 2
2953 \endtable
2954
2955 \note This function emits the rowsAboutToBeRemoved() signal which connected
2956 views (or proxies) must handle before the data is removed. Otherwise, the
2957 views may end up in an invalid state.
2958
2959 \sa endRemoveRows()
2960*/
2961void QAbstractItemModel::beginRemoveRows(const QModelIndex &parent, int first, int last)
2962{
2963 Q_ASSERT(first >= 0);
2964 Q_ASSERT(last >= first);
2965 Q_ASSERT(last < rowCount(parent));
2966 Q_D(QAbstractItemModel);
2967 d->changes.push(QAbstractItemModelPrivate::Change(parent, first, last));
2968 emit rowsAboutToBeRemoved(parent, first, last, QPrivateSignal());
2969 d->rowsAboutToBeRemoved(parent, first, last);
2970}
2971
2972/*!
2973 Ends a row removal operation.
2974
2975 When reimplementing removeRows() in a subclass, you must call this function
2976 \e after removing data from the model's underlying data store.
2977
2978 \sa beginRemoveRows()
2979*/
2980void QAbstractItemModel::endRemoveRows()
2981{
2982 Q_D(QAbstractItemModel);
2983 QAbstractItemModelPrivate::Change change = d->changes.pop();
2984 d->rowsRemoved(change.parent, change.first, change.last);
2985 emit rowsRemoved(change.parent, change.first, change.last, QPrivateSignal());
2986}
2987
2988/*!
2989 Returns whether a move operation is valid.
2990
2991 A move operation is not allowed if it moves a continuous range of rows to a destination within
2992 itself, or if it attempts to move a row to one of its own descendants.
2993
2994 \internal
2995*/
2996bool QAbstractItemModelPrivate::allowMove(const QModelIndex &srcParent, int start, int end, const QModelIndex &destinationParent, int destinationStart, Qt::Orientation orientation)
2997{
2998 // Don't move the range within itself.
2999 if (destinationParent == srcParent)
3000 return !(destinationStart >= start && destinationStart <= end + 1);
3001
3002 QModelIndex destinationAncestor = destinationParent;
3003 int pos = (Qt::Vertical == orientation) ? destinationAncestor.row() : destinationAncestor.column();
3004 forever {
3005 if (destinationAncestor == srcParent) {
3006 if (pos >= start && pos <= end)
3007 return false;
3008 break;
3009 }
3010
3011 if (!destinationAncestor.isValid())
3012 break;
3013
3014 pos = (Qt::Vertical == orientation) ? destinationAncestor.row() : destinationAncestor.column();
3015 destinationAncestor = destinationAncestor.parent();
3016 }
3017
3018 return true;
3019}
3020
3021/*!
3022 \since 4.6
3023
3024 Begins a row move operation.
3025
3026 When reimplementing a subclass, this method simplifies moving
3027 entities in your model. This method is responsible for moving
3028 persistent indexes in the model, which you would otherwise be
3029 required to do yourself. Using beginMoveRows and endMoveRows
3030 is an alternative to emitting layoutAboutToBeChanged and
3031 layoutChanged directly along with changePersistentIndex.
3032
3033 The \a sourceParent index corresponds to the parent from which the
3034 rows are moved; \a sourceFirst and \a sourceLast are the first and last
3035 row numbers of the rows to be moved. The \a destinationParent index
3036 corresponds to the parent into which those rows are moved. The \a
3037 destinationChild is the row to which the rows will be moved. That
3038 is, the index at row \a sourceFirst in \a sourceParent will become
3039 row \a destinationChild in \a destinationParent, followed by all other
3040 rows up to \a sourceLast.
3041
3042 However, when moving rows down in the same parent (\a sourceParent
3043 and \a destinationParent are equal), the rows will be placed before the
3044 \a destinationChild index. That is, if you wish to move rows 0 and 1 so
3045 they will become rows 1 and 2, \a destinationChild should be 3. In this
3046 case, the new index for the source row \c i (which is between
3047 \a sourceFirst and \a sourceLast) is equal to
3048 \c {(destinationChild-sourceLast-1+i)}.
3049
3050 Note that if \a sourceParent and \a destinationParent are the same,
3051 you must ensure that the \a destinationChild is not within the range
3052 of \a sourceFirst and \a sourceLast + 1. You must also ensure that you
3053 do not attempt to move a row to one of its own children or ancestors.
3054 This method returns \c{false} if either condition is true, in which case you
3055 should abort your move operation.
3056
3057 \table 80%
3058 \row
3059 \li \inlineimage modelview-move-rows-1.png Moving rows to another parent
3060 \li Specify the first and last row numbers for the span of rows in
3061 the source parent you want to move in the model. Also specify
3062 the row in the destination parent to move the span to.
3063
3064 For example, as shown in the diagram, we move three rows from
3065 row 2 to 4 in the source, so \a sourceFirst is 2 and \a sourceLast is 4.
3066 We move those items to above row 2 in the destination, so \a destinationChild is 2.
3067
3068 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 6
3069
3070 This moves the three rows rows 2, 3, and 4 in the source to become 2, 3 and 4 in
3071 the destination. Other affected siblings are displaced accordingly.
3072 \row
3073 \li \inlineimage modelview-move-rows-2.png Moving rows to append to another parent
3074 \li To append rows to another parent, move them to after the last row.
3075
3076 For example, as shown in the diagram, we move three rows to a
3077 collection of 6 existing rows (ending in row 5), so \a destinationChild is 6:
3078
3079 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 7
3080
3081 This moves the target rows to the end of the target parent as 6, 7 and 8.
3082 \row
3083 \li \inlineimage modelview-move-rows-3.png Moving rows in the same parent up
3084 \li To move rows within the same parent, specify the row to move them to.
3085
3086 For example, as shown in the diagram, we move one item from row 2 to row 0,
3087 so \a sourceFirst and \a sourceLast are 2 and \a destinationChild is 0.
3088
3089 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 8
3090
3091 Note that other rows may be displaced accordingly. Note also that when moving
3092 items within the same parent you should not attempt invalid or no-op moves. In
3093 the above example, item 2 is at row 2 before the move, so it cannot be moved
3094 to row 2 (where it is already) or row 3 (no-op as row 3 means above row 3, where
3095 it is already)
3096
3097 \row
3098 \li \inlineimage modelview-move-rows-4.png Moving rows in the same parent down
3099 \li To move rows within the same parent, specify the row to move them to.
3100
3101 For example, as shown in the diagram, we move one item from row 2 to row 4,
3102 so \a sourceFirst and \a sourceLast are 2 and \a destinationChild is 4.
3103
3104 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 9
3105
3106 Note that other rows may be displaced accordingly.
3107 \endtable
3108
3109 \sa endMoveRows()
3110*/
3111bool QAbstractItemModel::beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)
3112{
3113 Q_ASSERT(sourceFirst >= 0);
3114 Q_ASSERT(sourceLast >= sourceFirst);
3115 Q_ASSERT(destinationChild >= 0);
3116 Q_D(QAbstractItemModel);
3117
3118 if (!d->allowMove(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, Qt::Vertical)) {
3119 return false;
3120 }
3121
3122 QAbstractItemModelPrivate::Change sourceChange(sourceParent, sourceFirst, sourceLast);
3123 sourceChange.needsAdjust = sourceParent.isValid() && sourceParent.row() >= destinationChild && sourceParent.parent() == destinationParent;
3124 d->changes.push(sourceChange);
3125 int destinationLast = destinationChild + (sourceLast - sourceFirst);
3126 QAbstractItemModelPrivate::Change destinationChange(destinationParent, destinationChild, destinationLast);
3127 destinationChange.needsAdjust = destinationParent.isValid() && destinationParent.row() >= sourceLast && destinationParent.parent() == sourceParent;
3128 d->changes.push(destinationChange);
3129
3130 emit rowsAboutToBeMoved(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, QPrivateSignal());
3131 d->itemsAboutToBeMoved(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, Qt::Vertical);
3132 return true;
3133}
3134
3135/*!
3136 Ends a row move operation.
3137
3138 When implementing a subclass, you must call this
3139 function \e after moving data within the model's underlying data
3140 store.
3141
3142 \sa beginMoveRows()
3143
3144 \since 4.6
3145*/
3146void QAbstractItemModel::endMoveRows()
3147{
3148 Q_D(QAbstractItemModel);
3149
3150 QAbstractItemModelPrivate::Change insertChange = d->changes.pop();
3151 QAbstractItemModelPrivate::Change removeChange = d->changes.pop();
3152
3153 QModelIndex adjustedSource = removeChange.parent;
3154 QModelIndex adjustedDestination = insertChange.parent;
3155
3156 const int numMoved = removeChange.last - removeChange.first + 1;
3157 if (insertChange.needsAdjust)
3158 adjustedDestination = createIndex(adjustedDestination.row() - numMoved, adjustedDestination.column(), adjustedDestination.internalPointer());
3159
3160 if (removeChange.needsAdjust)
3161 adjustedSource = createIndex(adjustedSource.row() + numMoved, adjustedSource.column(), adjustedSource.internalPointer());
3162
3163 d->itemsMoved(adjustedSource, removeChange.first, removeChange.last, adjustedDestination, insertChange.first, Qt::Vertical);
3164
3165 emit rowsMoved(adjustedSource, removeChange.first, removeChange.last, adjustedDestination, insertChange.first, QPrivateSignal());
3166}
3167
3168/*!
3169 Begins a column insertion operation.
3170
3171 When reimplementing insertColumns() in a subclass, you must call this
3172 function \e before inserting data into the model's underlying data store.
3173
3174 The \a parent index corresponds to the parent into which the new columns
3175 are inserted; \a first and \a last are the column numbers of the new
3176 columns will have after they have been inserted.
3177
3178 \table 80%
3179 \row
3180 \li \inlineimage modelview-begin-insert-columns.png Inserting columns
3181 \li Specify the first and last column numbers for the span of columns
3182 you want to insert into an item in a model.
3183
3184 For example, as shown in the diagram, we insert three columns
3185 before column 4, so \a first is 4 and \a last is 6:
3186
3187 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 3
3188
3189 This inserts the three new columns as columns 4, 5, and 6.
3190 \row
3191 \li \inlineimage modelview-begin-append-columns.png Appending columns
3192 \li To append columns, insert them after the last column.
3193
3194 For example, as shown in the diagram, we append three columns to a
3195 collection of six existing columns (ending in column 5), so
3196 \a first is 6 and \a last is 8:
3197
3198 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 4
3199
3200 This appends the two new columns as columns 6, 7, and 8.
3201 \endtable
3202
3203 \note This function emits the columnsAboutToBeInserted() signal which
3204 connected views (or proxies) must handle before the data is inserted.
3205 Otherwise, the views may end up in an invalid state.
3206
3207 \sa endInsertColumns()
3208*/
3209void QAbstractItemModel::beginInsertColumns(const QModelIndex &parent, int first, int last)
3210{
3211 Q_ASSERT(first >= 0);
3212 Q_ASSERT(first <= columnCount(parent)); // == is allowed, to insert at the end
3213 Q_ASSERT(last >= first);
3214 Q_D(QAbstractItemModel);
3215 d->changes.push(QAbstractItemModelPrivate::Change(parent, first, last));
3216 emit columnsAboutToBeInserted(parent, first, last, QPrivateSignal());
3217 d->columnsAboutToBeInserted(parent, first, last);
3218}
3219
3220/*!
3221 Ends a column insertion operation.
3222
3223 When reimplementing insertColumns() in a subclass, you must call this
3224 function \e after inserting data into the model's underlying data
3225 store.
3226
3227 \sa beginInsertColumns()
3228*/
3229void QAbstractItemModel::endInsertColumns()
3230{
3231 Q_D(QAbstractItemModel);
3232 QAbstractItemModelPrivate::Change change = d->changes.pop();
3233 d->columnsInserted(change.parent, change.first, change.last);
3234 emit columnsInserted(change.parent, change.first, change.last, QPrivateSignal());
3235}
3236
3237/*!
3238 Begins a column removal operation.
3239
3240 When reimplementing removeColumns() in a subclass, you must call this
3241 function \e before removing data from the model's underlying data store.
3242
3243 The \a parent index corresponds to the parent from which the new columns
3244 are removed; \a first and \a last are the column numbers of the first and
3245 last columns to be removed.
3246
3247 \table 80%
3248 \row
3249 \li \inlineimage modelview-begin-remove-columns.png Removing columns
3250 \li Specify the first and last column numbers for the span of columns
3251 you want to remove from an item in a model.
3252
3253 For example, as shown in the diagram, we remove the three columns
3254 from column 4 to column 6, so \a first is 4 and \a last is 6:
3255
3256 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 5
3257 \endtable
3258
3259 \note This function emits the columnsAboutToBeRemoved() signal which
3260 connected views (or proxies) must handle before the data is removed.
3261 Otherwise, the views may end up in an invalid state.
3262
3263 \sa endRemoveColumns()
3264*/
3265void QAbstractItemModel::beginRemoveColumns(const QModelIndex &parent, int first, int last)
3266{
3267 Q_ASSERT(first >= 0);
3268 Q_ASSERT(last >= first);
3269 Q_ASSERT(last < columnCount(parent));
3270 Q_D(QAbstractItemModel);
3271 d->changes.push(QAbstractItemModelPrivate::Change(parent, first, last));
3272 emit columnsAboutToBeRemoved(parent, first, last, QPrivateSignal());
3273 d->columnsAboutToBeRemoved(parent, first, last);
3274}
3275
3276/*!
3277 Ends a column removal operation.
3278
3279 When reimplementing removeColumns() in a subclass, you must call this
3280 function \e after removing data from the model's underlying data store.
3281
3282 \sa beginRemoveColumns()
3283*/
3284void QAbstractItemModel::endRemoveColumns()
3285{
3286 Q_D(QAbstractItemModel);
3287 QAbstractItemModelPrivate::Change change = d->changes.pop();
3288 d->columnsRemoved(change.parent, change.first, change.last);
3289 emit columnsRemoved(change.parent, change.first, change.last, QPrivateSignal());
3290}
3291
3292/*!
3293 Begins a column move operation.
3294
3295 When reimplementing a subclass, this method simplifies moving
3296 entities in your model. This method is responsible for moving
3297 persistent indexes in the model, which you would otherwise be
3298 required to do yourself. Using beginMoveColumns and endMoveColumns
3299 is an alternative to emitting layoutAboutToBeChanged and
3300 layoutChanged directly along with changePersistentIndex.
3301
3302 The \a sourceParent index corresponds to the parent from which the
3303 columns are moved; \a sourceFirst and \a sourceLast are the first and last
3304 column numbers of the columns to be moved. The \a destinationParent index
3305 corresponds to the parent into which those columns are moved. The \a
3306 destinationChild is the column to which the columns will be moved. That
3307 is, the index at column \a sourceFirst in \a sourceParent will become
3308 column \a destinationChild in \a destinationParent, followed by all other
3309 columns up to \a sourceLast.
3310
3311 However, when moving columns down in the same parent (\a sourceParent
3312 and \a destinationParent are equal), the columns will be placed before the
3313 \a destinationChild index. That is, if you wish to move columns 0 and 1 so
3314 they will become columns 1 and 2, \a destinationChild should be 3. In this
3315 case, the new index for the source column \c i (which is between
3316 \a sourceFirst and \a sourceLast) is equal to
3317 \c {(destinationChild-sourceLast-1+i)}.
3318
3319 Note that if \a sourceParent and \a destinationParent are the same,
3320 you must ensure that the \a destinationChild is not within the range
3321 of \a sourceFirst and \a sourceLast + 1. You must also ensure that you
3322 do not attempt to move a column to one of its own children or ancestors.
3323 This method returns \c{false} if either condition is true, in which case you
3324 should abort your move operation.
3325
3326 \sa endMoveColumns()
3327
3328 \since 4.6
3329*/
3330bool QAbstractItemModel::beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destinationParent, int destinationChild)
3331{
3332 Q_ASSERT(sourceFirst >= 0);
3333 Q_ASSERT(sourceLast >= sourceFirst);
3334 Q_ASSERT(destinationChild >= 0);
3335 Q_D(QAbstractItemModel);
3336
3337 if (!d->allowMove(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, Qt::Horizontal)) {
3338 return false;
3339 }
3340
3341 QAbstractItemModelPrivate::Change sourceChange(sourceParent, sourceFirst, sourceLast);
3342 sourceChange.needsAdjust = sourceParent.isValid() && sourceParent.row() >= destinationChild && sourceParent.parent() == destinationParent;
3343 d->changes.push(sourceChange);
3344 int destinationLast = destinationChild + (sourceLast - sourceFirst);
3345 QAbstractItemModelPrivate::Change destinationChange(destinationParent, destinationChild, destinationLast);
3346 destinationChange.needsAdjust = destinationParent.isValid() && destinationParent.row() >= sourceLast && destinationParent.parent() == sourceParent;
3347 d->changes.push(destinationChange);
3348
3349 d->itemsAboutToBeMoved(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, Qt::Horizontal);
3350
3351 emit columnsAboutToBeMoved(sourceParent, sourceFirst, sourceLast, destinationParent, destinationChild, QPrivateSignal());
3352 return true;
3353}
3354
3355/*!
3356 Ends a column move operation.
3357
3358 When implementing a subclass, you must call this
3359 function \e after moving data within the model's underlying data
3360 store.
3361
3362 \sa beginMoveColumns()
3363
3364 \since 4.6
3365*/
3366void QAbstractItemModel::endMoveColumns()
3367{
3368 Q_D(QAbstractItemModel);
3369
3370 QAbstractItemModelPrivate::Change insertChange = d->changes.pop();
3371 QAbstractItemModelPrivate::Change removeChange = d->changes.pop();
3372
3373 QModelIndex adjustedSource = removeChange.parent;
3374 QModelIndex adjustedDestination = insertChange.parent;
3375
3376 const int numMoved = removeChange.last - removeChange.first + 1;
3377 if (insertChange.needsAdjust)
3378 adjustedDestination = createIndex(adjustedDestination.row(), adjustedDestination.column() - numMoved, adjustedDestination.internalPointer());
3379
3380 if (removeChange.needsAdjust)
3381 adjustedSource = createIndex(adjustedSource.row(), adjustedSource.column() + numMoved, adjustedSource.internalPointer());
3382
3383 d->itemsMoved(adjustedSource, removeChange.first, removeChange.last, adjustedDestination, insertChange.first, Qt::Horizontal);
3384
3385 emit columnsMoved(adjustedSource, removeChange.first, removeChange.last, adjustedDestination, insertChange.first, QPrivateSignal());
3386}
3387
3388/*!
3389 Begins a model reset operation.
3390
3391 A reset operation resets the model to its current state in any attached views.
3392
3393 \note Any views attached to this model will be reset as well.
3394
3395 When a model is reset it means that any previous data reported from the
3396 model is now invalid and has to be queried for again. This also means that
3397 the current item and any selected items will become invalid.
3398
3399 When a model radically changes its data it can sometimes be easier to just
3400 call this function rather than emit dataChanged() to inform other
3401 components when the underlying data source, or its structure, has changed.
3402
3403 You must call this function before resetting any internal data structures in your model
3404 or proxy model.
3405
3406 This function emits the signal modelAboutToBeReset().
3407
3408 \sa modelAboutToBeReset(), modelReset(), endResetModel()
3409 \since 4.6
3410*/
3411void QAbstractItemModel::beginResetModel()
3412{
3413 emit modelAboutToBeReset(QPrivateSignal());
3414}
3415
3416/*!
3417 Completes a model reset operation.
3418
3419 You must call this function after resetting any internal data structure in your model
3420 or proxy model.
3421
3422 This function emits the signal modelReset().
3423
3424 \sa beginResetModel()
3425 \since 4.6
3426*/
3427void QAbstractItemModel::endResetModel()
3428{
3429 Q_D(QAbstractItemModel);
3430 d->invalidatePersistentIndexes();
3431 resetInternalData();
3432 emit modelReset(QPrivateSignal());
3433}
3434
3435/*!
3436 Changes the QPersistentModelIndex that is equal to the given \a from model
3437 index to the given \a to model index.
3438
3439 If no persistent model index equal to the given \a from model index was
3440 found, nothing is changed.
3441
3442 \sa persistentIndexList(), changePersistentIndexList()
3443*/
3444void QAbstractItemModel::changePersistentIndex(const QModelIndex &from, const QModelIndex &to)
3445{
3446 Q_D(QAbstractItemModel);
3447 if (d->persistent.indexes.isEmpty())
3448 return;
3449 // find the data and reinsert it sorted
3450 const auto it = d->persistent.indexes.constFind(from);
3451 if (it != d->persistent.indexes.cend()) {
3452 QPersistentModelIndexData *data = *it;
3453 d->persistent.indexes.erase(it);
3454 data->index = to;
3455 if (to.isValid())
3456 d->persistent.insertMultiAtEnd(to, data);
3457 }
3458}
3459
3460/*!
3461 \since 4.1
3462
3463 Changes the {QPersistentModelIndex}es that are equal to the indexes in the
3464 given \a from model index list to the given \a to model index list.
3465
3466 If no persistent model indexes equal to the indexes in the given \a from
3467 model index list are found, nothing is changed.
3468
3469 \sa persistentIndexList(), changePersistentIndex()
3470*/
3471void QAbstractItemModel::changePersistentIndexList(const QModelIndexList &from,
3472 const QModelIndexList &to)
3473{
3474 Q_D(QAbstractItemModel);
3475 if (d->persistent.indexes.isEmpty())
3476 return;
3477 QList<QPersistentModelIndexData *> toBeReinserted;
3478 toBeReinserted.reserve(to.count());
3479 for (int i = 0; i < from.count(); ++i) {
3480 if (from.at(i) == to.at(i))
3481 continue;
3482 const auto it = d->persistent.indexes.constFind(from.at(i));
3483 if (it != d->persistent.indexes.cend()) {
3484 QPersistentModelIndexData *data = *it;
3485 d->persistent.indexes.erase(it);
3486 data->index = to.at(i);
3487 if (data->index.isValid())
3488 toBeReinserted << data;
3489 }
3490 }
3491
3492 for (auto *data : qAsConst(toBeReinserted))
3493 d->persistent.insertMultiAtEnd(data->index, data);
3494}
3495
3496/*!
3497 \since 4.2
3498
3499 Returns the list of indexes stored as persistent indexes in the model.
3500*/
3501QModelIndexList QAbstractItemModel::persistentIndexList() const
3502{
3503 Q_D(const QAbstractItemModel);
3504 QModelIndexList result;
3505 result.reserve(d->persistent.indexes.count());
3506 for (auto *data : qAsConst(d->persistent.indexes))
3507 result.append(data->index);
3508 return result;
3509}
3510
3511/*!
3512 \enum QAbstractItemModel::CheckIndexOption
3513 \since 5.11
3514
3515 This enum can be used to control the checks performed by
3516 QAbstractItemModel::checkIndex().
3517
3518 \value NoOption No check options are specified.
3519
3520 \value IndexIsValid The model index passed to
3521 QAbstractItemModel::checkIndex() is checked to be a valid model index.
3522
3523 \value DoNotUseParent Does not perform any check
3524 involving the usage of the parent of the index passed to
3525 QAbstractItemModel::checkIndex().
3526
3527 \value ParentIsInvalid The parent of the model index
3528 passed to QAbstractItemModel::checkIndex() is checked to be an invalid
3529 model index. If both this option and DoNotUseParent
3530 are specified, then this option is ignored.
3531*/
3532
3533/*!
3534 \since 5.11
3535
3536 This function checks whether \a index is a legal model index for
3537 this model. A legal model index is either an invalid model index, or a
3538 valid model index for which all the following holds:
3539
3540 \list
3541
3542 \li the index' model is \c{this};
3543 \li the index' row is greater or equal than zero;
3544 \li the index' row is less than the row count for the index' parent;
3545 \li the index' column is greater or equal than zero;
3546 \li the index' column is less than the column count for the index' parent.
3547
3548 \endlist
3549
3550 The \a options argument may change some of these checks. If \a options
3551 contains \c{IndexIsValid}, then \a index must be a valid
3552 index; this is useful when reimplementing functions such as \l{data()} or
3553 \l{setData()}, which expect valid indexes.
3554
3555 If \a options contains \c{DoNotUseParent}, then the
3556 checks that would call \l{parent()} are omitted; this allows calling this
3557 function from a \l{parent()} reimplementation (otherwise, this would result
3558 in endless recursion and a crash).
3559
3560 If \a options does not contain \c{DoNotUseParent}, and it
3561 contains \c{ParentIsInvalid}, then an additional check is
3562 performed: the parent index is checked for not being valid. This is useful
3563 when implementing flat models such as lists or tables, where no model index
3564 should have a valid parent index.
3565
3566 This function returns true if all the checks succeeded, and false otherwise.
3567 This allows to use the function in \l{Q_ASSERT} and similar other debugging
3568 mechanisms. If some check failed, a warning message will be printed in the
3569 \c{qt.core.qabstractitemmodel.checkindex} logging category, containing
3570 some information that may be useful for debugging the failure.
3571
3572 \note This function is a debugging helper for implementing your own item
3573 models. When developing complex models, as well as when building
3574 complicated model hierarchies (e.g. using proxy models), it is useful to
3575 call this function in order to catch bugs relative to illegal model indices
3576 (as defined above) accidentally passed to some QAbstractItemModel API.
3577
3578 \warning Note that it's undefined behavior to pass illegal indices to item
3579 models, so applications must refrain from doing so, and not rely on any
3580 "defensive" programming that item models could employ to handle illegal
3581 indexes gracefully.
3582
3583 \sa QModelIndex
3584*/
3585bool QAbstractItemModel::checkIndex(const QModelIndex &index, CheckIndexOptions options) const
3586{
3587 if (!index.isValid()) {
3588 if (options & CheckIndexOption::IndexIsValid) {
3589 qCWarning(lcCheckIndex) << "Index" << index << "is not valid (expected valid)";
3590 return false;
3591 }
3592 return true;
3593 }
3594
3595 if (index.model() != this) {
3596 qCWarning(lcCheckIndex) << "Index" << index
3597 << "is for model" << index.model()
3598 << "which is different from this model" << this;
3599 return false;
3600 }
3601
3602 if (index.row() < 0) {
3603 qCWarning(lcCheckIndex) << "Index" << index
3604 << "has negative row" << index.row();
3605 return false;
3606 }
3607
3608 if (index.column() < 0) {
3609 qCWarning(lcCheckIndex) << "Index" << index
3610 << "has negative column" << index.column();
3611 return false;
3612 }
3613
3614 if (!(options & CheckIndexOption::DoNotUseParent)) {
3615 const QModelIndex parentIndex = index.parent();
3616 if (options & CheckIndexOption::ParentIsInvalid) {
3617 if (parentIndex.isValid()) {
3618 qCWarning(lcCheckIndex) << "Index" << index
3619 << "has valid parent" << parentIndex
3620 << "(expected an invalid parent)";
3621 return false;
3622 }
3623 }
3624
3625 const int rc = rowCount(parentIndex);
3626 if (index.row() >= rc) {
3627 qCWarning(lcCheckIndex) << "Index" << index
3628 << "has out of range row" << index.row()
3629 << "rowCount() is" << rc;
3630 return false;
3631 }
3632
3633 const int cc = columnCount(parentIndex);
3634 if (index.column() >= cc) {
3635 qCWarning(lcCheckIndex) << "Index" << index
3636 << "has out of range column" << index.column()
3637 << "columnCount() is" << cc;
3638 return false;
3639
3640 }
3641 }
3642
3643 return true;
3644}
3645
3646/*!
3647 \since 6.0
3648
3649 Fills the \a roleDataSpan with the requested data for the given \a index.
3650
3651 The default implementation will call simply data() for each role in
3652 the span. A subclass can reimplement this function to provide data
3653 to views more efficiently:
3654
3655 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 15
3656
3657 In the snippet above, \c{index} is the same for the entire call.
3658 This means that accessing to the necessary data structures in order
3659 to retrieve the information for \c{index} can be done only once
3660 (hoisting the relevant code out of the loop).
3661
3662 The usage of QModelRoleData::setData(), or similarly
3663 QVariant::setValue(), is encouraged over constructing a QVariant
3664 separately and using a plain assignment operator; this is
3665 because the former allow to re-use the memory already allocated for
3666 the QVariant object stored inside a QModelRoleData, while the latter
3667 always allocates the new variant and then destroys the old one.
3668
3669 Note that views may call multiData() with spans that have been used
3670 in previous calls, and therefore may already contain some data.
3671 Therefore, it is imperative that if the model cannot return the
3672 data for a given role, then it must clear the data in the
3673 corresponding QModelRoleData object. This can be done by calling
3674 QModelRoleData::clearData(), or similarly by setting a default
3675 constructed QVariant, and so on. Failure to clear the data will
3676 result in the view believing that the "old" data is meant to be
3677 used for the corresponding role.
3678
3679 Finally, in order to avoid code duplication, a subclass may also
3680 decide to reimplement data() in terms of multiData(), by supplying
3681 a span of just one element:
3682
3683 \snippet code/src_corelib_kernel_qabstractitemmodel.cpp 16
3684
3685 \note Models are not allowed to modify the roles in the span, or
3686 to rearrange the span elements. Doing so results in undefined
3687 behavior.
3688
3689 \note It is illegal to pass an invalid model index to this function.
3690
3691 \sa QModelRoleDataSpan, data()
3692*/
3693void QAbstractItemModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
3694{
3695 Q_ASSERT(checkIndex(index, CheckIndexOption::IndexIsValid));
3696
3697 for (QModelRoleData &d : roleDataSpan)
3698 d.setData(data(index, d.role()));
3699}
3700
3701/*!
3702 \class QAbstractTableModel
3703 \inmodule QtCore
3704 \brief The QAbstractTableModel class provides an abstract model that can be
3705 subclassed to create table models.
3706
3707 \ingroup model-view
3708
3709 QAbstractTableModel provides a standard interface for models that represent
3710 their data as a two-dimensional array of items. It is not used directly,
3711 but must be subclassed.
3712
3713 Since the model provides a more specialized interface than
3714 QAbstractItemModel, it is not suitable for use with tree views, although it
3715 can be used to provide data to a QListView. If you need to represent a
3716 simple list of items, and only need a model to contain a single column of
3717 data, subclassing the QAbstractListModel may be more appropriate.
3718
3719 The rowCount() and columnCount() functions return the dimensions of the
3720 table. To retrieve a model index corresponding to an item in the model, use
3721 index() and provide only the row and column numbers.
3722
3723 \section1 Subclassing
3724
3725 When subclassing QAbstractTableModel, you must implement rowCount(),
3726 columnCount(), and data(). Default implementations of the index() and
3727 parent() functions are provided by QAbstractTableModel.
3728 Well behaved models will also implement headerData().
3729
3730 Editable models need to implement setData(), and implement flags() to
3731 return a value containing
3732 \l{Qt::ItemFlags}{Qt::ItemIsEditable}.
3733
3734 Models that provide interfaces to resizable data structures can
3735 provide implementations of insertRows(), removeRows(), insertColumns(),
3736 and removeColumns(). When implementing these functions, it is
3737 important to call the appropriate functions so that all connected views
3738 are aware of any changes:
3739
3740 \list
3741 \li An insertRows() implementation must call beginInsertRows()
3742 \e before inserting new rows into the data structure, and it must
3743 call endInsertRows() \e{immediately afterwards}.
3744 \li An insertColumns() implementation must call beginInsertColumns()
3745 \e before inserting new columns into the data structure, and it must
3746 call endInsertColumns() \e{immediately afterwards}.
3747 \li A removeRows() implementation must call beginRemoveRows()
3748 \e before the rows are removed from the data structure, and it must
3749 call endRemoveRows() \e{immediately afterwards}.
3750 \li A removeColumns() implementation must call beginRemoveColumns()
3751 \e before the columns are removed from the data structure, and it must
3752 call endRemoveColumns() \e{immediately afterwards}.
3753 \endlist
3754
3755 \note Some general guidelines for subclassing models are available in the
3756 \l{Model Subclassing Reference}.
3757
3758 \note
3759
3760 \sa {Model Classes}, QAbstractItemModel, QAbstractListModel,
3761 {Pixelator Example}
3762*/
3763
3764/*!
3765 Constructs an abstract table model for the given \a parent.
3766*/
3767
3768QAbstractTableModel::QAbstractTableModel(QObject *parent)
3769 : QAbstractItemModel(parent)
3770{
3771
3772}
3773
3774/*!
3775 \internal
3776
3777 Constructs an abstract table model with \a dd and the given \a parent.
3778*/
3779
3780QAbstractTableModel::QAbstractTableModel(QAbstractItemModelPrivate &dd, QObject *parent)
3781 : QAbstractItemModel(dd, parent)
3782{
3783
3784}
3785
3786/*!
3787 Destroys the abstract table model.
3788*/
3789
3790QAbstractTableModel::~QAbstractTableModel()
3791{
3792
3793}
3794
3795/*!
3796 \fn QModelIndex QAbstractTableModel::index(int row, int column, const QModelIndex &parent = QModelIndex()) const
3797
3798 Returns the index of the data in \a row and \a column with \a parent.
3799
3800 \sa parent()
3801*/
3802
3803QModelIndex QAbstractTableModel::index(int row, int column, const QModelIndex &parent) const
3804{
3805 return hasIndex(row, column, parent) ? createIndex(row, column) : QModelIndex();
3806}
3807
3808/*!
3809 \fn QModelIndex QAbstractTableModel::parent(const QModelIndex &index) const
3810
3811 Returns the parent of the model item with the given \a index.
3812
3813 \sa index(), hasChildren()
3814*/
3815
3816QModelIndex QAbstractTableModel::parent(const QModelIndex &) const
3817{
3818 return QModelIndex();
3819}
3820
3821/*!
3822 \reimp
3823*/
3824QModelIndex QAbstractTableModel::sibling(int row, int column, const QModelIndex &) const
3825{
3826 return index(row, column);
3827}
3828
3829bool QAbstractTableModel::hasChildren(const QModelIndex &parent) const
3830{
3831 if (!parent.isValid())
3832 return rowCount(parent) > 0 && columnCount(parent) > 0;
3833 return false;
3834}
3835
3836/*!
3837 \reimp
3838 */
3839Qt::ItemFlags QAbstractTableModel::flags(const QModelIndex &index) const
3840{
3841 Qt::ItemFlags f = QAbstractItemModel::flags(index);
3842 if (index.isValid())
3843 f |= Qt::ItemNeverHasChildren;
3844 return f;
3845}
3846
3847/*!
3848 \class QAbstractListModel
3849 \inmodule QtCore
3850 \brief The QAbstractListModel class provides an abstract model that can be
3851 subclassed to create one-dimensional list models.
3852
3853 \ingroup model-view
3854
3855 QAbstractListModel provides a standard interface for models that represent
3856 their data as a simple non-hierarchical sequence of items. It is not used
3857 directly, but must be subclassed.
3858
3859 Since the model provides a more specialized interface than
3860 QAbstractItemModel, it is not suitable for use with tree views; you will
3861 need to subclass QAbstractItemModel if you want to provide a model for
3862 that purpose. If you need to use a number of list models to manage data,
3863 it may be more appropriate to subclass QAbstractTableModel instead.
3864
3865 Simple models can be created by subclassing this class and implementing
3866 the minimum number of required functions. For example, we could implement
3867 a simple read-only QStringList-based model that provides a list of strings
3868 to a QListView widget. In such a case, we only need to implement the
3869 rowCount() function to return the number of items in the list, and the
3870 data() function to retrieve items from the list.
3871
3872 Since the model represents a one-dimensional structure, the rowCount()
3873 function returns the total number of items in the model. The columnCount()
3874 function is implemented for interoperability with all kinds of views, but
3875 by default informs views that the model contains only one column.
3876
3877 \section1 Subclassing
3878
3879 When subclassing QAbstractListModel, you must provide implementations
3880 of the rowCount() and data() functions. Well behaved models also provide
3881 a headerData() implementation.
3882
3883 If your model is used within QML and requires roles other than the
3884 default ones provided by the roleNames() function, you must override it.
3885
3886 For editable list models, you must also provide an implementation of
3887 setData(), and implement the flags() function so that it returns a value
3888 containing \l{Qt::ItemFlags}{Qt::ItemIsEditable}.
3889
3890 Note that QAbstractListModel provides a default implementation of
3891 columnCount() that informs views that there is only a single column
3892 of items in this model.
3893
3894 Models that provide interfaces to resizable list-like data structures
3895 can provide implementations of insertRows() and removeRows(). When
3896 implementing these functions, it is important to call the appropriate
3897 functions so that all connected views are aware of any changes:
3898
3899 \list
3900 \li An insertRows() implementation must call beginInsertRows()
3901 \e before inserting new rows into the data structure, and it must
3902 call endInsertRows() \e{immediately afterwards}.
3903 \li A removeRows() implementation must call beginRemoveRows()
3904 \e before the rows are removed from the data structure, and it must
3905 call endRemoveRows() \e{immediately afterwards}.
3906 \endlist
3907
3908 \note Some general guidelines for subclassing models are available in the
3909 \l{Model Subclassing Reference}.
3910
3911 \sa {Model Classes}, {Model Subclassing Reference}, QAbstractItemView,
3912 QAbstractTableModel, {Item Views Puzzle Example}
3913*/
3914
3915/*!
3916 Constructs an abstract list model with the given \a parent.
3917*/
3918
3919QAbstractListModel::QAbstractListModel(QObject *parent)
3920 : QAbstractItemModel(parent)
3921{
3922
3923}
3924
3925/*!
3926 \internal
3927
3928 Constructs an abstract list model with \a dd and the given \a parent.
3929*/
3930
3931QAbstractListModel::QAbstractListModel(QAbstractItemModelPrivate &dd, QObject *parent)
3932 : QAbstractItemModel(dd, parent)
3933{
3934
3935}
3936
3937/*!
3938 Destroys the abstract list model.
3939*/
3940
3941QAbstractListModel::~QAbstractListModel()
3942{
3943
3944}
3945
3946/*!
3947 \fn QModelIndex QAbstractListModel::index(int row, int column, const QModelIndex &parent = QModelIndex()) const
3948
3949 Returns the index of the data in \a row and \a column with \a parent.
3950
3951 \sa parent()
3952*/
3953
3954QModelIndex QAbstractListModel::index(int row, int column, const QModelIndex &parent) const
3955{
3956 return hasIndex(row, column, parent) ? createIndex(row, column) : QModelIndex();
3957}
3958
3959/*!
3960 Returns the parent of the model item with the given \a index.
3961
3962 \sa index(), hasChildren()
3963*/
3964
3965QModelIndex QAbstractListModel::parent(const QModelIndex & /* index */) const
3966{
3967 return QModelIndex();
3968}
3969
3970/*!
3971 \reimp
3972*/
3973QModelIndex QAbstractListModel::sibling(int row, int column, const QModelIndex &) const
3974{
3975 return index(row, column);
3976}
3977
3978/*!
3979 \reimp
3980 */
3981Qt::ItemFlags QAbstractListModel::flags(const QModelIndex &index) const
3982{
3983 Qt::ItemFlags f = QAbstractItemModel::flags(index);
3984 if (index.isValid())
3985 f |= Qt::ItemNeverHasChildren;
3986 return f;
3987}
3988
3989/*!
3990 \internal
3991
3992 Returns the number of columns in the list with the given \a parent.
3993
3994 \sa rowCount()
3995*/
3996
3997int QAbstractListModel::columnCount(const QModelIndex &parent) const
3998{
3999 return parent.isValid() ? 0 : 1;
4000}
4001
4002bool QAbstractListModel::hasChildren(const QModelIndex &parent) const
4003{
4004 return parent.isValid() ? false : (rowCount() > 0);
4005}
4006
4007/*!
4008 \typedef QModelIndexList
4009 \relates QModelIndex
4010
4011 Synonym for QList<QModelIndex>.
4012*/
4013
4014/*!
4015 \reimp
4016*/
4017bool QAbstractTableModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
4018 int row, int column, const QModelIndex &parent)
4019{
4020 if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
4021 return false;
4022
4023 QStringList types = mimeTypes();
4024 if (types.isEmpty())
4025 return false;
4026 QString format = types.at(0);
4027 if (!data->hasFormat(format))
4028 return false;
4029
4030 QByteArray encoded = data->data(format);
4031 QDataStream stream(&encoded, QDataStream::ReadOnly);
4032
4033 // if the drop is on an item, replace the data in the items
4034 if (parent.isValid() && row == -1 && column == -1) {
4035 int top = INT_MAX;
4036 int left = INT_MAX;
4037 QList<int> rows, columns;
4038 QList<QMap<int, QVariant>> data;
4039
4040 while (!stream.atEnd()) {
4041 int r, c;
4042 QMap<int, QVariant> v;
4043 stream >> r >> c >> v;
4044 rows.append(r);
4045 columns.append(c);
4046 data.append(v);
4047 top = qMin(r, top);
4048 left = qMin(c, left);
4049 }
4050
4051 for (int i = 0; i < data.size(); ++i) {
4052 int r = (rows.at(i) - top) + parent.row();
4053 int c = (columns.at(i) - left) + parent.column();
4054 if (hasIndex(r, c))
4055 setItemData(index(r, c), data.at(i));
4056 }
4057
4058 return true;
4059 }
4060
4061 // otherwise insert new rows for the data
4062 return decodeData(row, column, parent, stream);
4063}
4064
4065/*!
4066 \reimp
4067*/
4068bool QAbstractListModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
4069 int row, int column, const QModelIndex &parent)
4070{
4071 if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
4072 return false;
4073
4074 QStringList types = mimeTypes();
4075 if (types.isEmpty())
4076 return false;
4077 QString format = types.at(0);
4078 if (!data->hasFormat(format))
4079 return false;
4080
4081 QByteArray encoded = data->data(format);
4082 QDataStream stream(&encoded, QDataStream::ReadOnly);
4083
4084 // if the drop is on an item, replace the data in the items
4085 if (parent.isValid() && row == -1 && column == -1) {
4086 int top = INT_MAX;
4087 int left = INT_MAX;
4088 QList<int> rows, columns;
4089 QList<QMap<int, QVariant>> data;
4090
4091 while (!stream.atEnd()) {
4092 int r, c;
4093 QMap<int, QVariant> v;
4094 stream >> r >> c >> v;
4095 rows.append(r);
4096 columns.append(c);
4097 data.append(v);
4098 top = qMin(r, top);
4099 left = qMin(c, left);
4100 }
4101
4102 for (int i = 0; i < data.size(); ++i) {
4103 int r = (rows.at(i) - top) + parent.row();
4104 if (columns.at(i) == left && hasIndex(r, 0))
4105 setItemData(index(r), data.at(i));
4106 }
4107
4108 return true;
4109 }
4110
4111 if (row == -1)
4112 row = rowCount(parent);
4113
4114 // otherwise insert new rows for the data
4115 return decodeData(row, column, parent, stream);
4116}
4117
4118/*!
4119 \fn QAbstractItemModel::modelAboutToBeReset()
4120 \since 4.2
4121
4122 This signal is emitted when beginResetModel() is called, before the model's internal
4123 state (e.g. persistent model indexes) has been invalidated.
4124
4125 \sa beginResetModel(), modelReset()
4126*/
4127
4128/*!
4129 \fn QAbstractItemModel::modelReset()
4130 \since 4.1
4131
4132 This signal is emitted when endResetModel() is called, after the
4133 model's internal state (e.g. persistent model indexes) has been invalidated.
4134
4135 Note that if a model is reset it should be considered that all information
4136 previously retrieved from it is invalid. This includes but is not limited
4137 to the rowCount() and columnCount(), flags(), data retrieved through data(),
4138 and roleNames().
4139
4140 \sa endResetModel(), modelAboutToBeReset()
4141*/
4142
4143/*!
4144 \fn bool QModelIndex::operator<(const QModelIndex &other) const
4145 \since 4.1
4146
4147 Returns \c{true} if this model index is smaller than the \a other
4148 model index; otherwise returns \c{false}.
4149
4150 The less than calculation is not directly useful to developers - the way that indexes
4151 with different parents compare is not defined. This operator only exists so that the
4152 class can be used with QMap.
4153*/
4154
4155/*!
4156 \fn size_t qHash(const QPersistentModelIndex &index, size_t seed = 0)
4157 \since 5.0
4158 \relates QPersistentModelIndex
4159
4160 Returns a hash of the QPersistentModelIndex \a index, using \a seed to
4161 seed the calculation.
4162*/
4163
4164
4165/*!
4166 \internal
4167 QMultiHash::insert inserts the value before the old value. and find() return the new value.
4168 We need insertMultiAtEnd because we don't want to overwrite the old one, which should be removed later
4169
4170 There should be only one instance QPersistentModelIndexData per index, but in some intermediate state there may be
4171 severals of PersistantModelIndex pointing to the same index, but one is already updated, and the other one is not.
4172 This make sure than when updating the first one we don't overwrite the second one in the hash, and the second one
4173 will be updated right later.
4174 */
4175void QAbstractItemModelPrivate::Persistent::insertMultiAtEnd(const QModelIndex& key, QPersistentModelIndexData *data)
4176{
4177 auto newIt = indexes.insert(key, data);
4178 auto it = newIt;
4179 ++it;
4180 while (it != indexes.end() && it.key() == key) {
4181 qSwap(*newIt,*it);
4182 newIt = it;
4183 ++it;
4184 }
4185}
4186
4187QT_END_NAMESPACE
4188
4189#include "moc_qabstractitemmodel.cpp"
4190