Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmldelegatemodel.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
6
7#include <QtQml/qqmlinfo.h>
8
9#include <private/qabstractitemmodel_p.h>
10#include <private/qcoreapplication_p.h>
11#include <private/qjsvalue_p.h>
12#include <private/qmetaobjectbuilder_p.h>
13#include <private/qqmlabstractdelegatecomponent_p.h>
14#include <private/qqmladaptormodel_p.h>
15#include <private/qqmlanybinding_p.h>
16#include <private/qqmlchangeset_p.h>
17#include <private/qqmlcomponent_p.h>
18#include <private/qqmlengine_p.h>
19#include <private/qqmlpropertytopropertybinding_p.h>
20#include <private/qqmltableinstancemodel_p.h>
21#include <private/qquickpackage_p.h>
22#include <private/qv4functionobject_p.h>
23#include <private/qv4objectiterator_p.h>
24#include <private/qv4value_p.h>
25
27
28Q_LOGGING_CATEGORY(lcItemViewDelegateRecycling, "qt.qml.delegatemodel.recycling")
29
30class QQmlDelegateModelItem;
31
32namespace QV4 {
33
34namespace Heap {
35
37 void init(ExecutionEngine *engine, uint flag, QV4::ReturnedValue (*code)(QQmlDelegateModelItem *item, uint flag, const QV4::Value &arg));
38
39 QV4::ReturnedValue (*code)(QQmlDelegateModelItem *item, uint flag, const QV4::Value &arg);
41};
42
44 void init() { Object::init(); }
45
47};
48
50 void init(const QList<QQmlChangeSet::Change> &changes);
51 void destroy() {
52 delete changes;
53 Object::destroy();
54 }
55
57};
58
59
60}
61
63{
64 V4_OBJECT2(DelegateModelGroupFunction, FunctionObject)
65
67 QV4::ExecutionEngine *engine, uint flag,
68 QV4::ReturnedValue (*code)(QQmlDelegateModelItem *, uint, const QV4::Value &))
69 {
70 return engine->memoryManager->allocate<DelegateModelGroupFunction>(engine, flag, code);
71 }
72
73 static ReturnedValue virtualCall(const QV4::FunctionObject *that, const Value *thisObject, const Value *argv, int argc)
74 {
75 QV4::Scope scope(that->engine());
76 QV4::Scoped<DelegateModelGroupFunction> f(scope, static_cast<const DelegateModelGroupFunction *>(that));
77 QV4::Scoped<QQmlDelegateModelItemObject> o(scope, thisObject);
78 if (!o)
79 return scope.engine->throwTypeError(QStringLiteral("Not a valid DelegateModel object"));
80
81 QV4::ScopedValue v(scope, argc ? argv[0] : Value::undefinedValue());
82 return f->d()->code(o->d()->item(), f->d()->flag, v);
83 }
84};
85
87 QV4::ExecutionEngine *engine, uint flag,
88 QV4::ReturnedValue (*code)(QQmlDelegateModelItem *item, uint flag, const QV4::Value &arg))
89{
90 QV4::Heap::FunctionObject::init(engine, QStringLiteral("DelegateModelGroupFunction"));
91 this->flag = flag;
92 this->code = code;
93}
94
95}
96
98
99
100
102{
103public:
104 QQmlDelegateModelEngineData(QV4::ExecutionEngine *v4);
106
107 QV4::ReturnedValue array(QV4::ExecutionEngine *engine,
108 const QList<QQmlChangeSet::Change> &changes);
109
111};
112
113V4_DEFINE_EXTENSION(QQmlDelegateModelEngineData, qdmEngineData)
114
115
116void QQmlDelegateModelPartsMetaObject::propertyCreated(int, QMetaPropertyBuilder &prop)
117{
118 prop.setWritable(false);
119}
120
122{
123 QQmlDelegateModelParts *parts = static_cast<QQmlDelegateModelParts *>(object());
124 QQmlPartsModel *m = new QQmlPartsModel(
125 parts->model, QString::fromUtf8(name(id)), parts);
126 parts->models.append(m);
127 return QVariant::fromValue(static_cast<QObject *>(m));
128}
129
130QQmlDelegateModelParts::QQmlDelegateModelParts(QQmlDelegateModel *parent)
131: QObject(parent), model(parent)
132{
133 new QQmlDelegateModelPartsMetaObject(this);
134}
135
136//---------------------------------------------------------------------------
137
138/*!
139 \qmltype DelegateModel
140 \nativetype QQmlDelegateModel
141 \inqmlmodule QtQml.Models
142 \brief Encapsulates a model and delegate.
143
144 The DelegateModel type encapsulates a model and the delegate that will
145 be instantiated for items in the model.
146
147 It is usually not necessary to create a DelegateModel.
148 However, it can be useful for manipulating and accessing the \l modelIndex
149 when a QAbstractItemModel subclass is used as the
150 model. Also, DelegateModel is used together with \l Package to
151 provide delegates to multiple views, and with DelegateModelGroup to sort and filter
152 delegate items.
153
154 DelegateModel only supports one-dimensional models -- assigning a table model to
155 DelegateModel and that to TableView will thus only show one column.
156
157 The example below illustrates using a DelegateModel with a ListView.
158
159 \snippet delegatemodel/delegatemodel.qml 0
160*/
161
162QQmlDelegateModelPrivate::QQmlDelegateModelPrivate(QQmlContext *ctxt)
163 : m_delegateChooser(nullptr)
164 , m_context(ctxt)
165 , m_parts(nullptr)
166 , m_filterGroup(QStringLiteral("items"))
167 , m_count(0)
168 , m_groupCount(Compositor::MinimumGroupCount)
169 , m_compositorGroup(Compositor::Cache)
170 , m_complete(false)
171 , m_delegateValidated(false)
172 , m_reset(false)
173 , m_transaction(false)
175 , m_waitingToFetchMore(false)
176 , m_cacheItems(nullptr)
177 , m_items(nullptr)
178 , m_persistedItems(nullptr)
179{
180}
181
183{
184 qDeleteAll(m_finishedIncubating);
185
186 // Free up all items in the pool
188}
189
191{
192 // QQmlDelegateModel currently only support list models.
193 // So even if a model is a table model, only the first
194 // column will be used.
195 return m_adaptorModel.rowCount();
196}
197
199{
200 Q_Q(QQmlDelegateModel);
201 if (!m_waitingToFetchMore && m_adaptorModel.canFetchMore()) {
203 QCoreApplication::postEvent(q, new QEvent(QEvent::UpdateRequest));
204 }
205}
206
208{
209 Q_Q(QQmlDelegateModel);
210 m_compositor.setRemoveGroups(Compositor::GroupMask & ~Compositor::PersistedFlag);
211
212 m_items = new QQmlDelegateModelGroup(QStringLiteral("items"), q, Compositor::Default, q);
213 m_items->setDefaultInclude(true);
214 m_persistedItems = new QQmlDelegateModelGroup(QStringLiteral("persistedItems"), q, Compositor::Persisted, q);
215 QQmlDelegateModelGroupPrivate::get(m_items)->emitters.insert(this);
216}
217
218QQmlDelegateModel::QQmlDelegateModel()
219 : QQmlDelegateModel(nullptr, nullptr)
220{
221}
222
223QQmlDelegateModel::QQmlDelegateModel(QQmlContext *ctxt, QObject *parent)
224: QQmlInstanceModel(*(new QQmlDelegateModelPrivate(ctxt)), parent)
225{
226 Q_D(QQmlDelegateModel);
227 d->init();
228}
229
230QQmlDelegateModel::~QQmlDelegateModel()
231{
232 Q_D(QQmlDelegateModel);
233 d->disconnectFromAbstractItemModel();
234 d->m_adaptorModel.setObject(nullptr);
235
236 for (QQmlDelegateModelItem *cacheItem : std::as_const(d->m_cache)) {
237 cacheItem->destroyObject();
238 cacheItem->removeGroups(Compositor::UnresolvedFlag);
239 cacheItem->clearObjectWeakReferences();
240
241 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
242 d->releaseIncubator(incubationTask);
243 incubationTask->vdm = nullptr;
244 cacheItem->clearIncubationTask();
245 }
246
247 if (!cacheItem->isScriptReferenced())
248 delete cacheItem;
249 }
250}
251
252
253void QQmlDelegateModel::classBegin()
254{
255 Q_D(QQmlDelegateModel);
256 if (!d->m_context)
257 d->m_context = qmlContext(this);
258}
259
260void QQmlDelegateModel::componentComplete()
261{
262 Q_D(QQmlDelegateModel);
263 d->m_complete = true;
264
265 int defaultGroups = 0;
266 QStringList groupNames;
267 groupNames.append(QStringLiteral("items"));
268 groupNames.append(QStringLiteral("persistedItems"));
269 if (QQmlDelegateModelGroupPrivate::get(d->m_items)->defaultInclude)
270 defaultGroups |= Compositor::DefaultFlag;
271 if (QQmlDelegateModelGroupPrivate::get(d->m_persistedItems)->defaultInclude)
272 defaultGroups |= Compositor::PersistedFlag;
273 for (int i = Compositor::MinimumGroupCount; i < d->m_groupCount; ++i) {
274 QString name = d->m_groups[i]->name();
275 if (name.isEmpty()) {
276 d->m_groups[i] = d->m_groups[d->m_groupCount - 1];
277 --d->m_groupCount;
278 --i;
279 } else if (name.at(0).isUpper()) {
280 qmlWarning(d->m_groups[i]) << QQmlDelegateModelGroup::tr("Group names must start with a lower case letter");
281 d->m_groups[i] = d->m_groups[d->m_groupCount - 1];
282 --d->m_groupCount;
283 --i;
284 } else {
285 groupNames.append(name);
286
287 QQmlDelegateModelGroupPrivate *group = QQmlDelegateModelGroupPrivate::get(d->m_groups[i]);
288 group->setModel(this, Compositor::Group(i));
289 if (group->defaultInclude)
290 defaultGroups |= (1 << i);
291 }
292 }
293
294 d->m_cacheMetaType = QQml::makeRefPointer<QQmlDelegateModelItemMetaType>(
295 d->m_context->engine()->handle(), this, groupNames);
296
297 d->m_compositor.setGroupCount(d->m_groupCount);
298 d->m_compositor.setDefaultGroups(defaultGroups);
299 d->updateFilterGroup();
300
301 while (!d->m_pendingParts.isEmpty())
302 static_cast<QQmlPartsModel *>(d->m_pendingParts.first())->updateFilterGroup();
303
304 QList<Compositor::Insert> inserts;
305 d->m_count = d->adaptorModelCount();
306 d->m_compositor.append(
307 &d->m_adaptorModel,
308 0,
309 d->m_count,
310 defaultGroups | Compositor::AppendFlag | Compositor::PrependFlag,
311 &inserts);
312 d->itemsInserted(inserts);
313 d->emitChanges();
314 d->requestMoreIfNecessary();
315}
316
317/*!
318 \qmlproperty model QtQml.Models::DelegateModel::model
319 This property holds the model providing data for the DelegateModel.
320
321 The model provides a set of data that is used to create the items
322 for a view. For large or dynamic datasets the model is usually
323 provided by a C++ model object. The C++ model object must be a \l
324 {QAbstractItemModel} subclass or a simple list.
325
326 Models can also be created directly in QML, for example using
327 ListModel.
328
329 \sa {qml-data-models}{Data Models}
330 \keyword dm-model-property
331*/
332QVariant QQmlDelegateModel::model() const
333{
334 Q_D(const QQmlDelegateModel);
335 return d->m_adaptorModel.model();
336}
337
339{
340 Q_Q(QQmlDelegateModel);
341 if (!m_adaptorModel.adaptsAim())
342 return;
343
344 auto aim = m_adaptorModel.aim();
345
346 QObject::connect(aim, &QAbstractItemModel::rowsInserted, q, &QQmlDelegateModel::_q_rowsInserted);
347 QObject::connect(aim, &QAbstractItemModel::rowsRemoved, q, &QQmlDelegateModel::_q_rowsRemoved);
348 QObject::connect(aim, &QAbstractItemModel::rowsAboutToBeRemoved, q, &QQmlDelegateModel::_q_rowsAboutToBeRemoved);
349 QObject::connect(aim, &QAbstractItemModel::columnsInserted, q, &QQmlDelegateModel::_q_columnsInserted);
350 QObject::connect(aim, &QAbstractItemModel::columnsRemoved, q, &QQmlDelegateModel::_q_columnsRemoved);
351 QObject::connect(aim, &QAbstractItemModel::columnsMoved, q, &QQmlDelegateModel::_q_columnsMoved);
352 QObject::connect(aim, &QAbstractItemModel::dataChanged, q, &QQmlDelegateModel::_q_dataChanged);
353 QObject::connect(aim, &QAbstractItemModel::rowsMoved, q, &QQmlDelegateModel::_q_rowsMoved);
354 QObject::connect(aim, &QAbstractItemModel::modelAboutToBeReset, q, &QQmlDelegateModel::_q_modelAboutToBeReset);
355 QObject::connect(aim, &QAbstractItemModel::layoutChanged, q, &QQmlDelegateModel::_q_layoutChanged);
356}
357
359{
360 Q_Q(QQmlDelegateModel);
361 if (!m_adaptorModel.adaptsAim())
362 return;
363
364 auto aim = m_adaptorModel.aim();
365
366 QObject::disconnect(aim, &QAbstractItemModel::rowsInserted, q, &QQmlDelegateModel::_q_rowsInserted);
367 QObject::disconnect(aim, &QAbstractItemModel::rowsAboutToBeRemoved, q, &QQmlDelegateModel::_q_rowsAboutToBeRemoved);
368 QObject::disconnect(aim, &QAbstractItemModel::rowsRemoved, q, &QQmlDelegateModel::_q_rowsRemoved);
369 QObject::disconnect(aim, &QAbstractItemModel::columnsInserted, q, &QQmlDelegateModel::_q_columnsInserted);
370 QObject::disconnect(aim, &QAbstractItemModel::columnsRemoved, q, &QQmlDelegateModel::_q_columnsRemoved);
371 QObject::disconnect(aim, &QAbstractItemModel::columnsMoved, q, &QQmlDelegateModel::_q_columnsMoved);
372 QObject::disconnect(aim, &QAbstractItemModel::dataChanged, q, &QQmlDelegateModel::_q_dataChanged);
373 QObject::disconnect(aim, &QAbstractItemModel::rowsMoved, q, &QQmlDelegateModel::_q_rowsMoved);
374 QObject::disconnect(aim, &QAbstractItemModel::modelAboutToBeReset, q, &QQmlDelegateModel::_q_modelAboutToBeReset);
375 QObject::disconnect(aim, &QAbstractItemModel::layoutChanged, q, &QQmlDelegateModel::_q_layoutChanged);
376}
377
378void QQmlDelegateModel::setModel(const QVariant &model)
379{
380 Q_D(QQmlDelegateModel);
381
382 if (d->m_adaptorModel.model() == model)
383 return;
384
385 if (d->m_complete)
386 _q_itemsRemoved(0, d->m_count);
387
388 // Pooled items were created for the old model; reusing one for the new model
389 // leaves it showing stale data. Drain the pool, as
390 // QQmlTableInstanceModel::forceSetModel() does.
391 d->drainReusableItemsPool(0);
392
393 d->disconnectFromAbstractItemModel();
394 d->m_adaptorModel.setModel(model);
395 d->connectToAbstractItemModel();
396
397 d->m_adaptorModel.replaceWatchedRoles(QList<QByteArray>(), d->m_watchedRoles);
398 for (int i = 0; d->m_parts && i < d->m_parts->models.size(); ++i) {
399 d->m_adaptorModel.replaceWatchedRoles(
400 QList<QByteArray>(), d->m_parts->models.at(i)->watchedRoles());
401 }
402
403 if (d->m_complete) {
404 _q_itemsInserted(0, d->adaptorModelCount());
405 d->requestMoreIfNecessary();
406 }
407
408 // Since 837c2f18cd223707e7cedb213257b0158ea07146, we connect to modelAboutToBeReset
409 // rather than modelReset so that we can handle role name changes. _q_modelAboutToBeReset
410 // now connects modelReset to handleModelReset with a single shot connection instead.
411 // However, it's possible for user code to begin the reset before connectToAbstractItemModel is called
412 // (QTBUG-125053), in which case we connect to modelReset too late and handleModelReset is never called,
413 // resulting in delegates not being created in certain cases.
414 // So, we check at the earliest point we can if the model is in the process of being reset,
415 // and if so, connect modelReset to handleModelReset.
416 if (d->m_adaptorModel.adaptsAim()) {
417 auto *aim = d->m_adaptorModel.aim();
418 auto *aimPrivate = QAbstractItemModelPrivate::get(aim);
419 if (aimPrivate->resetting)
420 QObject::connect(aim, &QAbstractItemModel::modelReset, this, &QQmlDelegateModel::handleModelReset, Qt::SingleShotConnection);
421 }
422
423 emit modelChanged();
424}
425
426/*!
427 \qmlproperty Component QtQml.Models::DelegateModel::delegate
428
429 The delegate provides a template defining each item instantiated by a view.
430 The index is exposed as an accessible \c index property. Properties of the
431 model are also available depending upon the type of \l {qml-data-models}{Data Model}.
432*/
433QQmlComponent *QQmlDelegateModel::delegate() const
434{
435 Q_D(const QQmlDelegateModel);
436 return d->m_delegate;
437}
438
439void QQmlDelegateModel::setDelegate(QQmlComponent *delegate)
440{
441 Q_D(QQmlDelegateModel);
442 if (d->m_transaction) {
443 qmlWarning(this) << tr("The delegate of a DelegateModel cannot be changed within onUpdated.");
444 return;
445 }
446 if (d->m_delegate == delegate)
447 return;
448 if (d->m_complete)
449 _q_itemsRemoved(0, d->m_count);
450 d->m_delegate.setObject(delegate, this);
451 d->m_delegateValidated = false;
452 if (d->m_delegateChooser)
453 QObject::disconnect(d->m_delegateChooserChanged);
454
455 d->m_delegateChooser = nullptr;
456 if (delegate) {
457 QQmlAbstractDelegateComponent *adc =
458 qobject_cast<QQmlAbstractDelegateComponent *>(delegate);
459 if (adc) {
460 d->m_delegateChooser = adc;
461 d->m_delegateChooserChanged = connect(adc, &QQmlAbstractDelegateComponent::delegateChanged, this,
462 [d](){ d->delegateChanged(); });
463 }
464 }
465 if (d->m_complete) {
466 _q_itemsInserted(0, d->adaptorModelCount());
467 d->requestMoreIfNecessary();
468 }
469 emit delegateChanged();
470}
471
472/*!
473 \qmlproperty QModelIndex QtQml.Models::DelegateModel::rootIndex
474
475 QAbstractItemModel provides a hierarchical tree of data, whereas
476 QML only operates on list data. \c rootIndex allows the children of
477 any node in a QAbstractItemModel to be provided by this model.
478
479 This property only affects models of type QAbstractItemModel that
480 are hierarchical (e.g, a tree model).
481
482 For example, here is a simple interactive file system browser.
483 When a directory name is clicked, the view's \c rootIndex is set to the
484 QModelIndex node of the clicked directory, thus updating the view to show
485 the new directory's contents.
486
487 \c main.cpp:
488 \snippet delegatemodel/delegatemodel_rootindex/main.cpp 0
489
490 \c view.qml:
491 \snippet delegatemodel/delegatemodel_rootindex/view.qml 0
492
493 If the \l {dm-model-property}{model} is a QAbstractItemModel subclass,
494 the delegate can also reference a \c hasModelChildren property (optionally
495 qualified by a \e model. prefix) that indicates whether the delegate's
496 model item has any child nodes.
497
498 \sa modelIndex(), parentModelIndex()
499*/
500QVariant QQmlDelegateModel::rootIndex() const
501{
502 Q_D(const QQmlDelegateModel);
503 return QVariant::fromValue(QModelIndex(d->m_adaptorModel.rootIndex));
504}
505
506void QQmlDelegateModel::setRootIndex(const QVariant &root)
507{
508 Q_D(QQmlDelegateModel);
509
510 QModelIndex modelIndex = qvariant_cast<QModelIndex>(root);
511 const bool changed = d->m_adaptorModel.rootIndex != modelIndex;
512 if (changed || !d->m_adaptorModel.isValid()) {
513 const int oldCount = d->m_count;
514 d->m_adaptorModel.rootIndex = modelIndex;
515 if (!d->m_adaptorModel.isValid() && d->m_adaptorModel.aim()) {
516 // The previous root index was invalidated, so we need to reconnect the model.
517 d->disconnectFromAbstractItemModel();
518 d->m_adaptorModel.setModel(d->m_adaptorModel.list.list());
519 d->connectToAbstractItemModel();
520 }
521 if (d->m_adaptorModel.canFetchMore())
522 d->m_adaptorModel.fetchMore();
523 if (d->m_complete) {
524 const int newCount = d->adaptorModelCount();
525 if (oldCount)
526 _q_itemsRemoved(0, oldCount);
527 if (newCount)
528 _q_itemsInserted(0, newCount);
529 }
530 if (changed)
531 emit rootIndexChanged();
532 }
533}
534
535/*!
536 \qmlproperty enumeration QtQml.Models::DelegateModel::delegateModelAccess
537 \since 6.10
538
539 \include delegatemodelaccess.qdocinc
540*/
541QQmlDelegateModel::DelegateModelAccess QQmlDelegateModel::delegateModelAccess() const
542{
543 Q_D(const QQmlDelegateModel);
544 return d->m_adaptorModel.delegateModelAccess;
545}
546
547void QQmlDelegateModel::setDelegateModelAccess(
548 QQmlDelegateModel::DelegateModelAccess delegateModelAccess)
549{
550 Q_D(QQmlDelegateModel);
551 if (d->m_adaptorModel.delegateModelAccess == delegateModelAccess)
552 return;
553
554 if (d->m_transaction) {
555 qmlWarning(this) << tr("The delegateModelAccess of a DelegateModel "
556 "cannot be changed within onUpdated.");
557 return;
558 }
559
560 if (d->m_complete) {
561 _q_itemsRemoved(0, d->m_count);
562 d->m_adaptorModel.delegateModelAccess = delegateModelAccess;
563 _q_itemsInserted(0, d->adaptorModelCount());
564 d->requestMoreIfNecessary();
565 } else {
566 d->m_adaptorModel.delegateModelAccess = delegateModelAccess;
567 }
568
569 emit delegateModelAccessChanged();
570}
571
572/*!
573 \qmlmethod QModelIndex QtQml.Models::DelegateModel::modelIndex(int index)
574
575 QAbstractItemModel provides a hierarchical tree of data, whereas
576 QML only operates on list data. This function assists in using
577 tree models in QML.
578
579 Returns a QModelIndex for the specified \a index.
580 This value can be assigned to rootIndex.
581
582 \sa rootIndex
583*/
584QVariant QQmlDelegateModel::modelIndex(int idx) const
585{
586 Q_D(const QQmlDelegateModel);
587 return d->m_adaptorModel.modelIndex(idx);
588}
589
590/*!
591 \qmlmethod QModelIndex QtQml.Models::DelegateModel::parentModelIndex()
592
593 QAbstractItemModel provides a hierarchical tree of data, whereas
594 QML only operates on list data. This function assists in using
595 tree models in QML.
596
597 Returns a QModelIndex for the parent of the current rootIndex.
598 This value can be assigned to rootIndex.
599
600 \sa rootIndex
601*/
602QVariant QQmlDelegateModel::parentModelIndex() const
603{
604 Q_D(const QQmlDelegateModel);
605 return d->m_adaptorModel.parentModelIndex();
606}
607
608/*!
609 \qmlproperty int QtQml.Models::DelegateModel::count
610*/
611
612int QQmlDelegateModel::count() const
613{
614 Q_D(const QQmlDelegateModel);
615 if (!d->m_delegate)
616 return 0;
617 return d->m_compositor.count(d->m_compositorGroup);
618}
619
620QQmlDelegateModel::ReleaseFlags QQmlDelegateModelPrivate::release(QObject *object, QQmlInstanceModel::ReusableFlag reusableFlag)
621{
622 if (!object)
623 return QQmlDelegateModel::ReleaseFlags{};
624
625 QQmlDelegateModelItem *cacheItem = QQmlDelegateModelItem::dataForObject(object);
626 if (!cacheItem)
627 return QQmlDelegateModel::ReleaseFlags{};
628
629 if (!cacheItem->releaseObjectWeak())
630 return QQmlDelegateModel::Referenced;
631
632 if (reusableFlag == QQmlInstanceModel::Reusable && m_reusableItemsPool.insertItem(cacheItem)) {
633 removeCacheItem(cacheItem);
634 emit q_func()->itemPooled(cacheItem->modelIndex(), cacheItem->object());
635 return QQmlInstanceModel::Pooled;
636 }
637
638 destroyCacheItem(cacheItem);
639 return QQmlInstanceModel::Destroyed;
640}
641
642void QQmlDelegateModelPrivate::destroyCacheItem(QQmlDelegateModelItem *cacheItem)
643{
644 if (QObject *object = cacheItem->object()) {
645 emitDestroyingItem(object);
646 cacheItem->destroyObjectLater();
647 }
648
649 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
650 releaseIncubator(incubationTask);
651 cacheItem->clearIncubationTask();
652 }
653 cacheItem->dispose();
654}
655
656/*
657 Returns ReleaseStatus flags.
658*/
659QQmlDelegateModel::ReleaseFlags QQmlDelegateModel::release(QObject *item, QQmlInstanceModel::ReusableFlag reusableFlag)
660{
661 Q_D(QQmlDelegateModel);
662 QQmlInstanceModel::ReleaseFlags stat = d->release(item, reusableFlag);
663 return stat;
664}
665
666// Cancel a requested async item
667void QQmlDelegateModel::cancel(int index)
668{
669 Q_D(QQmlDelegateModel);
670 if (index < 0 || index >= d->m_compositor.count(d->m_compositorGroup)) {
671 qWarning() << "DelegateModel::cancel: index out range" << index << d->m_compositor.count(d->m_compositorGroup);
672 return;
673 }
674
675 Compositor::iterator it = d->m_compositor.find(d->m_compositorGroup, index);
676 QQmlDelegateModelItem *cacheItem = it->inCache() ? d->m_cache.at(it.cacheIndex()) : 0;
677 if (cacheItem) {
678 if (cacheItem->incubationTask() && !cacheItem->isObjectReferenced()) {
679 d->releaseIncubator(cacheItem->incubationTask());
680 cacheItem->clearIncubationTask();
681
682 if (QObject *object = cacheItem->object()) {
683 cacheItem->destroyObjectLater();
684 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
685 d->emitDestroyingPackage(package);
686 else
687 d->emitDestroyingItem(object);
688 }
689 }
690 if (!cacheItem->isScriptReferenced() && !cacheItem->object()) {
691 d->m_compositor.clearFlags(
692 Compositor::Cache, it.cacheIndex(), 1, Compositor::CacheFlag);
693 d->m_cache.removeAt(it.cacheIndex());
694 delete cacheItem;
695 Q_ASSERT(d->m_cache.size() == d->m_compositor.count(Compositor::Cache));
696 }
697 }
698}
699
700void QQmlDelegateModelPrivate::group_append(
701 QQmlListProperty<QQmlDelegateModelGroup> *property, QQmlDelegateModelGroup *group)
702{
703 QQmlDelegateModelPrivate *d = static_cast<QQmlDelegateModelPrivate *>(property->data);
704 if (d->m_complete)
705 return;
706 if (d->m_groupCount == Compositor::MaximumGroupCount) {
707 qmlWarning(d->q_func()) << QQmlDelegateModel::tr("The maximum number of supported DelegateModelGroups is 8");
708 return;
709 }
710 d->m_groups[d->m_groupCount] = group;
711 d->m_groupCount += 1;
712}
713
714qsizetype QQmlDelegateModelPrivate::group_count(
715 QQmlListProperty<QQmlDelegateModelGroup> *property)
716{
717 QQmlDelegateModelPrivate *d = static_cast<QQmlDelegateModelPrivate *>(property->data);
718 return d->m_groupCount - 1;
719}
720
721QQmlDelegateModelGroup *QQmlDelegateModelPrivate::group_at(
722 QQmlListProperty<QQmlDelegateModelGroup> *property, qsizetype index)
723{
724 QQmlDelegateModelPrivate *d = static_cast<QQmlDelegateModelPrivate *>(property->data);
725 return index >= 0 && index < d->m_groupCount - 1
726 ? d->m_groups[index + 1]
727 : nullptr;
728}
729
730/*!
731 \qmlproperty list<DelegateModelGroup> QtQml.Models::DelegateModel::groups
732
733 This property holds a delegate model's group definitions.
734
735 Groups define a sub-set of the items in a delegate model and can be used to filter
736 a model.
737
738 For every group defined in a DelegateModel two attached pseudo-properties are added to each
739 delegate item. The first of the form DelegateModel.in\e{GroupName} holds whether the
740 item belongs to the group and the second DelegateModel.\e{groupName}Index holds the
741 index of the item in that group.
742
743 The following example illustrates using groups to select items in a model.
744
745 \snippet delegatemodel/delegatemodelgroup.qml 0
746 \keyword dm-groups-property
747
748
749 \warning In contrast to normal attached properties, those cannot be set in a declarative way.
750 The following would result in an error:
751 \badcode
752 delegate: Rectangle {
753 DelegateModel.inSelected: true
754 }
755 \endcode
756*/
757
758QQmlListProperty<QQmlDelegateModelGroup> QQmlDelegateModel::groups()
759{
760 Q_D(QQmlDelegateModel);
761 return QQmlListProperty<QQmlDelegateModelGroup>(
762 this,
763 d,
764 QQmlDelegateModelPrivate::group_append,
765 QQmlDelegateModelPrivate::group_count,
766 QQmlDelegateModelPrivate::group_at,
767 nullptr, nullptr, nullptr);
768}
769
770/*!
771 \qmlproperty DelegateModelGroup QtQml.Models::DelegateModel::items
772
773 This property holds default group to which all new items are added.
774*/
775
776QQmlDelegateModelGroup *QQmlDelegateModel::items()
777{
778 Q_D(QQmlDelegateModel);
779 return d->m_items;
780}
781
782/*!
783 \qmlproperty DelegateModelGroup QtQml.Models::DelegateModel::persistedItems
784
785 This property holds delegate model's persisted items group.
786
787 Items in this group are not destroyed when released by a view, instead they are persisted
788 until removed from the group.
789
790 An item can be removed from the persistedItems group by setting the
791 DelegateModel.inPersistedItems property to false. If the item is not referenced by a view
792 at that time it will be destroyed. Adding an item to this group will not create a new
793 instance.
794
795 Items returned by the \l QtQml.Models::DelegateModelGroup::create() function are automatically added
796 to this group.
797*/
798
799QQmlDelegateModelGroup *QQmlDelegateModel::persistedItems()
800{
801 Q_D(QQmlDelegateModel);
802 return d->m_persistedItems;
803}
804
805/*!
806 \qmlproperty string QtQml.Models::DelegateModel::filterOnGroup
807
808 This property holds name of the group that is used to filter the delegate model.
809
810 Only items that belong to this group are visible to a view.
811
812 By default this is the \l items group.
813*/
814
815QString QQmlDelegateModel::filterGroup() const
816{
817 Q_D(const QQmlDelegateModel);
818 return d->m_filterGroup;
819}
820
821void QQmlDelegateModel::setFilterGroup(const QString &group)
822{
823 Q_D(QQmlDelegateModel);
824
825 if (d->m_transaction) {
826 qmlWarning(this) << tr("The group of a DelegateModel cannot be changed within onChanged");
827 return;
828 }
829
830 if (d->m_filterGroup != group) {
831 d->m_filterGroup = group;
832 d->updateFilterGroup();
833 emit filterGroupChanged();
834 }
835}
836
837void QQmlDelegateModel::resetFilterGroup()
838{
839 setFilterGroup(QStringLiteral("items"));
840}
841
843{
844 Q_Q(QQmlDelegateModel);
845 if (!m_cacheMetaType)
846 return;
847
848 QQmlListCompositor::Group previousGroup = m_compositorGroup;
849 m_compositorGroup = Compositor::Default;
850 for (int i = 1; i < m_groupCount; ++i) {
851 if (m_filterGroup == m_cacheMetaType->groupNames.at(i - 1)) {
852 m_compositorGroup = Compositor::Group(i);
853 break;
854 }
855 }
856
857 QQmlDelegateModelGroupPrivate::get(m_groups[m_compositorGroup])->emitters.insert(this);
858 if (m_compositorGroup != previousGroup) {
859 QList<QQmlChangeSet::Change> removes;
860 QList<QQmlChangeSet::Change> inserts;
861 m_compositor.transition(previousGroup, m_compositorGroup, &removes, &inserts);
862
863 QQmlChangeSet changeSet;
864 changeSet.move(removes, inserts);
865 emit q->modelUpdated(changeSet, false);
866
867 if (changeSet.difference() != 0)
868 emit q->countChanged();
869
870 if (m_parts) {
871 auto partsCopy = m_parts->models; // deliberate; this may alter m_parts
872 for (QQmlPartsModel *model : std::as_const(partsCopy))
873 model->updateFilterGroup(m_compositorGroup, changeSet);
874 }
875 }
876}
877
878/*!
879 \qmlproperty object QtQml.Models::DelegateModel::parts
880
881 The \a parts property selects a DelegateModel which creates
882 delegates from the part named. This is used in conjunction with
883 the \l Package type.
884
885 For example, the code below selects a model which creates
886 delegates named \e list from a \l Package:
887
888 \code
889 DelegateModel {
890 id: visualModel
891 delegate: Package {
892 Item { Package.name: "list" }
893 }
894 model: myModel
895 }
896
897 ListView {
898 width: 200; height:200
899 model: visualModel.parts.list
900 }
901 \endcode
902
903 \sa Package
904*/
905
906QObject *QQmlDelegateModel::parts()
907{
908 Q_D(QQmlDelegateModel);
909 if (!d->m_parts)
910 d->m_parts = new QQmlDelegateModelParts(this);
911 return d->m_parts;
912}
913
914const QAbstractItemModel *QQmlDelegateModel::abstractItemModel() const
915{
916 Q_D(const QQmlDelegateModel);
917 return d->m_adaptorModel.adaptsAim() ? d->m_adaptorModel.aim() : nullptr;
918}
919
920void QQmlDelegateModelPrivate::emitCreatedPackage(QQDMIncubationTask *incubationTask, QQuickPackage *package)
921{
922 for (int i = 1; i < m_groupCount; ++i)
923 QQmlDelegateModelGroupPrivate::get(m_groups[i])->createdPackage(incubationTask->index[i], package);
924}
925
926void QQmlDelegateModelPrivate::emitInitPackage(QQDMIncubationTask *incubationTask, QQuickPackage *package)
927{
928 for (int i = 1; i < m_groupCount; ++i)
929 QQmlDelegateModelGroupPrivate::get(m_groups[i])->initPackage(incubationTask->index[i], package);
930}
931
933{
934 for (int i = 1; i < m_groupCount; ++i)
935 QQmlDelegateModelGroupPrivate::get(m_groups[i])->destroyingPackage(package);
936}
937
938static bool isDoneIncubating(QQmlIncubator::Status status)
939{
940 return status == QQmlIncubator::Ready || status == QQmlIncubator::Error;
941}
942
944{
946public:
955
956 template<typename ModelObjectType>
958 {
960 for (int i = modelMetaObject->propertyOffset(); i < end; ++i) {
962 if (!prop.name())
963 continue;
965
966 bool wasInRequired = false;
970 if (!wasInRequired)
971 continue;
972
979
981 continue;
982
987 // Temporarily take away the metaobject so that the property can't actually be
988 // written. It shouldn't be written since we've just synchronized it the other way
989 // when installing the "forward" binding.
992 } else {
993 // It's only not a QQmlDelegateModelItem if the model is actually an ObjectModel.
994 // In that case, we hope that the generic equality check when setting a property
995 // is enough to de-bounce it.
997 }
998 }
999 }
1000
1001private:
1002 QQmlEngine *engine = nullptr;
1003 QObject *targetObject = nullptr;
1004 RequiredProperties *requiredProperties = nullptr;
1007};
1008
1010 QQmlDelegateModelItem *modelItemToIncubate, QObject *object,
1011 QQmlDelegateModel::DelegateModelAccess access)
1012{
1013 // QQmlObjectCreator produces a private internal context.
1014 // We can always attach the extra object there.
1015 QQmlData *d = QQmlData::get(object);
1016 if (auto contextData = d ? d->context : nullptr)
1017 contextData->setExtraObject(modelItemToIncubate);
1018
1019 Q_ASSERT(modelItemToIncubate->delegate());
1020 const bool isBound = QQmlComponentPrivate::get(modelItemToIncubate->delegate())->isBound();
1021
1022 auto incubatorPriv = QQmlIncubatorPrivate::get(this);
1023 if (incubatorPriv->hadTopLevelRequiredProperties()) {
1024 // If we have required properties, we clear the context object
1025 // so that the model role names are not polluting the context.
1026 // Unless the context is bound, in which case we have never set the context object.
1027 if (incubating && !isBound) {
1028 Q_ASSERT(incubating->contextData());
1029 incubating->contextData()->setContextObject(nullptr);
1030 }
1031 if (proxyContext) {
1032 proxyContext->setContextObject(nullptr);
1033 }
1034
1035 // Retrieve the metaObject before the potential return so that the accessors have a chance
1036 // to perform some finalization in case they produce a dynamic metaobject. Here we know for
1037 // sure that we are using required properties.
1038 const QMetaObject *qmlMetaObject = modelItemToIncubate->metaObject();
1039
1040 RequiredProperties *requiredProperties = incubatorPriv->requiredProperties();
1041 if (requiredProperties->empty())
1042 return;
1043
1044 const RequiredPropertiesInitializer initializer(
1045 QQmlEnginePrivate::get(incubatorPriv->enginePriv),
1046 object, requiredProperties, access);
1047
1048 // if a required property was not in the model, it might still be a static property of the
1049 // QQmlDelegateModelItem or one of its derived classes this is the case for index, row,
1050 // column, model and more
1051 // the most derived subclasses of QQmlDelegateModelItem are QQmlDMAbstractItemModelData and
1052 // QQmlDMObjectData at depth 2, so 4 should be plenty
1053
1054 // we first check the dynamic meta object for properties originating from the model
1055 // contains abstractitemmodelproperties
1056 initializer(qmlMetaObject, modelItemToIncubate);
1057
1058 auto delegateModelItemSubclassMO = qmlMetaObject->superClass();
1059 initializer(delegateModelItemSubclassMO, modelItemToIncubate);
1060
1061 while (strcmp(delegateModelItemSubclassMO->className(),
1062 modelItemToIncubate->staticMetaObject.className())) {
1063 delegateModelItemSubclassMO = delegateModelItemSubclassMO->superClass();
1064 initializer(delegateModelItemSubclassMO, modelItemToIncubate);
1065 }
1066
1067 if (proxiedObject)
1068 initializer(proxiedObject->metaObject(), proxiedObject.data());
1069
1070 } else {
1071 // To retain compatibility, we cannot enable structured model data if the data is passed
1072 // via context properties.
1073 modelItemToIncubate->disableStructuredModelData();
1074
1075 if (!isBound)
1076 modelItemToIncubate->contextData()->setContextObject(modelItemToIncubate);
1077 if (proxiedObject)
1078 proxyContext->setContextObject(proxiedObject);
1079
1080 // Retrieve the metaObject() once so that the accessors have a chance to perform some
1081 // finalization in case they produce a dynamic metaobject. For example, they might be
1082 // inclined to create a propertyCache now because there are no required properties and any
1083 // revisioned properties should be hidden after all. Here is the first time we know for
1084 // sure whether we are using context properties.
1085 modelItemToIncubate->metaObject();
1086 }
1087}
1088
1090{
1091 if (vdm) {
1092 vdm->incubatorStatusChanged(this, status);
1093 } else if (isDoneIncubating(status)) {
1094 Q_ASSERT(incubating);
1095 // The model was deleted from under our feet, cleanup ourselves
1096 incubating->destroyObject();
1097 incubating->deleteLater();
1098 }
1099}
1100
1102{
1103 Q_Q(QQmlDelegateModel);
1104 if (!incubationTask->isError())
1105 incubationTask->clear();
1106 m_finishedIncubating.append(incubationTask);
1109 QCoreApplication::postEvent(q, new QEvent(QEvent::User));
1110 }
1111}
1112
1113void QQmlDelegateModelPrivate::reuseItem(QQmlDelegateModelItem *item, int newModelIndex, int newGroups)
1114{
1115 Q_ASSERT(item->object());
1116
1117 // Update/reset which groups the item belongs to
1118 item->setGroups(newGroups);
1119
1120 // Update context property index (including row and column) on the delegate
1121 // item, and inform the application about it. For a list, the row is the same
1122 // as the index, and the column is always 0. We set alwaysEmit to true, to
1123 // force all bindings to be reevaluated, even if the index didn't change.
1124 const bool alwaysEmit = true;
1125 item->setModelIndex(newModelIndex, newModelIndex, 0, alwaysEmit);
1126
1127 // Notify the application that all 'dynamic'/role-based context data has
1128 // changed as well (their getter function will use the updated index).
1129 auto const itemAsList = QList<QQmlDelegateModelItem *>() << item;
1130 auto const updateAllRoles = QList<int>();
1131 m_adaptorModel.notify(itemAsList, newModelIndex, 1, updateAllRoles);
1132
1133 if (QQmlDelegateModelAttached *att = static_cast<QQmlDelegateModelAttached *>(
1134 qmlAttachedPropertiesObject<QQmlDelegateModel>(item->object(), false))) {
1135 // Update currentIndex of the attached DelegateModel object
1136 // to the index the item has in the cache.
1138 // emitChanges will emit both group-, and index changes to the application
1139 att->emitChanges();
1140 }
1141
1142 // Inform the view that the item is recycled. This will typically result
1143 // in the view updating its own attached delegate item properties.
1144 emit q_func()->itemReused(newModelIndex, item->object());
1145}
1146
1148{
1149 m_reusableItemsPool.drain(maxPoolTime, [this](QQmlDelegateModelItem *cacheItem){ destroyCacheItem(cacheItem); });
1150}
1151
1152void QQmlDelegateModel::drainReusableItemsPool(int maxPoolTime)
1153{
1154 d_func()->drainReusableItemsPool(maxPoolTime);
1155}
1156
1157int QQmlDelegateModel::poolSize()
1158{
1159 return d_func()->m_reusableItemsPool.size();
1160}
1161
1163{
1164 if (!m_delegateChooser)
1165 return m_delegate;
1166
1167 QQmlComponent *delegate = nullptr;
1168 QQmlAbstractDelegateComponent *chooser = m_delegateChooser;
1169
1170 do {
1171 delegate = chooser->delegate(&m_adaptorModel, index);
1172 chooser = qobject_cast<QQmlAbstractDelegateComponent *>(delegate);
1173 } while (chooser);
1174
1175 return delegate;
1176}
1177
1178void QQmlDelegateModelPrivate::addCacheItem(QQmlDelegateModelItem *item, Compositor::iterator it)
1179{
1180 m_cache.insert(it.cacheIndex(), item);
1181 m_compositor.setFlags(it, 1, Compositor::CacheFlag);
1182 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1183}
1184
1185void QQmlDelegateModelPrivate::removeCacheItem(QQmlDelegateModelItem *cacheItem)
1186{
1187 int cidx = m_cache.lastIndexOf(cacheItem);
1188 if (cidx >= 0) {
1189 m_compositor.clearFlags(Compositor::Cache, cidx, 1, Compositor::CacheFlag);
1190 m_cache.removeAt(cidx);
1191 }
1192 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1193}
1194
1195void QQmlDelegateModelPrivate::incubatorStatusChanged(QQDMIncubationTask *incubationTask, QQmlIncubator::Status status)
1196{
1197 if (!isDoneIncubating(status))
1198 return;
1199
1200 const QList<QQmlError> incubationTaskErrors = incubationTask->errors();
1201
1202 QQmlDelegateModelItem *cacheItem = incubationTask->incubating;
1203 cacheItem->clearIncubationTask();
1204 incubationTask->incubating = nullptr;
1205 releaseIncubator(incubationTask);
1206
1207 QObject *object = cacheItem->object();
1208 if (status == QQmlIncubator::Ready) {
1209 QQmlDelegateModelItem::ObjectReference guard(cacheItem);
1210 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
1211 emitCreatedPackage(incubationTask, package);
1212 else
1213 emitCreatedItem(incubationTask, object);
1214 } else if (status == QQmlIncubator::Error) {
1215 qmlInfo(m_delegate, incubationTaskErrors + m_delegate->errors()) << "Cannot create delegate";
1216 }
1217
1218 if (!cacheItem->isObjectReferenced()) {
1219 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
1221 else
1222 emitDestroyingItem(object);
1223 cacheItem->destroyObject();
1224
1225 if (!cacheItem->isScriptReferenced()) {
1226 removeCacheItem(cacheItem);
1227 delete cacheItem;
1228 }
1229 }
1230}
1231
1233{
1234 vdm->setInitialState(this, o);
1235}
1236
1238void QQmlDelegateModelGroupEmitter::createdPackage(int, QQuickPackage *) {}
1239void QQmlDelegateModelGroupEmitter::initPackage(int, QQuickPackage *) {}
1241
1243{
1244 QQmlDelegateModelItem *cacheItem = incubationTask->incubating;
1245 incubationTask->initializeRequiredProperties(
1246 incubationTask->incubating, o, m_adaptorModel.delegateModelAccess);
1247 cacheItem->setObject(o);
1248
1249 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(o))
1250 emitInitPackage(incubationTask, package);
1251 else
1252 emitInitItem(incubationTask, o);
1253}
1254
1255QObject *QQmlDelegateModelPrivate::object(Compositor::Group group, int index, QQmlIncubator::IncubationMode incubationMode)
1256{
1257 if (!m_delegate || index < 0 || index >= m_compositor.count(group)) {
1258 qWarning() << "DelegateModel::item: index out range" << index << m_compositor.count(group);
1259 return nullptr;
1260 } else if (!m_context || !m_context->isValid()) {
1261 return nullptr;
1262 }
1263
1264 Compositor::iterator it = m_compositor.find(group, index);
1265 const auto flags = it->flags;
1266 const auto modelIndex = it.modelIndex();
1267
1268 QQmlDelegateModelItem *cacheItem = it->inCache() ? m_cache.at(it.cacheIndex()) : 0;
1269
1270 if (!cacheItem || !cacheItem->delegate()) {
1271 QQmlComponent *delegate = resolveDelegate(modelIndex);
1272 if (!delegate)
1273 return nullptr;
1274
1275 if (!cacheItem) {
1276 cacheItem = m_reusableItemsPool.takeItem(delegate, index);
1277 if (cacheItem) {
1278 // Move the pooled item back into the cache, update
1279 // all related properties, and return the object (which
1280 // has already been incubated, otherwise it wouldn't be in the pool).
1281 addCacheItem(cacheItem, it);
1282 reuseItem(cacheItem, index, flags);
1283
1284 if (index == m_compositor.count(group) - 1)
1286 return cacheItem->referenceObjectWeak();
1287 }
1288
1289 // Since we could't find an available item in the pool, we create a new one
1290 cacheItem = m_adaptorModel.createItem(m_cacheMetaType, modelIndex);
1291 if (!cacheItem)
1292 return nullptr;
1293
1294 cacheItem->setGroups(flags);
1295 addCacheItem(cacheItem, it);
1296 }
1297
1298 cacheItem->setDelegate(delegate);
1299 }
1300
1301 {
1302 // Bump the reference counts temporarily so neither the content data or the delegate object
1303 // are deleted if incubatorStatusChanged() is called synchronously.
1304 QQmlDelegateModelItem::ScriptReference scriptRef(cacheItem);
1305 QQmlDelegateModelItem::ObjectReference objectRef(cacheItem);
1306
1307 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
1308 bool sync = (incubationMode == QQmlIncubator::Synchronous
1309 || incubationMode == QQmlIncubator::AsynchronousIfNested);
1310 if (sync && incubationTask->incubationMode() == QQmlIncubator::Asynchronous) {
1311 // previously requested async - now needed immediately
1312 incubationTask->forceCompletion();
1313 }
1314 } else if (!cacheItem->object()) {
1315 QQmlContext *creationContext = cacheItem->delegate()->creationContext();
1316
1317 QQDMIncubationTask *incubationTask = new QQDMIncubationTask(this, incubationMode);
1318 cacheItem->setIncubationTask(incubationTask);
1319 incubationTask->incubating = cacheItem;
1320 incubationTask->clear();
1321
1322 for (int i = 1; i < m_groupCount; ++i)
1323 incubationTask->index[i] = it.index[i];
1324
1325 const QQmlRefPointer<QQmlContextData> componentContext
1326 = QQmlContextData::get(creationContext ? creationContext : m_context.data());
1327 QQmlComponentPrivate *cp = QQmlComponentPrivate::get(cacheItem->delegate());
1328
1329 if (cp->isBound()) {
1330 cacheItem->setContextData(componentContext);
1331
1332 // Ignore return value of initProxy. We want to know the proxy when assigning required
1333 // properties, but we don't want it to pollute our context. The context is bound.
1334 if (m_adaptorModel.hasProxyObject())
1335 cacheItem->initProxy();
1336
1337 cp->incubateObject(
1338 incubationTask, cacheItem->delegate(), m_context->engine(),
1339 componentContext, QQmlContextData::get(m_context));
1340 } else {
1341 QQmlRefPointer<QQmlContextData> ctxt
1342 = QQmlContextData::createRefCounted(componentContext);
1343 ctxt->setContextObject(cacheItem);
1344 cacheItem->setContextData(ctxt);
1345
1346 // If the model is read-only we cannot just expose the object as context
1347 // We actually need a separate model object to moderate access.
1348 if (m_adaptorModel.hasProxyObject()) {
1349 if (m_adaptorModel.delegateModelAccess == QQmlDelegateModel::ReadOnly)
1350 cacheItem->initProxy();
1351 else
1352 ctxt = cacheItem->initProxy();
1353 }
1354
1355 cp->incubateObject(
1356 cacheItem->incubationTask(), cacheItem->delegate(), m_context->engine(),
1357 ctxt, QQmlContextData::get(m_context));
1358 }
1359 }
1360
1361 if (index == m_compositor.count(group) - 1)
1363
1364
1365 if (cacheItem->object()) {
1366 QQDMIncubationTask *incubationTask = cacheItem->incubationTask();
1367 if (!incubationTask || isDoneIncubating(incubationTask->status()))
1368 return cacheItem->referenceObjectWeak();
1369 }
1370 }
1371
1372 if (!cacheItem->isScriptReferenced()) {
1373
1374 // If it had an object and no incubationTask we would have returned above.
1375 // If it had an incubationTask it would be referenced, no matter if it has an object.
1376 Q_ASSERT(!cacheItem->object());
1377
1378 removeCacheItem(cacheItem);
1379 delete cacheItem;
1380 }
1381
1382 return nullptr;
1383}
1384
1385/*
1386 If asynchronous is true or the component is being loaded asynchronously due
1387 to an ancestor being loaded asynchronously, object() may return 0. In this
1388 case createdItem() will be emitted when the object is available. The object
1389 at this stage does not have any references, so object() must be called again
1390 to ensure a reference is held. Any call to object() which returns a valid object
1391 must be matched by a call to release() in order to destroy the object.
1392*/
1393QObject *QQmlDelegateModel::object(int index, QQmlIncubator::IncubationMode incubationMode)
1394{
1395 Q_D(QQmlDelegateModel);
1396 if (!d->m_delegate || index < 0 || index >= d->m_compositor.count(d->m_compositorGroup)) {
1397 qWarning() << "DelegateModel::item: index out range" << index << d->m_compositor.count(d->m_compositorGroup);
1398 return nullptr;
1399 }
1400
1401 return d->object(d->m_compositorGroup, index, incubationMode);
1402}
1403
1404QQmlIncubator::Status QQmlDelegateModel::incubationStatus(int index)
1405{
1406 Q_D(QQmlDelegateModel);
1407 if (d->m_compositor.count(d->m_compositorGroup) <= index)
1408 return QQmlIncubator::Null;
1409 Compositor::iterator it = d->m_compositor.find(d->m_compositorGroup, index);
1410 if (!it->inCache())
1411 return QQmlIncubator::Null;
1412
1413 if (auto incubationTask = d->m_cache.at(it.cacheIndex())->incubationTask())
1414 return incubationTask->status();
1415
1416 return QQmlIncubator::Ready;
1417}
1418
1419QVariant QQmlDelegateModelPrivate::variantValue(QQmlListCompositor::Group group, int index, const QString &name)
1420{
1421 Compositor::iterator it = m_compositor.find(group, index);
1422 if (QQmlAdaptorModel *model = it.list<QQmlAdaptorModel>()) {
1423 QString role = name;
1424 int dot = name.indexOf(QLatin1Char('.'));
1425 if (dot > 0)
1426 role = name.left(dot);
1427 QVariant value = model->value(it.modelIndex(), role);
1428 while (dot > 0) {
1429 const int from = dot + 1;
1430 dot = name.indexOf(QLatin1Char('.'), from);
1431 QStringView propertyName = QStringView{name}.mid(from, dot - from);
1432 if (QObject *obj = qvariant_cast<QObject*>(value)) {
1433 value = obj->property(propertyName.toUtf8());
1434 } else if (const QMetaObject *metaObject = QQmlMetaType::metaObjectForValueType(value.metaType())) {
1435 // Q_GADGET
1436 const int propertyIndex = metaObject->indexOfProperty(propertyName.toUtf8());
1437 if (propertyIndex >= 0)
1438 value = metaObject->property(propertyIndex).readOnGadget(value.constData());
1439 } else {
1440 return QVariant();
1441 }
1442 }
1443 return value;
1444 }
1445 return QVariant();
1446}
1447
1448QVariant QQmlDelegateModel::variantValue(int index, const QString &role)
1449{
1450 Q_D(QQmlDelegateModel);
1451 return d->variantValue(d->m_compositorGroup, index, role);
1452}
1453
1454int QQmlDelegateModel::indexOf(QObject *item, QObject *) const
1455{
1456 Q_D(const QQmlDelegateModel);
1457 if (QQmlDelegateModelItem *cacheItem = QQmlDelegateModelItem::dataForObject(item))
1458 return cacheItem->groupIndex(d->m_compositorGroup);
1459 return -1;
1460}
1461
1462void QQmlDelegateModel::setWatchedRoles(const QList<QByteArray> &roles)
1463{
1464 Q_D(QQmlDelegateModel);
1465 d->m_adaptorModel.replaceWatchedRoles(d->m_watchedRoles, roles);
1466 d->m_watchedRoles = roles;
1467}
1468
1470 Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
1471{
1472 QList<Compositor::Insert> inserts;
1473 m_compositor.setFlags(from, count, group, groupFlags, &inserts);
1474 itemsInserted(inserts);
1476}
1477
1479 Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
1480{
1481 QList<Compositor::Remove> removes;
1482 m_compositor.clearFlags(from, count, group, groupFlags, &removes);
1483 itemsRemoved(removes);
1485}
1486
1488 Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
1489{
1490 QList<Compositor::Remove> removes;
1491 QList<Compositor::Insert> inserts;
1492
1493 m_compositor.setFlags(from, count, group, groupFlags, &inserts);
1494 itemsInserted(inserts);
1495 const int removeFlags = ~groupFlags & Compositor::GroupMask;
1496
1497 from = m_compositor.find(from.group, from.index[from.group]);
1498 m_compositor.clearFlags(from, count, group, removeFlags, &removes);
1499 itemsRemoved(removes);
1501}
1502
1503bool QQmlDelegateModel::event(QEvent *e)
1504{
1505 Q_D(QQmlDelegateModel);
1506 if (e->type() == QEvent::UpdateRequest) {
1507 d->m_waitingToFetchMore = false;
1508 d->m_adaptorModel.fetchMore();
1509 } else if (e->type() == QEvent::User) {
1510 d->m_incubatorCleanupScheduled = false;
1511 qDeleteAll(d->m_finishedIncubating);
1512 d->m_finishedIncubating.clear();
1513 }
1514 return QQmlInstanceModel::event(e);
1515}
1516
1517void QQmlDelegateModelPrivate::itemsChanged(const QList<Compositor::Change> &changes)
1518{
1519 if (!m_delegate)
1520 return;
1521
1522 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> translatedChanges(m_groupCount);
1523
1524 for (const Compositor::Change &change : changes) {
1525 for (int i = 1; i < m_groupCount; ++i) {
1526 if (change.inGroup(i)) {
1527 translatedChanges[i].append(QQmlChangeSet::Change(change.index[i], change.count));
1528 }
1529 }
1530 }
1531
1532 for (int i = 1; i < m_groupCount; ++i)
1533 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.change(translatedChanges.at(i));
1534}
1535
1536void QQmlDelegateModel::_q_itemsChanged(int index, int count, const QList<int> &roles)
1537{
1538 Q_D(QQmlDelegateModel);
1539 if (count <= 0 || !d->m_complete)
1540 return;
1541
1542 if (d->m_adaptorModel.notify(d->m_cache, index, count, roles)) {
1543 QList<Compositor::Change> changes;
1544 d->m_compositor.listItemsChanged(&d->m_adaptorModel, index, count, &changes);
1545 d->itemsChanged(changes);
1546 d->emitChanges();
1547 }
1548 const bool needToCheckDelegateChoiceInvalidation = d->m_delegateChooser && !roles.isEmpty();
1549 if (!needToCheckDelegateChoiceInvalidation)
1550 return;
1551
1552 // here, we only really can handle AIM based models, because only there
1553 // we can do something sensible with roles
1554 if (!d->m_adaptorModel.adaptsAim())
1555 return;
1556
1557 const auto aim = d->m_adaptorModel.aim();
1558 const auto choiceRole = d->m_delegateChooser->role().toUtf8();
1559 const auto &roleNames = aim->roleNames();
1560 auto it = std::find_if(roles.begin(), roles.end(), [&](int role) {
1561 return roleNames[role] == choiceRole;
1562 });
1563 if (it == roles.end())
1564 return;
1565
1566 // Compare handleModelReset - we're doing a more localized version
1567
1568 /* A role change affecting the DelegateChoice is equivalent to removing all
1569 affected items (including invalidating their cache entries) and afterwards
1570 reinserting them.
1571 */
1572 QList<Compositor::Remove> removes;
1573 QList<Compositor::Insert> inserts;
1574 d->m_compositor.listItemsRemoved(&d->m_adaptorModel, index, count, &removes);
1575 {
1576 const QList<QQmlDelegateModelItem *> cache = d->m_cache;
1577 QQmlDelegateModelItem::ObjectSpanReference guard(cache);
1578 for (const auto &removed: std::as_const(removes)) {
1579 if (!d->m_cache.isSharedWith(cache))
1580 break;
1581 QQmlDelegateModelItem *item = cache.value(removed.cacheIndex(), nullptr);
1582 if (!d->m_cache.contains(item))
1583 continue;
1584 if (item->modelIndex() != -1)
1585 item->setModelIndex(-1, -1, -1);
1586 }
1587 }
1588 d->m_compositor.listItemsInserted(&d->m_adaptorModel, index, count, &inserts);
1589 d->itemsMoved(removes, inserts);
1590 d->emitChanges();
1591}
1592
1593static void incrementIndexes(QQmlDelegateModelItem *cacheItem, int count, const int *deltas)
1594{
1595 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
1596 for (int i = 1; i < count; ++i)
1597 incubationTask->index[i] += deltas[i];
1598 }
1599 if (QQmlDelegateModelAttached *attached = cacheItem->attached()) {
1600 for (int i = 1; i < qMin<int>(count, Compositor::MaximumGroupCount); ++i)
1601 attached->m_currentIndex[i] += deltas[i];
1602 }
1603}
1604
1606 const QList<Compositor::Insert> &inserts,
1607 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> *translatedInserts,
1608 QHash<int, QList<QQmlDelegateModelItem *> > *movedItems)
1609{
1610 int cacheIndex = 0;
1611
1612 int inserted[Compositor::MaximumGroupCount];
1613 for (int i = 1; i < m_groupCount; ++i)
1614 inserted[i] = 0;
1615
1616 for (const Compositor::Insert &insert : inserts) {
1617 for (; cacheIndex < insert.cacheIndex(); ++cacheIndex)
1618 incrementIndexes(m_cache.at(cacheIndex), m_groupCount, inserted);
1619
1620 for (int i = 1; i < m_groupCount; ++i) {
1621 if (insert.inGroup(i)) {
1622 (*translatedInserts)[i].append(
1623 QQmlChangeSet::Change(insert.index[i], insert.count, insert.moveId));
1624 inserted[i] += insert.count;
1625 }
1626 }
1627
1628 if (!insert.inCache())
1629 continue;
1630
1631 if (movedItems && insert.isMove()) {
1632 QList<QQmlDelegateModelItem *> items = movedItems->take(insert.moveId);
1633 Q_ASSERT(items.size() == insert.count);
1634 m_cache = m_cache.mid(0, insert.cacheIndex())
1635 + items + m_cache.mid(insert.cacheIndex());
1636 }
1637 if (insert.inGroup()) {
1638 for (int offset = 0; cacheIndex < insert.cacheIndex() + insert.count;
1639 ++cacheIndex, ++offset) {
1640 QQmlDelegateModelItem *cacheItem = m_cache.at(cacheIndex);
1641 cacheItem->addGroups(insert.flags & Compositor::GroupMask);
1642
1643 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
1644 for (int i = 1; i < m_groupCount; ++i)
1645 incubationTask->index[i] = cacheItem->groups() & (1 << i)
1646 ? insert.index[i] + offset
1647 : insert.index[i];
1648 }
1649 if (QQmlDelegateModelAttached *attached = cacheItem->attached()) {
1650 for (int i = 1; i < m_groupCount; ++i)
1651 attached->m_currentIndex[i] = cacheItem->groups() & (1 << i)
1652 ? insert.index[i] + offset
1653 : insert.index[i];
1654 }
1655 }
1656 } else {
1657 cacheIndex = insert.cacheIndex() + insert.count;
1658 }
1659 }
1660 for (const QList<QQmlDelegateModelItem *> cache = m_cache; cacheIndex < cache.size(); ++cacheIndex)
1661 incrementIndexes(cache.at(cacheIndex), m_groupCount, inserted);
1662}
1663
1664void QQmlDelegateModelPrivate::itemsInserted(const QList<Compositor::Insert> &inserts)
1665{
1666 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> translatedInserts(m_groupCount);
1667 itemsInserted(inserts, &translatedInserts);
1668 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1669 if (!m_delegate)
1670 return;
1671
1672 for (int i = 1; i < m_groupCount; ++i)
1673 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.insert(translatedInserts.at(i));
1674}
1675
1676void QQmlDelegateModel::_q_itemsInserted(int index, int count)
1677{
1678
1679 Q_D(QQmlDelegateModel);
1680 if (count <= 0 || !d->m_complete)
1681 return;
1682
1683 d->m_count += count;
1684
1685 const QList<QQmlDelegateModelItem *> cache = d->m_cache;
1686 for (int i = 0, c = cache.size(); i < c; ++i) {
1687 QQmlDelegateModelItem *item = cache.at(i);
1688 // layout change triggered by changing the modelIndex might have
1689 // already invalidated this item in d->m_cache and deleted it.
1690 if (!d->m_cache.isSharedWith(cache) && !d->m_cache.contains(item))
1691 continue;
1692
1693 if (item->modelIndex() >= index) {
1694 const int newIndex = item->modelIndex() + count;
1695 const int row = newIndex;
1696 const int column = 0;
1697 item->setModelIndex(newIndex, row, column);
1698 }
1699 }
1700
1701 QList<Compositor::Insert> inserts;
1702 d->m_compositor.listItemsInserted(&d->m_adaptorModel, index, count, &inserts);
1703 d->itemsInserted(inserts);
1704 d->emitChanges();
1705}
1706
1707//### This method should be split in two. It will remove delegates, and it will re-render the list.
1708// When e.g. QQmlListModel::remove is called, the removal of the delegates should be done on
1709// QAbstractItemModel::rowsAboutToBeRemoved, and the re-rendering on
1710// QAbstractItemModel::rowsRemoved. Currently both are done on the latter signal. The problem is
1711// that the destruction of an item will emit a changed signal that ends up at the delegate, which
1712// in turn will try to load the data from the model (which should have already freed it), resulting
1713// in a use-after-free. See QTBUG-59256.
1715 const QList<Compositor::Remove> &removes,
1716 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> *translatedRemoves,
1717 QHash<int, QList<QQmlDelegateModelItem *> > *movedItems)
1718{
1719 int cacheIndex = 0;
1720 int removedCache = 0;
1721
1722 int removed[Compositor::MaximumGroupCount];
1723 for (int i = 1; i < m_groupCount; ++i)
1724 removed[i] = 0;
1725
1726 for (const Compositor::Remove &remove : removes) {
1727 for (; cacheIndex < remove.cacheIndex() && cacheIndex < m_cache.size(); ++cacheIndex)
1728 incrementIndexes(m_cache.at(cacheIndex), m_groupCount, removed);
1729
1730 for (int i = 1; i < m_groupCount; ++i) {
1731 if (remove.inGroup(i)) {
1732 (*translatedRemoves)[i].append(
1733 QQmlChangeSet::Change(remove.index[i], remove.count, remove.moveId));
1734 removed[i] -= remove.count;
1735 }
1736 }
1737
1738 if (!remove.inCache())
1739 continue;
1740
1741 if (movedItems && remove.isMove()) {
1742 movedItems->insert(remove.moveId, m_cache.mid(remove.cacheIndex(), remove.count));
1743 QList<QQmlDelegateModelItem *>::const_iterator begin = m_cache.constBegin() + remove.cacheIndex();
1744 QList<QQmlDelegateModelItem *>::const_iterator end = begin + remove.count;
1745 m_cache.erase(begin, end);
1746 } else {
1747 for (; cacheIndex < remove.cacheIndex() + remove.count - removedCache; ++cacheIndex) {
1748 QQmlDelegateModelItem *cacheItem = m_cache.at(cacheIndex);
1749 if (remove.inGroup(Compositor::Persisted)
1750 && cacheItem->objectStrongRef() == 0
1751 && cacheItem->objectWeakRef() == 0
1752 && cacheItem->object()) {
1753 QObject *object = cacheItem->object();
1754 cacheItem->destroyObjectLater();
1755 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
1756 emitDestroyingPackage(package);
1757 else
1758 emitDestroyingItem(object);
1759 }
1760 if (!cacheItem->isScriptReferenced()
1761 && !cacheItem->object()
1762 && !remove.inGroup(Compositor::Persisted)) {
1763 m_compositor.clearFlags(Compositor::Cache, cacheIndex, 1, Compositor::CacheFlag);
1764 m_cache.removeAt(cacheIndex);
1765 delete cacheItem;
1766 --cacheIndex;
1767 ++removedCache;
1768 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1769 } else if (remove.groups() == cacheItem->groups()) {
1770 cacheItem->setGroups(0);
1771 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
1772 for (int i = 1; i < m_groupCount; ++i)
1773 incubationTask->index[i] = -1;
1774 }
1775 if (QQmlDelegateModelAttached *attached = cacheItem->attached()) {
1776 for (int i = 1; i < m_groupCount; ++i)
1777 attached->m_currentIndex[i] = -1;
1778 }
1779 } else {
1780 if (QQDMIncubationTask *incubationTask = cacheItem->incubationTask()) {
1781 if (!cacheItem->isObjectReferenced()) {
1782 releaseIncubator(incubationTask);
1783 cacheItem->clearIncubationTask();
1784 if (QObject *object = cacheItem->object()) {
1785 cacheItem->destroyObjectLater();
1786 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
1787 emitDestroyingPackage(package);
1788 else
1789 emitDestroyingItem(object);
1790 }
1791 } else {
1792 for (int i = 1; i < m_groupCount; ++i) {
1793 if (remove.inGroup(i))
1794 incubationTask->index[i] = remove.index[i];
1795 }
1796 }
1797 }
1798 if (QQmlDelegateModelAttached *attached = cacheItem->attached()) {
1799 for (int i = 1; i < m_groupCount; ++i) {
1800 if (remove.inGroup(i))
1801 attached->m_currentIndex[i] = remove.index[i];
1802 }
1803 }
1804 cacheItem->removeGroups(remove.flags);
1805 }
1806 }
1807 }
1808 }
1809
1810 for (const QList<QQmlDelegateModelItem *> cache = m_cache; cacheIndex < cache.size(); ++cacheIndex)
1811 incrementIndexes(cache.at(cacheIndex), m_groupCount, removed);
1812}
1813
1814void QQmlDelegateModelPrivate::itemsRemoved(const QList<Compositor::Remove> &removes)
1815{
1816 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> translatedRemoves(m_groupCount);
1817 itemsRemoved(removes, &translatedRemoves);
1818 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1819 if (!m_delegate)
1820 return;
1821
1822 for (int i = 1; i < m_groupCount; ++i)
1823 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.remove(translatedRemoves.at(i));
1824}
1825
1826void QQmlDelegateModel::_q_itemsRemoved(int index, int count)
1827{
1828 Q_D(QQmlDelegateModel);
1829 if (count <= 0|| !d->m_complete)
1830 return;
1831
1832 d->m_count -= count;
1833 Q_ASSERT(d->m_count >= 0);
1834
1835 {
1836 const QList<QQmlDelegateModelItem *> cache = d->m_cache;
1837
1838 //Prevents items being deleted in remove loop
1839 QQmlDelegateModelItem::ObjectSpanReference guard(cache);
1840
1841 for (int i = 0, c = cache.size(); i < c; ++i) {
1842 QQmlDelegateModelItem *item = cache.at(i);
1843 // layout change triggered by removal of a previous item might have
1844 // already invalidated this item in d->m_cache and deleted it
1845 if (!d->m_cache.isSharedWith(cache) && !d->m_cache.contains(item))
1846 continue;
1847
1848 if (item->modelIndex() >= index + count) {
1849 const int newIndex = item->modelIndex() - count;
1850 const int row = newIndex;
1851 const int column = 0;
1852 item->setModelIndex(newIndex, row, column);
1853 } else if (item->modelIndex() >= index) {
1854 item->setModelIndex(-1, -1, -1);
1855 }
1856 }
1857 }
1858
1859 QList<Compositor::Remove> removes;
1860 d->m_compositor.listItemsRemoved(&d->m_adaptorModel, index, count, &removes);
1861 d->itemsRemoved(removes);
1862
1863 d->emitChanges();
1864}
1865
1867 const QList<Compositor::Remove> &removes, const QList<Compositor::Insert> &inserts)
1868{
1869 QHash<int, QList<QQmlDelegateModelItem *> > movedItems;
1870
1871 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> translatedRemoves(m_groupCount);
1872 itemsRemoved(removes, &translatedRemoves, &movedItems);
1873
1874 QVarLengthArray<QList<QQmlChangeSet::Change>, Compositor::MaximumGroupCount> translatedInserts(m_groupCount);
1875 itemsInserted(inserts, &translatedInserts, &movedItems);
1876 Q_ASSERT(m_cache.size() == m_compositor.count(Compositor::Cache));
1877 Q_ASSERT(movedItems.isEmpty());
1878 if (!m_delegate)
1879 return;
1880
1881 for (int i = 1; i < m_groupCount; ++i) {
1882 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.move(
1883 translatedRemoves.at(i),
1884 translatedInserts.at(i));
1885 }
1886}
1887
1888void QQmlDelegateModel::_q_itemsMoved(int from, int to, int count)
1889{
1890 Q_D(QQmlDelegateModel);
1891 if (count <= 0 || !d->m_complete)
1892 return;
1893
1894 const int minimum = qMin(from, to);
1895 const int maximum = qMax(from, to) + count;
1896 const int difference = from > to ? count : -count;
1897
1898 const QList<QQmlDelegateModelItem *> cache = d->m_cache;
1899 for (int i = 0, c = cache.size(); i < c; ++i) {
1900 QQmlDelegateModelItem *item = cache.at(i);
1901 // layout change triggered by changing the modelIndex might have
1902 // already invalidated this item in d->m_cache and deleted it.
1903 if (!d->m_cache.isSharedWith(cache) && !d->m_cache.contains(item))
1904 continue;
1905
1906 if (item->modelIndex() >= from && item->modelIndex() < from + count) {
1907 const int newIndex = item->modelIndex() - from + to;
1908 const int row = newIndex;
1909 const int column = 0;
1910 item->setModelIndex(newIndex, row, column);
1911 } else if (item->modelIndex() >= minimum && item->modelIndex() < maximum) {
1912 const int newIndex = item->modelIndex() + difference;
1913 const int row = newIndex;
1914 const int column = 0;
1915 item->setModelIndex(newIndex, row, column);
1916 }
1917 }
1918
1919 QList<Compositor::Remove> removes;
1920 QList<Compositor::Insert> inserts;
1921 d->m_compositor.listItemsMoved(&d->m_adaptorModel, from, to, count, &removes, &inserts);
1922 d->itemsMoved(removes, inserts);
1923 d->emitChanges();
1924}
1925
1926void QQmlDelegateModelPrivate::emitModelUpdated(const QQmlChangeSet &changeSet, bool reset)
1927{
1928 Q_Q(QQmlDelegateModel);
1929 emit q->modelUpdated(changeSet, reset);
1930 if (changeSet.difference() != 0)
1931 emit q->countChanged();
1932}
1933
1934void QQmlDelegateModelPrivate::delegateChanged(bool add, bool remove)
1935{
1936 Q_Q(QQmlDelegateModel);
1937 if (!m_complete)
1938 return;
1939
1940 if (m_transaction) {
1941 qmlWarning(q) << QQmlDelegateModel::tr("The delegates of a DelegateModel cannot be changed within onUpdated.");
1942 return;
1943 }
1944
1945 if (remove) {
1946 for (int i = 1; i < m_groupCount; ++i) {
1947 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.remove(
1948 0, m_compositor.count(Compositor::Group(i)));
1949 }
1950 }
1951 if (add) {
1952 for (int i = 1; i < m_groupCount; ++i) {
1953 QQmlDelegateModelGroupPrivate::get(m_groups[i])->changeSet.insert(
1954 0, m_compositor.count(Compositor::Group(i)));
1955 }
1956 }
1958}
1959
1961{
1962 if (m_transaction || !m_complete || !m_context || !m_context->isValid())
1963 return;
1964
1965 m_transaction = true;
1966 QV4::ExecutionEngine *engine = m_context->engine()->handle();
1967 for (int i = 1; i < m_groupCount; ++i)
1968 QQmlDelegateModelGroupPrivate::get(m_groups[i])->emitChanges(engine);
1969 m_transaction = false;
1970
1971 const bool reset = m_reset;
1972 m_reset = false;
1973 for (int i = 1; i < m_groupCount; ++i)
1974 QQmlDelegateModelGroupPrivate::get(m_groups[i])->emitModelUpdated(reset);
1975
1976 // emitChanges may alter m_cache and delete items
1977 QVarLengthArray<QPointer<QQmlDelegateModelAttached>> attachedObjects;
1978 attachedObjects.reserve(m_cache.length());
1979 for (const QQmlDelegateModelItem *cacheItem : std::as_const(m_cache))
1980 attachedObjects.append(cacheItem->attached());
1981
1982 for (const QPointer<QQmlDelegateModelAttached> &attached : std::as_const(attachedObjects)) {
1983 if (attached && attached->m_cacheItem)
1984 attached->emitChanges();
1985 }
1986}
1987
1988void QQmlDelegateModel::_q_modelAboutToBeReset()
1989{
1990 Q_D(QQmlDelegateModel);
1991 if (!d->m_adaptorModel.adaptsAim())
1992 return;
1993 auto aim = d->m_adaptorModel.aim();
1994 auto oldRoleNames = aim->roleNames();
1995 // this relies on the fact that modelAboutToBeReset must be followed
1996 // by a modelReset signal before any further modelAboutToBeReset can occur
1997 QObject::connect(aim, &QAbstractItemModel::modelReset, this, [this, d, oldRoleNames, aim](){
1998 if (!d->m_adaptorModel.adaptsAim() || d->m_adaptorModel.aim() != aim)
1999 return;
2000 if (oldRoleNames == aim->roleNames()) {
2001 // if the rolenames stayed the same (most common case), then we don't have
2002 // to throw away all the setup that we did
2003 handleModelReset();
2004 } else {
2005 // If they did change, we give up and just start from scratch via setModel
2006 QVariant m = model();
2007 setModel(QVariant());
2008 setModel(m);
2009 // but we still have to call handleModelReset, otherwise views will
2010 // not refresh
2011 handleModelReset();
2012 }
2013 }, Qt::SingleShotConnection);
2014}
2015
2016void QQmlDelegateModel::handleModelReset()
2017{
2018 Q_D(QQmlDelegateModel);
2019 if (!d->m_delegate)
2020 return;
2021
2022 int oldCount = d->m_count;
2023 d->m_adaptorModel.rootIndex = QModelIndex();
2024
2025 if (d->m_complete) {
2026 d->m_count = d->adaptorModelCount();
2027
2028 {
2029 const QList<QQmlDelegateModelItem *> cache = d->m_cache;
2030 QQmlDelegateModelItem::ObjectSpanReference guard(cache);
2031
2032 for (int i = 0, c = cache.size(); i < c; ++i) {
2033 QQmlDelegateModelItem *item = cache.at(i);
2034 // layout change triggered by changing the modelIndex might have
2035 // already invalidated this item in d->m_cache and deleted it.
2036 if (!d->m_cache.isSharedWith(cache) && !d->m_cache.contains(item))
2037 continue;
2038
2039 if (item->modelIndex() != -1)
2040 item->setModelIndex(-1, -1, -1);
2041 }
2042 }
2043
2044 QList<Compositor::Remove> removes;
2045 QList<Compositor::Insert> inserts;
2046 if (oldCount)
2047 d->m_compositor.listItemsRemoved(&d->m_adaptorModel, 0, oldCount, &removes);
2048 if (d->m_count)
2049 d->m_compositor.listItemsInserted(&d->m_adaptorModel, 0, d->m_count, &inserts);
2050 d->itemsMoved(removes, inserts);
2051 d->m_reset = true;
2052
2053 if (d->m_adaptorModel.canFetchMore())
2054 d->m_adaptorModel.fetchMore();
2055
2056 d->emitChanges();
2057 }
2058 emit rootIndexChanged();
2059}
2060
2061void QQmlDelegateModel::_q_rowsInserted(const QModelIndex &parent, int begin, int end)
2062{
2063 Q_D(QQmlDelegateModel);
2064 if (parent == d->m_adaptorModel.rootIndex)
2065 _q_itemsInserted(begin, end - begin + 1);
2066}
2067
2068void QQmlDelegateModel::_q_rowsAboutToBeRemoved(const QModelIndex &parent, int begin, int end)
2069{
2070 Q_D(QQmlDelegateModel);
2071 if (!d->m_adaptorModel.rootIndex.isValid())
2072 return;
2073 const QModelIndex index = d->m_adaptorModel.rootIndex;
2074 if (index.parent() == parent && index.row() >= begin && index.row() <= end) {
2075 const int oldCount = d->m_count;
2076 d->m_count = 0;
2077 d->disconnectFromAbstractItemModel();
2078 d->m_adaptorModel.invalidateModel();
2079
2080 if (d->m_complete && oldCount > 0) {
2081 QList<Compositor::Remove> removes;
2082 d->m_compositor.listItemsRemoved(&d->m_adaptorModel, 0, oldCount, &removes);
2083 d->itemsRemoved(removes);
2084 d->emitChanges();
2085 }
2086 }
2087}
2088
2089void QQmlDelegateModel::_q_rowsRemoved(const QModelIndex &parent, int begin, int end)
2090{
2091 Q_D(QQmlDelegateModel);
2092 if (parent == d->m_adaptorModel.rootIndex)
2093 _q_itemsRemoved(begin, end - begin + 1);
2094}
2095
2096void QQmlDelegateModel::_q_rowsMoved(
2097 const QModelIndex &sourceParent, int sourceStart, int sourceEnd,
2098 const QModelIndex &destinationParent, int destinationRow)
2099{
2100 Q_D(QQmlDelegateModel);
2101 const int count = sourceEnd - sourceStart + 1;
2102 if (destinationParent == d->m_adaptorModel.rootIndex && sourceParent == d->m_adaptorModel.rootIndex) {
2103 _q_itemsMoved(sourceStart, sourceStart > destinationRow ? destinationRow : destinationRow - count, count);
2104 } else if (sourceParent == d->m_adaptorModel.rootIndex) {
2105 _q_itemsRemoved(sourceStart, count);
2106 } else if (destinationParent == d->m_adaptorModel.rootIndex) {
2107 _q_itemsInserted(destinationRow, count);
2108 }
2109}
2110
2111void QQmlDelegateModel::_q_columnsInserted(const QModelIndex &parent, int begin, int end)
2112{
2113 Q_D(QQmlDelegateModel);
2114 Q_UNUSED(end);
2115 if (parent == d->m_adaptorModel.rootIndex && begin == 0) {
2116 // mark all items as changed
2117 _q_itemsChanged(0, d->m_count, QList<int>());
2118 }
2119}
2120
2121void QQmlDelegateModel::_q_columnsRemoved(const QModelIndex &parent, int begin, int end)
2122{
2123 Q_D(QQmlDelegateModel);
2124 Q_UNUSED(end);
2125 if (parent == d->m_adaptorModel.rootIndex && begin == 0) {
2126 // mark all items as changed
2127 _q_itemsChanged(0, d->m_count, QList<int>());
2128 }
2129}
2130
2131void QQmlDelegateModel::_q_columnsMoved(const QModelIndex &parent, int start, int end,
2132 const QModelIndex &destination, int column)
2133{
2134 Q_D(QQmlDelegateModel);
2135 Q_UNUSED(end);
2136 if ((parent == d->m_adaptorModel.rootIndex && start == 0)
2137 || (destination == d->m_adaptorModel.rootIndex && column == 0)) {
2138 // mark all items as changed
2139 _q_itemsChanged(0, d->m_count, QList<int>());
2140 }
2141}
2142
2143void QQmlDelegateModel::_q_dataChanged(const QModelIndex &begin, const QModelIndex &end, const QList<int> &roles)
2144{
2145 Q_D(QQmlDelegateModel);
2146 if (begin.parent() == d->m_adaptorModel.rootIndex)
2147 _q_itemsChanged(begin.row(), end.row() - begin.row() + 1, roles);
2148}
2149
2150bool QQmlDelegateModel::isDescendantOf(const QPersistentModelIndex& desc, const QList< QPersistentModelIndex >& parents) const
2151{
2152 for (int i = 0, c = parents.size(); i < c; ++i) {
2153 for (QPersistentModelIndex parent = desc; parent.isValid(); parent = parent.parent()) {
2154 if (parent == parents[i])
2155 return true;
2156 }
2157 }
2158
2159 return false;
2160}
2161
2162void QQmlDelegateModel::_q_layoutChanged(const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint)
2163{
2164 Q_D(QQmlDelegateModel);
2165 if (!d->m_complete)
2166 return;
2167
2168 if (hint == QAbstractItemModel::VerticalSortHint) {
2169 if (!parents.isEmpty() && d->m_adaptorModel.rootIndex.isValid() && !isDescendantOf(d->m_adaptorModel.rootIndex, parents)) {
2170 return;
2171 }
2172
2173 // mark all items as changed
2174 _q_itemsChanged(0, d->m_count, QList<int>());
2175
2176 } else if (hint == QAbstractItemModel::HorizontalSortHint) {
2177 // Ignored
2178 } else {
2179 // We don't know what's going on, so reset the model
2180 handleModelReset();
2181 }
2182}
2183
2184QQmlDelegateModelAttached *QQmlDelegateModel::qmlAttachedProperties(QObject *obj)
2185{
2186 if (QQmlDelegateModelItem *cacheItem = QQmlDelegateModelItem::dataForObject(obj))
2187 return new QQmlDelegateModelAttached(cacheItem, obj);
2188 return new QQmlDelegateModelAttached(obj);
2189}
2190
2192QQmlDelegateModelPrivate::insert(Compositor::insert_iterator &before, const QV4::Value &object, int groups)
2193{
2194 if (!m_context || !m_context->isValid())
2196
2197 QQmlDelegateModelItem *cacheItem = m_adaptorModel.createItem(m_cacheMetaType, -1);
2198 if (!cacheItem)
2200 if (!object.isObject())
2202
2203 QV4::ExecutionEngine *v4 = object.as<QV4::Object>()->engine();
2204 QV4::Scope scope(v4);
2205 QV4::ScopedObject o(scope, object);
2206 if (!o)
2208
2209 QV4::ObjectIterator it(scope, o, QV4::ObjectIterator::EnumerableOnly);
2210 QV4::ScopedValue propertyName(scope);
2211 QV4::ScopedValue v(scope);
2212 const auto oldCache = m_cache;
2213 while (1) {
2214 propertyName = it.nextPropertyNameAsString(v);
2215 if (propertyName->isNull())
2216 break;
2217 cacheItem->setValue(
2218 propertyName->toQStringNoThrow(),
2219 QV4::ExecutionEngine::toVariant(v, QMetaType {}));
2220 }
2221 const bool cacheModified = !m_cache.isSharedWith(oldCache);
2222 if (cacheModified)
2224
2225 cacheItem->setGroups(groups | Compositor::UnresolvedFlag | Compositor::CacheFlag);
2226
2227 // Must be before the new object is inserted into the cache or its indexes will be adjusted too.
2228 itemsInserted(QList<Compositor::Insert>(
2229 1, Compositor::Insert(before, 1, cacheItem->groups() & ~Compositor::CacheFlag)));
2230
2231 m_cache.insert(before.cacheIndex(), cacheItem);
2232 m_compositor.insert(before, nullptr, 0, 1, cacheItem->groups());
2233
2235}
2236
2237//============================================================================
2238
2239QQmlDelegateModelItemMetaType::QQmlDelegateModelItemMetaType(
2240 QV4::ExecutionEngine *engine, QQmlDelegateModel *model, const QStringList &groupNames)
2241 : model(model)
2242 , v4Engine(engine)
2243 , groupNames(groupNames)
2244 , modelKind(ModelKind::DelegateModel)
2245{
2246}
2247
2248QQmlDelegateModelItemMetaType::QQmlDelegateModelItemMetaType(
2249 QV4::ExecutionEngine *engine, QQmlTableInstanceModel *model)
2250 : model(model)
2251 , v4Engine(engine)
2252 , modelKind(ModelKind::TableInstanceModel)
2253{
2254}
2255
2256QQmlDelegateModelItemMetaType::~QQmlDelegateModelItemMetaType() = default;
2257
2258void QQmlDelegateModelItemMetaType::emitModelChanged() const
2259{
2260 switch (modelKind) {
2261 case ModelKind::InstanceModel:
2262 break;
2263 case ModelKind::DelegateModel:
2264 emit static_cast<QQmlDelegateModel *>(model.data())->modelChanged();
2265 break;
2266 case ModelKind::TableInstanceModel:
2267 emit static_cast<QQmlTableInstanceModel *>(model.data())->modelChanged();
2268 break;
2269 }
2270}
2271
2272void QQmlDelegateModelItemMetaType::initializeAttachedMetaObject()
2273{
2274 QMetaObjectBuilder builder;
2275 builder.setFlags(DynamicMetaObject);
2276 builder.setClassName(QQmlDelegateModelAttached::staticMetaObject.className());
2277 builder.setSuperClass(&QQmlDelegateModelAttached::staticMetaObject);
2278
2279 int notifierId = 0;
2280 for (qsizetype i = 0, end = groupCount(); i < end; ++i, ++notifierId) {
2281 QString propertyName = QLatin1String("in") + groupNames.at(i);
2282 propertyName.replace(2, 1, propertyName.at(2).toUpper());
2283 builder.addSignal("__" + propertyName.toUtf8() + "Changed()");
2284 QMetaPropertyBuilder propertyBuilder = builder.addProperty(
2285 propertyName.toUtf8(), "bool", notifierId);
2286 propertyBuilder.setWritable(true);
2287 propertyBuilder.setFinal(true);
2288 }
2289 for (qsizetype i = 0, end = groupCount(); i < end; ++i, ++notifierId) {
2290 const QString propertyName = groupNames.at(i) + QLatin1String("Index");
2291 builder.addSignal("__" + propertyName.toUtf8() + "Changed()");
2292 QMetaPropertyBuilder propertyBuilder = builder.addProperty(
2293 propertyName.toUtf8(), "int", notifierId);
2294 propertyBuilder.setWritable(true);
2295 propertyBuilder.setFinal(true);
2296 }
2297
2298 attachedMetaObject = QQml::makeRefPointer<QQmlDelegateModelAttachedMetaObject>(
2299 this, builder.toMetaObject());
2300}
2301
2302void QQmlDelegateModelItemMetaType::initializePrototype()
2303{
2304 QV4::Scope scope(v4Engine);
2305
2306 QV4::ScopedObject proto(scope, v4Engine->newObject());
2307 proto->defineAccessorProperty(QStringLiteral("model"), QQmlDelegateModelItem::get_model, nullptr);
2308 proto->defineAccessorProperty(QStringLiteral("groups"), QQmlDelegateModelItem::get_groups, QQmlDelegateModelItem::set_groups);
2309 QV4::ScopedString s(scope);
2310 QV4::ScopedProperty p(scope);
2311
2312 s = v4Engine->newString(QStringLiteral("isUnresolved"));
2313 QV4::ScopedFunctionObject f(scope);
2314 QV4::ExecutionEngine *engine = scope.engine;
2315 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, 30, QQmlDelegateModelItem::get_member)));
2316 p->setSetter(nullptr);
2317 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2318
2319 s = v4Engine->newString(QStringLiteral("inItems"));
2320 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Default, QQmlDelegateModelItem::get_member)));
2321 p->setSetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Default, QQmlDelegateModelItem::set_member)));
2322 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2323
2324 s = v4Engine->newString(QStringLiteral("inPersistedItems"));
2325 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Persisted, QQmlDelegateModelItem::get_member)));
2326 p->setSetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Persisted, QQmlDelegateModelItem::set_member)));
2327 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2328
2329 s = v4Engine->newString(QStringLiteral("itemsIndex"));
2330 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Default, QQmlDelegateModelItem::get_index)));
2331 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2332
2333 s = v4Engine->newString(QStringLiteral("persistedItemsIndex"));
2334 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, QQmlListCompositor::Persisted, QQmlDelegateModelItem::get_index)));
2335 p->setSetter(nullptr);
2336 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2337
2338 for (qsizetype i = 2, end = groupCount(); i < end; ++i) {
2339 QString propertyName = QLatin1String("in") + groupNames.at(i);
2340 propertyName.replace(2, 1, propertyName.at(2).toUpper());
2341 s = v4Engine->newString(propertyName);
2342 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, i + 1, QQmlDelegateModelItem::get_member)));
2343 p->setSetter((f = QV4::DelegateModelGroupFunction::create(engine, i + 1, QQmlDelegateModelItem::set_member)));
2344 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2345 }
2346 for (qsizetype i = 2, end = groupCount(); i < end; ++i) {
2347 const QString propertyName = groupNames.at(i) + QLatin1String("Index");
2348 s = v4Engine->newString(propertyName);
2349 p->setGetter((f = QV4::DelegateModelGroupFunction::create(engine, i + 1, QQmlDelegateModelItem::get_index)));
2350 p->setSetter(nullptr);
2351 proto->insertMember(s, p, QV4::Attr_Accessor|QV4::Attr_NotConfigurable|QV4::Attr_NotEnumerable);
2352 }
2353 modelItemProto.set(v4Engine, proto);
2354}
2355
2356int QQmlDelegateModelItemMetaType::parseGroups(const QStringList &groups) const
2357{
2358 int groupFlags = 0;
2359 for (const QString &groupName : groups) {
2360 int index = groupNames.indexOf(groupName);
2361 if (index != -1)
2362 groupFlags |= 2 << index;
2363 }
2364 return groupFlags;
2365}
2366
2367int QQmlDelegateModelItemMetaType::parseGroups(const QV4::Value &groups) const
2368{
2369 int groupFlags = 0;
2370 QV4::Scope scope(v4Engine);
2371
2372 QV4::ScopedString s(scope, groups);
2373 if (s) {
2374 const QString groupName = s->toQString();
2375 int index = groupNames.indexOf(groupName);
2376 if (index != -1)
2377 groupFlags |= 2 << index;
2378 return groupFlags;
2379 }
2380
2381 QV4::ScopedArrayObject array(scope, groups);
2382 if (array) {
2383 QV4::ScopedValue v(scope);
2384 uint arrayLength = array->getLength();
2385 for (uint i = 0; i < arrayLength; ++i) {
2386 v = array->get(i);
2387 const QString groupName = v->toQString();
2388 int index = groupNames.indexOf(groupName);
2389 if (index != -1)
2390 groupFlags |= 2 << index;
2391 }
2392 }
2393 return groupFlags;
2394}
2395
2396QV4::ReturnedValue QQmlDelegateModelItem::get_model(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
2397{
2398 QV4::Scope scope(b);
2399 QV4::Scoped<QQmlDelegateModelItemObject> o(scope, thisObject->as<QQmlDelegateModelItemObject>());
2400 if (!o)
2401 return b->engine()->throwTypeError(QStringLiteral("Not a valid DelegateModel object"));
2402
2403 QQmlDelegateModelItem *item = o->d()->item();
2404 if (!item->m_metaType->model)
2405 RETURN_UNDEFINED();
2406
2407 return item->get();
2408}
2409
2410QV4::ReturnedValue QQmlDelegateModelItem::get_groups(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
2411{
2412 QV4::Scope scope(b);
2413 QV4::Scoped<QQmlDelegateModelItemObject> o(scope, thisObject->as<QQmlDelegateModelItemObject>());
2414 if (!o)
2415 return scope.engine->throwTypeError(QStringLiteral("Not a valid DelegateModel object"));
2416
2417 QStringList groups;
2418 QQmlDelegateModelItem *item = o->d()->item();
2419 const auto &metaType = item->m_metaType;
2420 for (qsizetype i = 0, end = metaType->groupCount(); i < end; ++i) {
2421 if (item->m_groups & (1 << (i + 1)))
2422 groups.append(metaType->groupNames.at(i));
2423 }
2424
2425 return scope.engine->fromVariant(groups);
2426}
2427
2428QV4::ReturnedValue QQmlDelegateModelItem::set_groups(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
2429{
2430 QV4::Scope scope(b);
2431 QV4::Scoped<QQmlDelegateModelItemObject> o(scope, thisObject->as<QQmlDelegateModelItemObject>());
2432 if (!o)
2433 return scope.engine->throwTypeError(QStringLiteral("Not a valid DelegateModel object"));
2434
2435 if (!argc)
2436 THROW_TYPE_ERROR();
2437
2438 QQmlDelegateModelItem *item = o->d()->item();
2439 QQmlDelegateModel *delegateModel = item->m_metaType->delegateModel();
2440 if (!delegateModel)
2441 RETURN_UNDEFINED();
2442
2443 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2444 const int groupFlags = model->m_cacheMetaType->parseGroups(argv[0]);
2445 const int cacheIndex = model->m_cache.indexOf(item);
2446 Compositor::iterator it = model->m_compositor.find(Compositor::Cache, cacheIndex);
2447 model->setGroups(it, 1, Compositor::Cache, groupFlags);
2448 return QV4::Encode::undefined();
2449}
2450
2451QV4::ReturnedValue QQmlDelegateModelItem::get_member(QQmlDelegateModelItem *thisItem, uint flag, const QV4::Value &)
2452{
2453 return QV4::Encode(bool(thisItem->m_groups & (1 << flag)));
2454}
2455
2456QV4::ReturnedValue QQmlDelegateModelItem::set_member(QQmlDelegateModelItem *cacheItem, uint flag, const QV4::Value &arg)
2457{
2458 bool member = arg.toBoolean();
2459 uint groupFlag = (1 << flag);
2460 if (member == ((cacheItem->m_groups & groupFlag) != 0))
2461 return QV4::Encode::undefined();
2462
2463 QQmlDelegateModel *delegateModel = cacheItem->m_metaType->delegateModel();
2464 if (!delegateModel)
2465 return QV4::Encode::undefined();
2466
2467 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2468 const int cacheIndex = model->m_cache.indexOf(cacheItem);
2469 Compositor::iterator it = model->m_compositor.find(Compositor::Cache, cacheIndex);
2470 if (member)
2471 model->addGroups(it, 1, Compositor::Cache, groupFlag);
2472 else
2473 model->removeGroups(it, 1, Compositor::Cache, groupFlag);
2474 return QV4::Encode::undefined();
2475}
2476
2477QV4::ReturnedValue QQmlDelegateModelItem::get_index(QQmlDelegateModelItem *thisItem, uint flag, const QV4::Value &)
2478{
2479 return QV4::Encode((int)thisItem->groupIndex(Compositor::Group(flag)));
2480}
2481
2482void QQmlDelegateModelItem::childContextObjectDestroyed(QObject *childContextObject)
2483{
2484 if (!m_contextData)
2485 return;
2486
2487 for (QQmlRefPointer<QQmlContextData> ctxt = m_contextData->childContexts(); ctxt;
2488 ctxt = ctxt->nextChild()) {
2489 ctxt->deepClearContextObject(childContextObject);
2490 }
2491}
2492
2493
2494//---------------------------------------------------------------------------
2495
2497
2499{
2500 // We need to first destroy the reference and then call dispose() because dispose() only
2501 // does something if the item is not referenced anymore.
2502 QQmlDelegateModelItem *disposable = item();
2503 reinterpret_cast<QQmlDelegateModelItem::ScriptReference *>(&ref)->~ScriptReference();
2504 disposable->dispose();
2505 Object::destroy();
2506}
2507
2508
2509QQmlDelegateModelItem::QQmlDelegateModelItem(
2510 const QQmlRefPointer<QQmlDelegateModelItemMetaType> &metaType,
2511 QQmlAdaptorModel::Accessors *accessor,
2512 int modelIndex, int row, int column)
2513 : m_metaType(metaType)
2514 , m_index(modelIndex)
2515 , m_row(row)
2516 , m_column(column)
2517{
2518 if (accessor->propertyCache) {
2519 // The property cache in the accessor is common for all the model
2520 // items in the model it wraps. It describes available model roles,
2521 // together with revisioned properties like row, column and index, all
2522 // which should be available in the delegate. We assign this cache to the
2523 // model item so that the QML engine can use the revision information
2524 // when resolving the properties (rather than falling back to just
2525 // inspecting the QObject in the model item directly).
2526 QQmlData::get(this, true)->propertyCache = accessor->propertyCache;
2527 }
2528}
2529
2530QQmlDelegateModelItem::~QQmlDelegateModelItem()
2531{
2532 Q_ASSERT(m_scriptRef == 0);
2533 Q_ASSERT(m_objectStrongRef == 0);
2534 Q_ASSERT(!m_object);
2535
2536 if (m_incubationTask) {
2537 if (QQmlDelegateModel *delegateModel = m_metaType->delegateModel())
2538 QQmlDelegateModelPrivate::get(delegateModel)->releaseIncubator(m_incubationTask);
2539 else
2540 delete m_incubationTask;
2541 }
2542}
2543
2544void QQmlDelegateModelItem::dispose()
2545{
2546 if (isScriptReferenced() || m_object)
2547 return;
2548
2549 if (QQmlDelegateModel *delegateModel = m_metaType->delegateModel())
2550 QQmlDelegateModelPrivate::get(delegateModel)->removeCacheItem(this);
2551
2552 delete this;
2553}
2554
2555void QQmlDelegateModelItem::setModelIndex(int idx, int newRow, int newColumn, bool alwaysEmit)
2556{
2557 const int prevIndex = m_index;
2558 const int prevRow = m_row;
2559 const int prevColumn = m_column;
2560
2561 m_index = idx;
2562 m_row = newRow;
2563 m_column = newColumn;
2564
2565 if (idx != prevIndex || alwaysEmit)
2566 emit modelIndexChanged();
2567 if (m_row != prevRow || alwaysEmit)
2568 emit rowChanged();
2569 if (m_column != prevColumn || alwaysEmit)
2570 emit columnChanged();
2571}
2572
2573void QQmlDelegateModelItem::destroyObject()
2574{
2575 delete std::exchange(m_object, nullptr);
2576 m_contextData.reset();
2577}
2578
2579void QQmlDelegateModelItem::destroyObjectLater()
2580{
2581 Q_ASSERT(m_object);
2582 Q_ASSERT(m_contextData);
2583
2584 QQmlData *data = QQmlData::get(m_object);
2585 Q_ASSERT(data);
2586 if (data->ownContext) {
2587 data->ownContext->emitDestruction();
2588 data->ownContext->clearExpressions();
2589 data->ownContext->deepClearContextObject(m_object);
2590 data->ownContext.reset();
2591 data->context = nullptr;
2592 }
2593 /* QTBUG-87228: when destroying object at the application exit, the deferred
2594 * parent by setting it to QCoreApplication instance if it's nullptr, so
2595 * deletion won't work. Not to leak memory, make sure our object has a that
2596 * the parent claims the object at the end of the lifetime. When not at the
2597 * application exit, normal event loop will handle the deferred deletion
2598 * earlier.
2599 */
2600 if (Q_UNLIKELY(static_cast<QCoreApplicationPrivate *>(QCoreApplicationPrivate::get(QCoreApplication::instance()))->aboutToQuitEmitted)) {
2601 if (m_object->parent() == nullptr)
2602 m_object->setParent(QCoreApplication::instance());
2603 }
2604 m_object->deleteLater();
2605
2606 if (QQmlDelegateModelAttached *attachedObject = attached())
2607 attachedObject->m_cacheItem = nullptr;
2608
2609 m_contextData.reset();
2610 m_object = nullptr;
2611}
2612
2613QQmlDelegateModelItem *QQmlDelegateModelItem::dataForObject(QObject *object)
2614{
2615 QQmlData *d = QQmlData::get(object);
2616 if (!d)
2617 return nullptr;
2618
2619 QQmlRefPointer<QQmlContextData> context = d->context;
2620 if (!context || !context->isValid())
2621 return nullptr;
2622
2623 if (QObject *extraObject = context->extraObject())
2624 return qobject_cast<QQmlDelegateModelItem *>(extraObject);
2625
2626 for (context = context->parent(); context; context = context->parent()) {
2627 if (QObject *extraObject = context->extraObject())
2628 return qobject_cast<QQmlDelegateModelItem *>(extraObject);
2629 if (QQmlDelegateModelItem *cacheItem = qobject_cast<QQmlDelegateModelItem *>(
2630 context->contextObject())) {
2631 return cacheItem;
2632 }
2633 }
2634 return nullptr;
2635}
2636
2637int QQmlDelegateModelItem::groupIndex(Compositor::Group group)
2638{
2639 if (QQmlDelegateModel *delegateModel = m_metaType->delegateModel()) {
2640 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2641 return model->m_compositor.find(Compositor::Cache, model->m_cache.indexOf(this)).index[group];
2642 }
2643 return -1;
2644}
2645
2646//---------------------------------------------------------------------------
2647
2648QQmlDelegateModelAttachedMetaObject::QQmlDelegateModelAttachedMetaObject(
2649 QQmlDelegateModelItemMetaType *metaType, QMetaObject *metaObject)
2654 + metaType->groupCount())
2655{
2656 // Don't reference count the meta-type here as that would create a circular reference.
2657 // Instead we rely the fact that the meta-type's reference count can't reach 0 without first
2658 // destroying all delegates with attached objects.
2659 *static_cast<QMetaObject *>(this) = *metaObject;
2660}
2661
2662QQmlDelegateModelAttachedMetaObject::~QQmlDelegateModelAttachedMetaObject()
2663{
2664 ::free(metaObject);
2665}
2666
2667void QQmlDelegateModelAttachedMetaObject::objectDestroyed(QObject *)
2668{
2669 release();
2670}
2671
2672int QQmlDelegateModelAttachedMetaObject::metaCall(QObject *object, QMetaObject::Call call, int _id, void **arguments)
2673{
2674 QQmlDelegateModelAttached *attached = static_cast<QQmlDelegateModelAttached *>(object);
2675 if (call == QMetaObject::ReadProperty) {
2676 if (_id >= indexPropertyOffset) {
2677 Compositor::Group group = Compositor::Group(_id - indexPropertyOffset + 1);
2678 *static_cast<int *>(arguments[0]) = attached->m_currentIndex[group];
2679 return -1;
2680 } else if (_id >= memberPropertyOffset) {
2681 Compositor::Group group = Compositor::Group(_id - memberPropertyOffset + 1);
2682 *static_cast<bool *>(arguments[0]) = attached->m_cacheItem->groups() & (1 << group);
2683 return -1;
2684 }
2685 } else if (call == QMetaObject::WriteProperty) {
2686 if (_id >= memberPropertyOffset) {
2687 QQmlDelegateModel *delegateModel = metaType->delegateModel();
2688 if (!delegateModel)
2689 return -1;
2690 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2691 Compositor::Group group = Compositor::Group(_id - memberPropertyOffset + 1);
2692 const int groupFlag = 1 << group;
2693 const bool member = attached->m_cacheItem->groups() & groupFlag;
2694 if (member && !*static_cast<bool *>(arguments[0])) {
2695 Compositor::iterator it = model->m_compositor.find(
2696 group, attached->m_currentIndex[group]);
2697 model->removeGroups(it, 1, group, groupFlag);
2698 } else if (!member && *static_cast<bool *>(arguments[0])) {
2699 for (qsizetype i = 1, end = metaType->groupCount(); i <= end; ++i) {
2700 if (attached->m_cacheItem->groups() & (1 << i)) {
2701 Compositor::iterator it = model->m_compositor.find(
2702 Compositor::Group(i), attached->m_currentIndex[i]);
2703 model->addGroups(it, 1, Compositor::Group(i), groupFlag);
2704 break;
2705 }
2706 }
2707 }
2708 return -1;
2709 }
2710 }
2711 return attached->qt_metacall(call, _id, arguments);
2712}
2713
2714QQmlDelegateModelAttached::QQmlDelegateModelAttached(QObject *parent)
2715 : m_cacheItem(nullptr)
2716 , m_previousGroups(0)
2717{
2718 QQml_setParent_noEvent(this, parent);
2719}
2720
2722 QQmlDelegateModelItem *cacheItem, QObject *parent)
2723 : m_cacheItem(cacheItem)
2724 , m_previousGroups(cacheItem->groups())
2725{
2726 QQml_setParent_noEvent(this, parent);
2728 // Let m_previousIndex be equal to m_currentIndex
2729 std::copy(std::begin(m_currentIndex), std::end(m_currentIndex), std::begin(m_previousIndex));
2730
2731 const auto &metaType = cacheItem->metaType();
2732 if (!metaType->attachedMetaObject)
2733 metaType->initializeAttachedMetaObject();
2734
2735 QObjectPrivate::get(this)->metaObject = metaType->attachedMetaObject.data();
2736 metaType->attachedMetaObject->addref();
2737}
2738
2740
2742{
2743 const auto &metaType = m_cacheItem->metaType();
2744 if (QQDMIncubationTask *incubationTask = m_cacheItem->incubationTask()) {
2745 for (qsizetype i = 1, end = metaType->groupCount(); i <= end; ++i)
2746 m_currentIndex[i] = incubationTask->index[i];
2747 } else if (QQmlDelegateModel *delegateModel = metaType->delegateModel()) {
2748 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2749 Compositor::iterator it = model->m_compositor.find(
2750 Compositor::Cache, model->m_cache.indexOf(m_cacheItem));
2751 for (qsizetype i = 1, end = metaType->groupCount(); i <= end; ++i)
2752 m_currentIndex[i] = it.index[i];
2753 }
2754}
2755
2757{
2758 setInGroup(QQmlListCompositor::Persisted, inPersisted);
2759}
2760
2762{
2763 if (!m_cacheItem)
2764 return false;
2765 const uint groupFlag = (1 << QQmlListCompositor::Persisted);
2766 return m_cacheItem->groups() & groupFlag;
2767}
2768
2770{
2771 if (!m_cacheItem)
2772 return -1;
2773 return m_cacheItem->groupIndex(QQmlListCompositor::Persisted);
2774}
2775
2776void QQmlDelegateModelAttached::setInGroup(QQmlListCompositor::Group group, bool inGroup)
2777{
2778 if (!m_cacheItem)
2779 return;
2780
2781 QQmlDelegateModel *delegateModel = m_cacheItem->metaType()->delegateModel();
2782 if (!delegateModel)
2783 return;
2784
2785 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2786 const uint groupFlag = (1 << group);
2787 if (inGroup == bool(m_cacheItem->groups() & groupFlag))
2788 return;
2789
2790 const int cacheIndex = model->m_cache.indexOf(m_cacheItem);
2791 Compositor::iterator it = model->m_compositor.find(Compositor::Cache, cacheIndex);
2792 if (inGroup)
2793 model->addGroups(it, 1, Compositor::Cache, groupFlag);
2794 else
2795 model->removeGroups(it, 1, Compositor::Cache, groupFlag);
2796 // signal emission happens in add-/removeGroups
2797}
2798
2800{
2801 setInGroup(QQmlListCompositor::Default, inItems);
2802}
2803
2805{
2806 if (!m_cacheItem)
2807 return false;
2808 const uint groupFlag = (1 << QQmlListCompositor::Default);
2809 return m_cacheItem->groups() & groupFlag;
2810}
2811
2813{
2814 if (!m_cacheItem)
2815 return -1;
2816 return m_cacheItem->groupIndex(QQmlListCompositor::Default);
2817}
2818
2819/*!
2820 \qmlattachedproperty model QtQml.Models::DelegateModel::model
2821
2822 This attached property holds the data model this delegate instance belongs to.
2823
2824 It is attached to each instance of the delegate.
2825*/
2826
2828{
2829 return m_cacheItem ? m_cacheItem->metaType()->delegateModel() : nullptr;
2830}
2831
2832/*!
2833 \qmlattachedproperty list<string> QtQml.Models::DelegateModel::groups
2834
2835 This attached property holds the name of DelegateModelGroups the item belongs to.
2836
2837 It is attached to each instance of the delegate.
2838*/
2839
2841{
2842 QStringList groups;
2843
2844 if (!m_cacheItem)
2845 return groups;
2846 const auto &metaType = m_cacheItem->metaType();
2847 for (qsizetype i = 0, end = metaType->groupCount(); i < end; ++i) {
2848 if (m_cacheItem->groups() & (1 << (i + 1)))
2849 groups.append(metaType->groupNames.at(i));
2850 }
2851 return groups;
2852}
2853
2854void QQmlDelegateModelAttached::setGroups(const QStringList &groups)
2855{
2856 if (!m_cacheItem)
2857 return;
2858
2859 QQmlDelegateModel *delegateModel = m_cacheItem->metaType()->delegateModel();
2860 if (!delegateModel)
2861 return;
2862
2863 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(delegateModel);
2864 const int groupFlags = model->m_cacheMetaType->parseGroups(groups);
2865 const int cacheIndex = model->m_cache.indexOf(m_cacheItem);
2866 Compositor::iterator it = model->m_compositor.find(Compositor::Cache, cacheIndex);
2867 model->setGroups(it, 1, Compositor::Cache, groupFlags);
2868}
2869
2870/*!
2871 \qmlattachedproperty bool QtQml.Models::DelegateModel::isUnresolved
2872
2873 This attached property indicates whether the visual item is bound to a data model index.
2874 Returns true if the item is not bound to the model, and false if it is.
2875
2876 An unresolved item can be bound to the data model using the DelegateModelGroup::resolve()
2877 function.
2878
2879 It is attached to each instance of the delegate.
2880*/
2881
2883{
2884 if (!m_cacheItem)
2885 return false;
2886
2887 return m_cacheItem->groups() & Compositor::UnresolvedFlag;
2888}
2889
2890/*!
2891 \qmlattachedproperty bool QtQml.Models::DelegateModel::inItems
2892
2893 This attached property holds whether the item belongs to the default \l items
2894 DelegateModelGroup.
2895
2896 Changing this property will add or remove the item from the items group.
2897
2898 It is attached to each instance of the delegate.
2899*/
2900
2901/*!
2902 \qmlattachedproperty int QtQml.Models::DelegateModel::itemsIndex
2903
2904 This attached property holds the index of the item in the default \l items DelegateModelGroup.
2905
2906 It is attached to each instance of the delegate.
2907*/
2908
2909/*!
2910 \qmlattachedproperty bool QtQml.Models::DelegateModel::inPersistedItems
2911
2912 This attached property holds whether the item belongs to the \l persistedItems
2913 DelegateModelGroup.
2914
2915 Changing this property will add or remove the item from the items group. Change with caution
2916 as removing an item from the persistedItems group will destroy the current instance if it is
2917 not referenced by a model.
2918
2919 It is attached to each instance of the delegate.
2920*/
2921
2922/*!
2923 \qmlattachedproperty int QtQml.Models::DelegateModel::persistedItemsIndex
2924
2925 This attached property holds the index of the item in the \l persistedItems DelegateModelGroup.
2926
2927 It is attached to each instance of the delegate.
2928*/
2929
2931{
2932 const int groupChanges = m_previousGroups ^ m_cacheItem->groups();
2933 m_previousGroups = m_cacheItem->groups();
2934
2935 int indexChanges = 0;
2936 const qsizetype groupCount = m_cacheItem->metaType()->groupCount();
2937 for (qsizetype i = 1; i <= groupCount; ++i) {
2938 if (m_previousIndex[i] != m_currentIndex[i]) {
2939 m_previousIndex[i] = m_currentIndex[i];
2940 indexChanges |= (1 << i);
2941 }
2942 }
2943
2944 // Don't access m_cacheItem anymore once we've started sending signals.
2945 // We don't own it and someone might delete it.
2946
2947 int notifierId = 0;
2948 const QMetaObject *meta = metaObject();
2949 for (qsizetype i = 1; i <= groupCount; ++i, ++notifierId) {
2950 if (groupChanges & (1 << i))
2951 QMetaObject::activate(this, meta, notifierId, nullptr);
2952 }
2953 for (qsizetype i = 1; i <= groupCount; ++i, ++notifierId) {
2954 if (indexChanges & (1 << i))
2955 QMetaObject::activate(this, meta, notifierId, nullptr);
2956 }
2957
2958 if (groupChanges)
2959 emit groupsChanged();
2960}
2961
2962//============================================================================
2963
2964void QQmlDelegateModelGroupPrivate::setModel(QQmlDelegateModel *m, Compositor::Group g)
2965{
2966 Q_ASSERT(!model);
2967 model = m;
2968 group = g;
2969}
2970
2972{
2973 Q_Q(QQmlDelegateModelGroup);
2974 IS_SIGNAL_CONNECTED(q, QQmlDelegateModelGroup, changed, (const QJSValue &,const QJSValue &));
2975}
2976
2977void QQmlDelegateModelGroupPrivate::emitChanges(QV4::ExecutionEngine *v4)
2978{
2979 Q_Q(QQmlDelegateModelGroup);
2980 if (isChangedConnected() && !changeSet.isEmpty()) {
2981 emit q->changed(QJSValuePrivate::fromReturnedValue(
2982 qdmEngineData(v4)->array(v4, changeSet.removes())),
2983 QJSValuePrivate::fromReturnedValue(
2984 qdmEngineData(v4)->array(v4, changeSet.inserts())));
2985 }
2986 if (changeSet.difference() != 0)
2987 emit q->countChanged();
2988}
2989
2991{
2992 for (QQmlDelegateModelGroupEmitterList::iterator it = emitters.begin(); it != emitters.end(); ++it)
2993 it->emitModelUpdated(changeSet, reset);
2994 changeSet.clear();
2995}
2996
2998
2999void QQmlDelegateModelGroupPrivate::createdPackage(int index, QQuickPackage *package)
3000{
3001 for (GroupEmitterListIt it = emitters.begin(), end = emitters.end(); it != end; ++it)
3002 it->createdPackage(index, package);
3003}
3004
3005void QQmlDelegateModelGroupPrivate::initPackage(int index, QQuickPackage *package)
3006{
3007 for (GroupEmitterListIt it = emitters.begin(), end = emitters.end(); it != end; ++it)
3008 it->initPackage(index, package);
3009}
3010
3012{
3013 for (GroupEmitterListIt it = emitters.begin(), end = emitters.end(); it != end; ++it)
3014 it->destroyingPackage(package);
3015}
3016
3017/*!
3018 \qmltype DelegateModelGroup
3019 \nativetype QQmlDelegateModelGroup
3020 \inqmlmodule QtQml.Models
3021 \ingroup qtquick-models
3022 \brief Encapsulates a filtered set of visual data items.
3023
3024 The DelegateModelGroup type provides a means to address the model data of a
3025 DelegateModel's delegate items, as well as sort and filter these delegate
3026 items.
3027
3028 The initial set of instantiable delegate items in a DelegateModel is represented
3029 by its \l {QtQml.Models::DelegateModel::items}{items} group, which normally directly reflects
3030 the contents of the model assigned to DelegateModel::model. This set can be changed to
3031 the contents of any other member of DelegateModel::groups by assigning the \l name of that
3032 DelegateModelGroup to the DelegateModel::filterOnGroup property.
3033
3034 The data of an item in a DelegateModelGroup can be accessed using the get() function, which returns
3035 information about group membership and indexes as well as model data. In combination
3036 with the move() function this can be used to implement view sorting, with remove() to filter
3037 items out of a view, or with setGroups() and \l Package delegates to categorize items into
3038 different views. Different groups can only be sorted independently if they are disjunct. Moving
3039 an item in one group will also move it in all other groups it is a part of.
3040
3041 Data from models can be supplemented by inserting data directly into a DelegateModelGroup
3042 with the insert() function. This can be used to introduce mock items into a view, or
3043 placeholder items that are later \l {resolve()}{resolved} to real model data when it becomes
3044 available.
3045
3046 Delegate items can also be instantiated directly from a DelegateModelGroup using the
3047 create() function, making it possible to use DelegateModel without an accompanying view
3048 type or to cherry-pick specific items that should be instantiated irregardless of whether
3049 they're currently within a view's visible area.
3050
3051 \sa {QML Dynamic View Ordering Tutorial}
3052*/
3053QQmlDelegateModelGroup::QQmlDelegateModelGroup(QObject *parent)
3054 : QObject(*new QQmlDelegateModelGroupPrivate, parent)
3055{
3056}
3057
3058QQmlDelegateModelGroup::QQmlDelegateModelGroup(
3059 const QString &name, QQmlDelegateModel *model, int index, QObject *parent)
3060 : QQmlDelegateModelGroup(parent)
3061{
3062 Q_D(QQmlDelegateModelGroup);
3063 d->name = name;
3064 d->setModel(model, Compositor::Group(index));
3065}
3066
3067QQmlDelegateModelGroup::~QQmlDelegateModelGroup() = default;
3068
3069/*!
3070 \qmlproperty string QtQml.Models::DelegateModelGroup::name
3071
3072 This property holds the name of the group.
3073
3074 Each group in a model must have a unique name starting with a lower case letter.
3075*/
3076
3077QString QQmlDelegateModelGroup::name() const
3078{
3079 Q_D(const QQmlDelegateModelGroup);
3080 return d->name;
3081}
3082
3083void QQmlDelegateModelGroup::setName(const QString &name)
3084{
3085 Q_D(QQmlDelegateModelGroup);
3086 if (d->model)
3087 return;
3088 if (d->name != name) {
3089 d->name = name;
3090 emit nameChanged();
3091 }
3092}
3093
3094/*!
3095 \qmlproperty int QtQml.Models::DelegateModelGroup::count
3096
3097 This property holds the number of items in the group.
3098*/
3099
3100int QQmlDelegateModelGroup::count() const
3101{
3102 Q_D(const QQmlDelegateModelGroup);
3103 if (!d->model)
3104 return 0;
3105 return QQmlDelegateModelPrivate::get(d->model)->m_compositor.count(d->group);
3106}
3107
3108/*!
3109 \qmlproperty bool QtQml.Models::DelegateModelGroup::includeByDefault
3110
3111 This property holds whether new items are assigned to this group by default.
3112*/
3113
3114bool QQmlDelegateModelGroup::defaultInclude() const
3115{
3116 Q_D(const QQmlDelegateModelGroup);
3117 return d->defaultInclude;
3118}
3119
3120void QQmlDelegateModelGroup::setDefaultInclude(bool include)
3121{
3122 Q_D(QQmlDelegateModelGroup);
3123 if (d->defaultInclude != include) {
3124 d->defaultInclude = include;
3125
3126 if (d->model) {
3127 if (include)
3128 QQmlDelegateModelPrivate::get(d->model)->m_compositor.setDefaultGroup(d->group);
3129 else
3130 QQmlDelegateModelPrivate::get(d->model)->m_compositor.clearDefaultGroup(d->group);
3131 }
3132 emit defaultIncludeChanged();
3133 }
3134}
3135
3136/*!
3137 \qmlmethod var QtQml.Models::DelegateModelGroup::get(int index)
3138
3139 Returns a javascript object describing the item at \a index in the group.
3140
3141 The returned object contains the same information that is available to a delegate from the
3142 DelegateModel attached as well as the model for that item. It has the properties:
3143
3144 \list
3145 \li \b model The model data of the item. This is the same as the model context property in
3146 a delegate
3147 \li \b groups A list the of names of groups the item is a member of. This property can be
3148 written to change the item's membership.
3149 \li \b inItems Whether the item belongs to the \l {QtQml.Models::DelegateModel::items}{items} group.
3150 Writing to this property will add or remove the item from the group.
3151 \li \b itemsIndex The index of the item within the \l {QtQml.Models::DelegateModel::items}{items} group.
3152 \li \b {in<GroupName>} Whether the item belongs to the dynamic group \e groupName. Writing to
3153 this property will add or remove the item from the group.
3154 \li \b {<groupName>Index} The index of the item within the dynamic group \e groupName.
3155 \li \b isUnresolved Whether the item is bound to an index in the model assigned to
3156 DelegateModel::model. Returns true if the item is not bound to the model, and false if it is.
3157 \endlist
3158*/
3159
3160QJSValue QQmlDelegateModelGroup::get(int index)
3161{
3162 Q_D(QQmlDelegateModelGroup);
3163 if (!d->model)
3164 return QJSValue();
3165
3166 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3167 if (!model->m_context || !model->m_context->isValid()) {
3168 return QJSValue();
3169 } else if (index < 0 || index >= model->m_compositor.count(d->group)) {
3170 qmlWarning(this) << tr("get: index out of range");
3171 return QJSValue();
3172 }
3173
3174 Compositor::iterator it = model->m_compositor.find(d->group, index);
3175 QQmlDelegateModelItem *cacheItem = it->inCache()
3176 ? model->m_cache.at(it.cacheIndex())
3177 : 0;
3178
3179 if (!cacheItem) {
3180 cacheItem = model->m_adaptorModel.createItem(
3181 model->m_cacheMetaType, it.modelIndex());
3182 if (!cacheItem)
3183 return QJSValue();
3184 cacheItem->setGroups(it->flags);
3185
3186 model->m_cache.insert(it.cacheIndex(), cacheItem);
3187 model->m_compositor.setFlags(it, 1, Compositor::CacheFlag);
3188 }
3189
3190 if (model->m_cacheMetaType->modelItemProto.isUndefined())
3191 model->m_cacheMetaType->initializePrototype();
3192 QV4::ExecutionEngine *v4 = model->m_cacheMetaType->v4Engine;
3193 QV4::Scope scope(v4);
3194 QV4::ScopedObject o(scope, v4->memoryManager->allocate<QQmlDelegateModelItemObject>(cacheItem));
3195 QV4::ScopedObject p(scope, model->m_cacheMetaType->modelItemProto.value());
3196 o->setPrototypeOf(p);
3197
3198 return QJSValuePrivate::fromReturnedValue(o->asReturnedValue());
3199}
3200
3201bool QQmlDelegateModelGroupPrivate::parseIndex(const QV4::Value &value, int *index, Compositor::Group *group) const
3202{
3203 if (value.isNumber()) {
3204 *index = value.toInt32();
3205 return true;
3206 }
3207
3208 if (!value.isObject())
3209 return false;
3210
3211 QV4::ExecutionEngine *v4 = value.as<QV4::Object>()->engine();
3212 QV4::Scope scope(v4);
3213 QV4::Scoped<QQmlDelegateModelItemObject> object(scope, value);
3214
3215 if (object) {
3216 QQmlDelegateModelItem * const cacheItem = object->d()->item();
3217 if (QQmlDelegateModel *delegateModel = cacheItem->metaType()->delegateModel()) {
3218 *index = QQmlDelegateModelPrivate::get(delegateModel)->m_cache.indexOf(cacheItem);
3219 *group = Compositor::Cache;
3220 return true;
3221 }
3222 }
3223 return false;
3224}
3225
3226/*!
3227 \qmlmethod void QtQml.Models::DelegateModelGroup::insert(int index, jsdict data, array groups = undefined)
3228 \qmlmethod void QtQml.Models::DelegateModelGroup::insert(jsdict data, var groups = undefined)
3229
3230 Creates a new entry at \a index in a DelegateModel with the values from \a data that
3231 correspond to roles in the model assigned to DelegateModel::model.
3232
3233 If no index is supplied the data is appended to the model.
3234
3235 The optional \a groups parameter identifies the groups the new entry should belong to,
3236 if unspecified this is equal to the group insert was called on.
3237
3238 Data inserted into a DelegateModel can later be merged with an existing entry in
3239 DelegateModel::model using the \l resolve() function. This can be used to create placeholder
3240 items that are later replaced by actual data.
3241*/
3242
3243void QQmlDelegateModelGroup::insert(QQmlV4FunctionPtr args)
3244{
3245 Q_D(QQmlDelegateModelGroup);
3246 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3247
3248 int index = model->m_compositor.count(d->group);
3249 Compositor::Group group = d->group;
3250
3251 if (args->length() == 0)
3252 return;
3253
3254 int i = 0;
3255 QV4::Scope scope(args->v4engine());
3256 QV4::ScopedValue v(scope, (*args)[i]);
3257 if (d->parseIndex(v, &index, &group)) {
3258 if (index < 0 || index > model->m_compositor.count(group)) {
3259 qmlWarning(this) << tr("insert: index out of range");
3260 return;
3261 }
3262 if (++i == args->length())
3263 return;
3264 v = (*args)[i];
3265 }
3266
3267 if (v->as<QV4::ArrayObject>())
3268 return;
3269
3270 int groups = 1 << d->group;
3271 if (++i < args->length()) {
3272 QV4::ScopedValue val(scope, (*args)[i]);
3273 groups |= model->m_cacheMetaType->parseGroups(val);
3274 }
3275
3276 if (v->as<QV4::Object>()) {
3277 auto insertionResult = QQmlDelegateModelPrivate::InsertionResult::Retry;
3278 do {
3279 Compositor::insert_iterator before = index < model->m_compositor.count(group)
3280 ? model->m_compositor.findInsertPosition(group, index)
3281 : model->m_compositor.end();
3282 insertionResult = model->insert(before, v, groups);
3283 } while (insertionResult == QQmlDelegateModelPrivate::InsertionResult::Retry);
3284 if (insertionResult == QQmlDelegateModelPrivate::InsertionResult::Success)
3285 model->emitChanges();
3286 }
3287}
3288
3289/*!
3290 \qmlmethod var QtQml.Models::DelegateModelGroup::create(int index)
3291 \qmlmethod var QtQml.Models::DelegateModelGroup::create(int index, jsdict data, array groups = undefined)
3292 \qmlmethod var QtQml.Models::DelegateModelGroup::create(jsdict data, array groups = undefined)
3293
3294 Returns a reference to the instantiated item at \a index in the group.
3295
3296 If a \a data object is provided it will be \l {insert}{inserted} at \a index and an item
3297 referencing this new entry will be returned. The optional \a groups parameter identifies
3298 the groups the new entry should belong to, if unspecified this is equal to the group create()
3299 was called on.
3300
3301 All items returned by create are added to the
3302 \l {QtQml.Models::DelegateModel::persistedItems}{persistedItems} group. Items in this
3303 group remain instantiated when not referenced by any view.
3304*/
3305
3306void QQmlDelegateModelGroup::create(QQmlV4FunctionPtr args)
3307{
3308 Q_D(QQmlDelegateModelGroup);
3309 if (!d->model)
3310 return;
3311
3312 if (args->length() == 0)
3313 return;
3314
3315 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3316
3317 int index = model->m_compositor.count(d->group);
3318 Compositor::Group group = d->group;
3319
3320 int i = 0;
3321 QV4::Scope scope(args->v4engine());
3322 QV4::ScopedValue v(scope, (*args)[i]);
3323 if (d->parseIndex(v, &index, &group))
3324 ++i;
3325
3326 if (i < args->length() && index >= 0 && index <= model->m_compositor.count(group)) {
3327 v = (*args)[i];
3328 if (v->as<QV4::Object>()) {
3329 int groups = 1 << d->group;
3330 if (++i < args->length()) {
3331 QV4::ScopedValue val(scope, (*args)[i]);
3332 groups |= model->m_cacheMetaType->parseGroups(val);
3333 }
3334
3335 auto insertionResult = QQmlDelegateModelPrivate::InsertionResult::Retry;
3336 do {
3337 Compositor::insert_iterator before = index < model->m_compositor.count(group)
3338 ? model->m_compositor.findInsertPosition(group, index)
3339 : model->m_compositor.end();
3340
3341 index = before.index[d->group];
3342 group = d->group;
3343
3344 insertionResult = model->insert(before, v, groups);
3345 } while (insertionResult == QQmlDelegateModelPrivate::InsertionResult::Retry);
3346 if (insertionResult == QQmlDelegateModelPrivate::InsertionResult::Error)
3347 return;
3348 }
3349 }
3350 if (index < 0 || index >= model->m_compositor.count(group)) {
3351 qmlWarning(this) << tr("create: index out of range");
3352 return;
3353 }
3354
3355 QObject *object = model->object(group, index, QQmlIncubator::AsynchronousIfNested);
3356 if (object) {
3357 QList<Compositor::Insert> inserts;
3358 Compositor::iterator it = model->m_compositor.find(group, index);
3359 model->m_compositor.setFlags(it, 1, d->group, Compositor::PersistedFlag, &inserts);
3360 model->itemsInserted(inserts);
3361 model->m_cache.at(it.cacheIndex())->releaseObjectWeak();
3362 }
3363
3364 args->setReturnValue(QV4::QObjectWrapper::wrap(args->v4engine(), object));
3365 model->emitChanges();
3366}
3367
3368/*!
3369 \qmlmethod void QtQml.Models::DelegateModelGroup::resolve(int from, int to)
3370
3371 Binds an unresolved item at \a from to an item in DelegateModel::model at index \a to.
3372
3373 Unresolved items are entries whose data has been \l {insert()}{inserted} into a DelegateModelGroup
3374 instead of being derived from a DelegateModel::model index. Resolving an item will replace
3375 the item at the target index with the unresolved item. A resolved an item will reflect the data
3376 of the source model at its bound index and will move when that index moves like any other item.
3377
3378 If a new item is replaced in the DelegateModelGroup onChanged() handler its insertion and
3379 replacement will be communicated to views as an atomic operation, creating the appearance
3380 that the model contents have not changed, or if the unresolved and model item are not adjacent
3381 that the previously unresolved item has simply moved.
3382
3383*/
3384void QQmlDelegateModelGroup::resolve(QQmlV4FunctionPtr args)
3385{
3386 Q_D(QQmlDelegateModelGroup);
3387 if (!d->model)
3388 return;
3389
3390 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3391
3392 if (args->length() < 2)
3393 return;
3394
3395 int from = -1;
3396 int to = -1;
3397 Compositor::Group fromGroup = d->group;
3398 Compositor::Group toGroup = d->group;
3399
3400 QV4::Scope scope(args->v4engine());
3401 QV4::ScopedValue v(scope, (*args)[0]);
3402 if (d->parseIndex(v, &from, &fromGroup)) {
3403 if (from < 0 || from >= model->m_compositor.count(fromGroup)) {
3404 qmlWarning(this) << tr("resolve: from index out of range");
3405 return;
3406 }
3407 } else {
3408 qmlWarning(this) << tr("resolve: from index invalid");
3409 return;
3410 }
3411
3412 v = (*args)[1];
3413 if (d->parseIndex(v, &to, &toGroup)) {
3414 if (to < 0 || to >= model->m_compositor.count(toGroup)) {
3415 qmlWarning(this) << tr("resolve: to index out of range");
3416 return;
3417 }
3418 } else {
3419 qmlWarning(this) << tr("resolve: to index invalid");
3420 return;
3421 }
3422
3423 Compositor::iterator fromIt = model->m_compositor.find(fromGroup, from);
3424 Compositor::iterator toIt = model->m_compositor.find(toGroup, to);
3425
3426 if (!fromIt->isUnresolved()) {
3427 qmlWarning(this) << tr("resolve: from is not an unresolved item");
3428 return;
3429 }
3430 if (!toIt->list) {
3431 qmlWarning(this) << tr("resolve: to is not a model item");
3432 return;
3433 }
3434
3435 const int unresolvedFlags = fromIt->flags;
3436 const int resolvedFlags = toIt->flags;
3437 const int resolvedIndex = toIt.modelIndex();
3438 void * const resolvedList = toIt->list;
3439
3440 QQmlDelegateModelItem *cacheItem = model->m_cache.at(fromIt.cacheIndex());
3441 cacheItem->removeGroups(Compositor::UnresolvedFlag);
3442
3443 if (toIt.cacheIndex() > fromIt.cacheIndex())
3444 toIt.decrementIndexes(1, unresolvedFlags);
3445 if (!toIt->inGroup(fromGroup) || toIt.index[fromGroup] > from)
3446 from += 1;
3447
3448 model->itemsMoved(
3449 QList<Compositor::Remove>(1, Compositor::Remove(fromIt, 1, unresolvedFlags, 0)),
3450 QList<Compositor::Insert>(1, Compositor::Insert(toIt, 1, unresolvedFlags, 0)));
3451 model->itemsInserted(
3452 QList<Compositor::Insert>(1, Compositor::Insert(toIt, 1, (resolvedFlags & ~unresolvedFlags) | Compositor::CacheFlag)));
3453 toIt.incrementIndexes(1, resolvedFlags | unresolvedFlags);
3454 model->itemsRemoved(QList<Compositor::Remove>(1, Compositor::Remove(toIt, 1, resolvedFlags)));
3455
3456 model->m_compositor.setFlags(toGroup, to, 1, unresolvedFlags & ~Compositor::UnresolvedFlag);
3457 model->m_compositor.clearFlags(fromGroup, from, 1, unresolvedFlags);
3458
3459 if (resolvedFlags & Compositor::CacheFlag)
3460 model->m_compositor.insert(
3461 Compositor::Cache, toIt.cacheIndex(), resolvedList,
3462 resolvedIndex, 1, Compositor::CacheFlag);
3463
3464 Q_ASSERT(model->m_cache.size() == model->m_compositor.count(Compositor::Cache));
3465
3466 if (!cacheItem->isScriptReferenced() && !cacheItem->object()) {
3467 Q_ASSERT(toIt.cacheIndex() == model->m_cache.indexOf(cacheItem));
3468 model->m_cache.removeAt(toIt.cacheIndex());
3469 model->m_compositor.clearFlags(
3470 Compositor::Cache, toIt.cacheIndex(), 1, Compositor::CacheFlag);
3471 delete cacheItem;
3472 Q_ASSERT(model->m_cache.size() == model->m_compositor.count(Compositor::Cache));
3473 } else {
3474 cacheItem->resolveIndex(model->m_adaptorModel, resolvedIndex);
3475 if (QQmlDelegateModelAttached *attached = cacheItem->attached())
3476 attached->emitUnresolvedChanged();
3477 }
3478
3479 model->emitChanges();
3480}
3481
3482/*!
3483 \qmlmethod void QtQml.Models::DelegateModelGroup::remove(int index, int count)
3484
3485 Removes \a count items starting at \a index from the group.
3486*/
3487
3488void QQmlDelegateModelGroup::remove(QQmlV4FunctionPtr args)
3489{
3490 Q_D(QQmlDelegateModelGroup);
3491 if (!d->model)
3492 return;
3493 Compositor::Group group = d->group;
3494 int index = -1;
3495 int count = 1;
3496
3497 if (args->length() == 0)
3498 return;
3499
3500 int i = 0;
3501 QV4::Scope scope(args->v4engine());
3502 QV4::ScopedValue v(scope, (*args)[0]);
3503 if (!d->parseIndex(v, &index, &group)) {
3504 qmlWarning(this) << tr("remove: invalid index");
3505 return;
3506 }
3507
3508 if (++i < args->length()) {
3509 v = (*args)[i];
3510 if (v->isNumber())
3511 count = v->toInt32();
3512 }
3513
3514 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3515 if (index < 0 || index >= model->m_compositor.count(group)) {
3516 qmlWarning(this) << tr("remove: index out of range");
3517 } else if (count != 0) {
3518 Compositor::iterator it = model->m_compositor.find(group, index);
3519 if (count < 0 || count > model->m_compositor.count(d->group) - it.index[d->group]) {
3520 qmlWarning(this) << tr("remove: invalid count");
3521 } else {
3522 model->removeGroups(it, count, d->group, 1 << d->group);
3523 }
3524 }
3525}
3526
3528 QQmlV4FunctionPtr args, Compositor::Group *group, int *index, int *count, int *groups) const
3529{
3530 if (!model || !QQmlDelegateModelPrivate::get(model)->m_cacheMetaType)
3531 return false;
3532
3533 if (args->length() < 2)
3534 return false;
3535
3536 int i = 0;
3537 QV4::Scope scope(args->v4engine());
3538 QV4::ScopedValue v(scope, (*args)[i]);
3539 if (!parseIndex(v, index, group))
3540 return false;
3541
3542 v = (*args)[++i];
3543 if (v->isNumber()) {
3544 *count = v->toInt32();
3545
3546 if (++i == args->length())
3547 return false;
3548 v = (*args)[i];
3549 }
3550
3551 *groups = QQmlDelegateModelPrivate::get(model)->m_cacheMetaType->parseGroups(v);
3552
3553 return true;
3554}
3555
3556/*!
3557 \qmlmethod void QtQml.Models::DelegateModelGroup::addGroups(int index, int count, list<string> groups)
3558
3559 Adds \a count items starting at \a index to \a groups.
3560*/
3561
3562void QQmlDelegateModelGroup::addGroups(QQmlV4FunctionPtr args)
3563{
3564 Q_D(QQmlDelegateModelGroup);
3565 Compositor::Group group = d->group;
3566 int index = -1;
3567 int count = 1;
3568 int groups = 0;
3569
3570 if (!d->parseGroupArgs(args, &group, &index, &count, &groups))
3571 return;
3572
3573 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3574 if (index < 0 || index >= model->m_compositor.count(group)) {
3575 qmlWarning(this) << tr("addGroups: index out of range");
3576 } else if (count != 0) {
3577 Compositor::iterator it = model->m_compositor.find(group, index);
3578 if (count < 0 || count > model->m_compositor.count(d->group) - it.index[d->group]) {
3579 qmlWarning(this) << tr("addGroups: invalid count");
3580 } else {
3581 model->addGroups(it, count, d->group, groups);
3582 }
3583 }
3584}
3585
3586/*!
3587 \qmlmethod void QtQml.Models::DelegateModelGroup::removeGroups(int index, int count, list<string> groups)
3588
3589 Removes \a count items starting at \a index from \a groups.
3590*/
3591
3592void QQmlDelegateModelGroup::removeGroups(QQmlV4FunctionPtr args)
3593{
3594 Q_D(QQmlDelegateModelGroup);
3595 Compositor::Group group = d->group;
3596 int index = -1;
3597 int count = 1;
3598 int groups = 0;
3599
3600 if (!d->parseGroupArgs(args, &group, &index, &count, &groups))
3601 return;
3602
3603 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3604 if (index < 0 || index >= model->m_compositor.count(group)) {
3605 qmlWarning(this) << tr("removeGroups: index out of range");
3606 } else if (count != 0) {
3607 Compositor::iterator it = model->m_compositor.find(group, index);
3608 if (count < 0 || count > model->m_compositor.count(d->group) - it.index[d->group]) {
3609 qmlWarning(this) << tr("removeGroups: invalid count");
3610 } else {
3611 model->removeGroups(it, count, d->group, groups);
3612 }
3613 }
3614}
3615
3616/*!
3617 \qmlmethod void QtQml.Models::DelegateModelGroup::setGroups(int index, int count, list<string> groups)
3618
3619 Changes the group membership of \a count items starting at \a index. The items are removed from
3620 their existing groups and added to \a groups.
3621*/
3622
3623void QQmlDelegateModelGroup::setGroups(QQmlV4FunctionPtr args)
3624{
3625 Q_D(QQmlDelegateModelGroup);
3626 Compositor::Group group = d->group;
3627 int index = -1;
3628 int count = 1;
3629 int groups = 0;
3630
3631 if (!d->parseGroupArgs(args, &group, &index, &count, &groups))
3632 return;
3633
3634 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3635 if (index < 0 || index >= model->m_compositor.count(group)) {
3636 qmlWarning(this) << tr("setGroups: index out of range");
3637 } else if (count != 0) {
3638 Compositor::iterator it = model->m_compositor.find(group, index);
3639 if (count < 0 || count > model->m_compositor.count(d->group) - it.index[d->group]) {
3640 qmlWarning(this) << tr("setGroups: invalid count");
3641 } else {
3642 model->setGroups(it, count, d->group, groups);
3643 }
3644 }
3645}
3646
3647/*!
3648 \qmlmethod void QtQml.Models::DelegateModelGroup::move(var from, var to, int count)
3649
3650 Moves \a count at \a from in a group \a to a new position.
3651
3652 \note The DelegateModel acts as a proxy model: it holds the delegates in a
3653 different order than the \l{dm-model-property}{underlying model} has them.
3654 Any subsequent changes to the underlying model will not undo whatever
3655 reordering you have done via this function.
3656*/
3657
3658void QQmlDelegateModelGroup::move(QQmlV4FunctionPtr args)
3659{
3660 Q_D(QQmlDelegateModelGroup);
3661
3662 if (args->length() < 2)
3663 return;
3664
3665 Compositor::Group fromGroup = d->group;
3666 Compositor::Group toGroup = d->group;
3667 int from = -1;
3668 int to = -1;
3669 int count = 1;
3670
3671 QV4::Scope scope(args->v4engine());
3672 QV4::ScopedValue v(scope, (*args)[0]);
3673 if (!d->parseIndex(v, &from, &fromGroup)) {
3674 qmlWarning(this) << tr("move: invalid from index");
3675 return;
3676 }
3677
3678 v = (*args)[1];
3679 if (!d->parseIndex(v, &to, &toGroup)) {
3680 qmlWarning(this) << tr("move: invalid to index");
3681 return;
3682 }
3683
3684 if (args->length() > 2) {
3685 v = (*args)[2];
3686 if (v->isNumber())
3687 count = v->toInt32();
3688 }
3689
3690 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(d->model);
3691
3692 if (count < 0) {
3693 qmlWarning(this) << tr("move: invalid count");
3694 } else if (from < 0 || from + count > model->m_compositor.count(fromGroup)) {
3695 qmlWarning(this) << tr("move: from index out of range");
3696 } else if (!model->m_compositor.verifyMoveTo(fromGroup, from, toGroup, to, count, d->group)) {
3697 qmlWarning(this) << tr("move: to index out of range");
3698 } else if (count > 0) {
3699 QList<Compositor::Remove> removes;
3700 QList<Compositor::Insert> inserts;
3701
3702 model->m_compositor.move(fromGroup, from, toGroup, to, count, d->group, &removes, &inserts);
3703 model->itemsMoved(removes, inserts);
3704 model->emitChanges();
3705 }
3706
3707}
3708
3709/*!
3710 \qmlsignal QtQml.Models::DelegateModelGroup::changed(array removed, array inserted)
3711
3712 This signal is emitted when items have been removed from or inserted into the group.
3713
3714 Each object in the \a removed and \a inserted arrays has two values; the \e index of the first
3715 item inserted or removed and a \e count of the number of consecutive items inserted or removed.
3716
3717 Each index is adjusted for previous changes with all removed items preceding any inserted
3718 items.
3719*/
3720
3721//============================================================================
3722
3723QQmlPartsModel::QQmlPartsModel(QQmlDelegateModel *model, const QString &part, QObject *parent)
3724 : QQmlInstanceModel(*new QObjectPrivate, parent)
3725 , m_model(model)
3726 , m_part(part)
3727 , m_compositorGroup(Compositor::Cache)
3728 , m_inheritGroup(true)
3729{
3730 QQmlDelegateModelPrivate *d = QQmlDelegateModelPrivate::get(m_model);
3731 if (d->m_cacheMetaType) {
3732 QQmlDelegateModelGroupPrivate::get(d->m_groups[1])->emitters.insert(this);
3733 m_compositorGroup = Compositor::Default;
3734 } else {
3735 d->m_pendingParts.insert(this);
3736 }
3737}
3738
3742
3744{
3745 if (m_inheritGroup)
3746 return m_model->filterGroup();
3747 return m_filterGroup;
3748}
3749
3750void QQmlPartsModel::setFilterGroup(const QString &group)
3751{
3752 if (QQmlDelegateModelPrivate::get(m_model)->m_transaction) {
3753 qmlWarning(this) << tr("The group of a DelegateModel cannot be changed within onChanged");
3754 return;
3755 }
3756
3757 if (m_filterGroup != group || m_inheritGroup) {
3758 m_filterGroup = group;
3759 m_inheritGroup = false;
3761
3762 emit filterGroupChanged();
3763 }
3764}
3765
3767{
3768 if (!m_inheritGroup) {
3769 m_inheritGroup = true;
3771 emit filterGroupChanged();
3772 }
3773}
3774
3776{
3777 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3778 if (!model->m_cacheMetaType)
3779 return;
3780
3781 if (m_inheritGroup) {
3782 if (m_filterGroup == model->m_filterGroup)
3783 return;
3784 m_filterGroup = model->m_filterGroup;
3785 }
3786
3787 QQmlListCompositor::Group previousGroup = m_compositorGroup;
3788 m_compositorGroup = Compositor::Default;
3789 QQmlDelegateModelGroupPrivate::get(model->m_groups[Compositor::Default])->emitters.insert(this);
3790 for (int i = 1; i < model->m_groupCount; ++i) {
3791 if (m_filterGroup == model->m_cacheMetaType->groupNames.at(i - 1)) {
3792 m_compositorGroup = Compositor::Group(i);
3793 break;
3794 }
3795 }
3796
3797 QQmlDelegateModelGroupPrivate::get(model->m_groups[m_compositorGroup])->emitters.insert(this);
3798 if (m_compositorGroup != previousGroup) {
3799 QList<QQmlChangeSet::Change> removes;
3800 QList<QQmlChangeSet::Change> inserts;
3801 model->m_compositor.transition(previousGroup, m_compositorGroup, &removes, &inserts);
3802
3803 QQmlChangeSet changeSet;
3804 changeSet.move(removes, inserts);
3805 if (!changeSet.isEmpty())
3806 emit modelUpdated(changeSet, false);
3807
3808 if (changeSet.difference() != 0)
3809 emit countChanged();
3810 }
3811}
3812
3814 Compositor::Group group, const QQmlChangeSet &changeSet)
3815{
3816 if (!m_inheritGroup)
3817 return;
3818
3819 m_compositorGroup = group;
3820 QQmlDelegateModelGroupPrivate::get(QQmlDelegateModelPrivate::get(m_model)->m_groups[m_compositorGroup])->emitters.insert(this);
3821
3822 if (!changeSet.isEmpty())
3823 emit modelUpdated(changeSet, false);
3824
3825 if (changeSet.difference() != 0)
3826 emit countChanged();
3827
3828 emit filterGroupChanged();
3829}
3830
3832{
3833 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3834 return model->m_delegate
3835 ? model->m_compositor.count(m_compositorGroup)
3836 : 0;
3837}
3838
3840{
3841 return m_model->isValid();
3842}
3843
3844QObject *QQmlPartsModel::object(int index, QQmlIncubator::IncubationMode incubationMode)
3845{
3846 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3847
3848 if (!model->m_delegate || index < 0 || index >= model->m_compositor.count(m_compositorGroup)) {
3849 qWarning() << "DelegateModel::item: index out range" << index << model->m_compositor.count(m_compositorGroup);
3850 return nullptr;
3851 }
3852
3853 QObject *object = model->object(m_compositorGroup, index, incubationMode);
3854
3855 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object)) {
3856 QObject *part = package->part(m_part);
3857 if (!part)
3858 return nullptr;
3859 m_packaged.insert(part, package);
3860 return part;
3861 }
3862
3863 model->release(object);
3864 if (!model->m_delegateValidated) {
3865 if (object)
3866 qmlWarning(model->m_delegate) << tr("Delegate component must be Package type.");
3867 model->m_delegateValidated = true;
3868 }
3869
3870 return nullptr;
3871}
3872
3874{
3875 QQmlInstanceModel::ReleaseFlags flags;
3876
3877 auto it = m_packaged.find(item);
3878 if (it != m_packaged.end()) {
3879 QQuickPackage *package = *it;
3880 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3881 flags = model->release(package);
3882 m_packaged.erase(it);
3883 if (!m_packaged.contains(item))
3884 flags &= ~Referenced;
3885 if (flags & Destroyed)
3886 QQmlDelegateModelPrivate::get(m_model)->emitDestroyingPackage(package);
3887 }
3888 return flags;
3889}
3890
3891QVariant QQmlPartsModel::variantValue(int index, const QString &role)
3892{
3893 return QQmlDelegateModelPrivate::get(m_model)->variantValue(m_compositorGroup, index, role);
3894}
3895
3896void QQmlPartsModel::setWatchedRoles(const QList<QByteArray> &roles)
3897{
3898 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3899 model->m_adaptorModel.replaceWatchedRoles(m_watchedRoles, roles);
3900 m_watchedRoles = roles;
3901}
3902
3904{
3905 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3906 Compositor::iterator it = model->m_compositor.find(model->m_compositorGroup, index);
3907 if (!it->inCache())
3908 return QQmlIncubator::Null;
3909
3910 if (auto incubationTask = model->m_cache.at(it.cacheIndex())->incubationTask())
3911 return incubationTask->status();
3912
3913 return QQmlIncubator::Ready;
3914}
3915
3916int QQmlPartsModel::indexOf(QObject *item, QObject *) const
3917{
3918 auto it = m_packaged.find(item);
3919 if (it != m_packaged.end()) {
3920 if (QQmlDelegateModelItem *cacheItem = QQmlDelegateModelItem::dataForObject(*it))
3921 return cacheItem->groupIndex(m_compositorGroup);
3922 }
3923 return -1;
3924}
3925
3926void QQmlPartsModel::createdPackage(int index, QQuickPackage *package)
3927{
3928 emit createdItem(index, package->part(m_part));
3929}
3930
3931void QQmlPartsModel::initPackage(int index, QQuickPackage *package)
3932{
3933 if (m_modelUpdatePending)
3934 m_pendingPackageInitializations << index;
3935 else
3936 emit initItem(index, package->part(m_part));
3937}
3938
3939void QQmlPartsModel::destroyingPackage(QQuickPackage *package)
3940{
3941 QObject *item = package->part(m_part);
3942 Q_ASSERT(!m_packaged.contains(item));
3943 emit destroyingItem(item);
3944}
3945
3946void QQmlPartsModel::emitModelUpdated(const QQmlChangeSet &changeSet, bool reset)
3947{
3948 m_modelUpdatePending = false;
3949 emit modelUpdated(changeSet, reset);
3950 if (changeSet.difference() != 0)
3951 emit countChanged();
3952
3953 QQmlDelegateModelPrivate *model = QQmlDelegateModelPrivate::get(m_model);
3954 QList<int> pendingPackageInitializations;
3955 qSwap(pendingPackageInitializations, m_pendingPackageInitializations);
3956 for (int index : pendingPackageInitializations) {
3957 if (!model->m_delegate || index < 0 || index >= model->m_compositor.count(m_compositorGroup))
3958 continue;
3959 QObject *object = model->object(m_compositorGroup, index, QQmlIncubator::Asynchronous);
3960 if (QQuickPackage *package = qmlobject_cast<QQuickPackage *>(object))
3961 emit initItem(index, package->part(m_part));
3962 model->release(object);
3963 }
3964}
3965
3966bool QQmlReusableDelegateModelItemsPool::insertItem(QQmlDelegateModelItem *modelItem)
3967{
3968 // We can only hold INT_MAX items, due to the return type of size().
3969 if (Q_UNLIKELY(m_reusableItemsPool.size() == QQmlReusableDelegateModelItemsPool::MaxSize))
3970 return false;
3971
3972 Q_ASSERT(m_reusableItemsPool.size() < QQmlReusableDelegateModelItemsPool::MaxSize);
3973
3974 // Currently, the only way for a view to reuse items is to call release()
3975 // in the model class with the second argument explicitly set to
3976 // QQmlReuseableDelegateModelItemsPool::Reusable. If the released item is
3977 // no longer referenced, it will be added to the pool. Reusing of items can
3978 // be specified per item, in case certain items cannot be recycled. A
3979 // QQmlDelegateModelItem knows which delegate its object was created from.
3980 // So when we are about to create a new item, we first check if the pool
3981 // contains an item based on the same delegate from before. If so, we take
3982 // it out of the pool (instead of creating a new item), and update all its
3983 // context properties and attached properties.
3984
3985 // When a view is recycling items, it should call drain() regularly. As
3986 // there is currently no logic to 'hibernate' items in the pool, they are
3987 // only meant to rest there for a short while, ideally only from the time
3988 // e.g a row is unloaded on one side of the view, and until a new row is
3989 // loaded on the opposite side. Between these times, the application will
3990 // see the item as fully functional and 'alive' (just not visible on
3991 // screen). Since this time is supposed to be short, we don't take any
3992 // action to notify the application about it, since we don't want to
3993 // trigger any bindings that can disturb performance.
3994
3995 // A recommended time for calling drain() is each time a view has finished
3996 // loading e.g a new row or column. If there are more items in the pool
3997 // after that, it means that the view most likely doesn't need them anytime
3998 // soon. Those items should be destroyed to reduce resource consumption.
3999
4000 // Depending on if a view is a list or a table, it can sometimes be
4001 // performant to keep items in the pool for a bit longer than one "row
4002 // out/row in" cycle. E.g for a table, if the number of visible rows in a
4003 // view is much larger than the number of visible columns. In that case, if
4004 // you flick out a row, and then flick in a column, you would throw away a
4005 // lot of items in the pool if completely draining it. The reason is that
4006 // unloading a row places more items in the pool than what ends up being
4007 // recycled when loading a new column. And then, when you next flick in a
4008 // new row, you would need to load all those drained items again from
4009 // scratch. For that reason, you can specify a maxPoolTime to the
4010 // drainReusableItemsPool() that allows you to keep items in the pool for a
4011 // bit longer, effectively keeping more items in circulation. A recommended
4012 // maxPoolTime would be equal to the number of dimensions in the view,
4013 // which means 1 for a list view and 2 for a table view. If you specify 0,
4014 // all items will be drained.
4015
4016 Q_ASSERT(!modelItem->incubationTask());
4017 Q_ASSERT(!modelItem->isObjectReferenced());
4018 Q_ASSERT(modelItem->object());
4019 Q_ASSERT(modelItem->delegate());
4020
4021 m_reusableItemsPool.push_back({modelItem, 0});
4022
4023 qCDebug(lcItemViewDelegateRecycling)
4024 << "item:" << modelItem
4025 << "delegate:" << modelItem->delegate()
4026 << "index:" << modelItem->modelIndex()
4027 << "row:" << modelItem->modelRow()
4028 << "column:" << modelItem->modelColumn()
4029 << "pool size:" << m_reusableItemsPool.size();
4030
4031 return true;
4032}
4033
4034QQmlDelegateModelItem *QQmlReusableDelegateModelItemsPool::takeItem(const QQmlComponent *delegate, int newIndexHint)
4035{
4036 // Find the oldest item in the pool that was made from the same delegate as
4037 // the given argument, remove it from the pool, and return it.
4038 for (auto it = m_reusableItemsPool.cbegin(); it != m_reusableItemsPool.cend(); ++it) {
4039 QQmlDelegateModelItem *modelItem = it->item;
4040 if (modelItem->delegate() != delegate)
4041 continue;
4042 m_reusableItemsPool.erase(it);
4043
4044 qCDebug(lcItemViewDelegateRecycling)
4045 << "item:" << modelItem
4046 << "delegate:" << delegate
4047 << "old index:" << modelItem->modelIndex()
4048 << "old row:" << modelItem->modelRow()
4049 << "old column:" << modelItem->modelColumn()
4050 << "new index:" << newIndexHint
4051 << "pool size:" << m_reusableItemsPool.size();
4052
4053 return modelItem;
4054 }
4055
4056 qCDebug(lcItemViewDelegateRecycling)
4057 << "no available item for delegate:" << delegate
4058 << "new index:" << newIndexHint
4059 << "pool size:" << m_reusableItemsPool.size();
4060
4061 return nullptr;
4062}
4063
4064void QQmlReusableDelegateModelItemsPool::drain(int maxPoolTime, std::function<void(QQmlDelegateModelItem *cacheItem)> releaseItem)
4065{
4066 // Rather than releasing all pooled items upon a call to this function, each
4067 // item has a poolTime. The poolTime specifies for how many loading cycles an item
4068 // has been resting in the pool. And for each invocation of this function, poolTime
4069 // will increase. If poolTime is equal to, or exceeds, maxPoolTime, it will be removed
4070 // from the pool and released. This way, the view can tweak a bit for how long
4071 // items should stay in "circulation", even if they are not recycled right away.
4072 qCDebug(lcItemViewDelegateRecycling) << "pool size before drain:" << m_reusableItemsPool.size();
4073
4074 if (maxPoolTime == 0) {
4075 // Special-case 0 because it's so common and so easy to handle.
4076 const std::vector<PoolItem> removed = std::exchange(m_reusableItemsPool, {});
4077 for (const PoolItem &item : removed)
4078 releaseItem(item.item);
4079 qCDebug(lcItemViewDelegateRecycling) << "pool size after drain: 0";
4080 return;
4081 }
4082
4083 const auto begin = m_reusableItemsPool.begin();
4084 const auto oldEnd = m_reusableItemsPool.end();
4085 const auto newEnd = std::stable_partition(
4086 begin, oldEnd,
4087 [maxPoolTime](const PoolItem &item) { return item.poolTime < maxPoolTime; });
4088 std::for_each(begin, newEnd, [](PoolItem &item) { ++item.poolTime; });
4089
4090 QVarLengthArray<PoolItem> removed;
4091 removed.reserve(oldEnd - newEnd);
4092 std::move(newEnd, oldEnd, std::back_inserter(removed));
4093 m_reusableItemsPool.erase(newEnd, oldEnd);
4094
4095 for (const PoolItem &item : removed)
4096 releaseItem(item.item);
4097
4098 qCDebug(lcItemViewDelegateRecycling) << "pool size after drain:" << m_reusableItemsPool.size();
4099}
4100
4101//============================================================================
4102
4104{
4105 V4_OBJECT2(QQmlDelegateModelGroupChange, QV4::Object)
4106
4107 static QV4::Heap::QQmlDelegateModelGroupChange *create(QV4::ExecutionEngine *e) {
4108 return e->memoryManager->allocate<QQmlDelegateModelGroupChange>();
4109 }
4110
4111 static QV4::ReturnedValue method_get_index(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int) {
4112 QV4::Scope scope(b);
4113 QV4::Scoped<QQmlDelegateModelGroupChange> that(scope, thisObject->as<QQmlDelegateModelGroupChange>());
4114 if (!that)
4115 THROW_TYPE_ERROR();
4116 return QV4::Encode(that->d()->change.index);
4117 }
4118 static QV4::ReturnedValue method_get_count(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int) {
4119 QV4::Scope scope(b);
4120 QV4::Scoped<QQmlDelegateModelGroupChange> that(scope, thisObject->as<QQmlDelegateModelGroupChange>());
4121 if (!that)
4122 THROW_TYPE_ERROR();
4123 return QV4::Encode(that->d()->change.count);
4124 }
4125 static QV4::ReturnedValue method_get_moveId(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int) {
4126 QV4::Scope scope(b);
4127 QV4::Scoped<QQmlDelegateModelGroupChange> that(scope, thisObject->as<QQmlDelegateModelGroupChange>());
4128 if (!that)
4129 THROW_TYPE_ERROR();
4130 if (that->d()->change.moveId < 0)
4131 RETURN_UNDEFINED();
4132 return QV4::Encode(that->d()->change.moveId);
4133 }
4134};
4135
4137
4139{
4140 V4_OBJECT2(QQmlDelegateModelGroupChangeArray, QV4::Object)
4142public:
4147
4148 quint32 count() const { return d()->changes->size(); }
4149 const QQmlChangeSet::Change &at(int index) const { return d()->changes->at(index); }
4150
4152 {
4153 if (id.isArrayIndex()) {
4156 QV4::ExecutionEngine *v4 = static_cast<const QQmlDelegateModelGroupChangeArray *>(m)->engine();
4157 QV4::Scope scope(v4);
4159
4160 if (index >= array->count()) {
4161 if (hasProperty)
4162 *hasProperty = false;
4164 }
4165
4167
4171 object->d()->change = change;
4172
4173 if (hasProperty)
4174 *hasProperty = true;
4175 return object.asReturnedValue();
4176 }
4177
4180
4181 if (id == array->engine()->id_length()->propertyKey()) {
4182 if (hasProperty)
4183 *hasProperty = true;
4184 return QV4::Encode(array->count());
4185 }
4186
4188 }
4189};
4190
4191void QV4::Heap::QQmlDelegateModelGroupChangeArray::init(const QList<QQmlChangeSet::Change> &changes)
4192{
4193 Object::init();
4194 this->changes = new QList<QQmlChangeSet::Change>(changes);
4195 QV4::Scope scope(internalClass->engine);
4196 QV4::ScopedObject o(scope, this);
4197 o->setArrayType(QV4::Heap::ArrayData::Custom);
4198}
4199
4201
4203{
4204 QV4::Scope scope(v4);
4205
4206 QV4::ScopedObject proto(scope, v4->newObject());
4207 proto->defineAccessorProperty(QStringLiteral("index"), QQmlDelegateModelGroupChange::method_get_index, nullptr);
4208 proto->defineAccessorProperty(QStringLiteral("count"), QQmlDelegateModelGroupChange::method_get_count, nullptr);
4209 proto->defineAccessorProperty(QStringLiteral("moveId"), QQmlDelegateModelGroupChange::method_get_moveId, nullptr);
4210 changeProto.set(v4, proto);
4211}
4212
4216
4218 const QList<QQmlChangeSet::Change> &changes)
4219{
4220 QV4::Scope scope(v4);
4221 QV4::ScopedObject o(scope, QQmlDelegateModelGroupChangeArray::create(v4, changes));
4222 return o.asReturnedValue();
4223}
4224
4225QT_END_NAMESPACE
4226
4227#include "moc_qqmldelegatemodel_p_p.cpp"
4228
4229#include "moc_qqmldelegatemodel_p.cpp"
void initializeRequiredProperties(QQmlDelegateModelItem *modelItemToIncubate, QObject *object, QQmlDelegateModel::DelegateModelAccess access)
void statusChanged(Status) override
Called when the status of the incubator changes.
void setInitialState(QObject *) override
Called after the object is first created, but before complex property bindings are evaluated and,...
QQmlDelegateModelItem * incubating
QQmlDelegateModelPrivate * vdm
QQmlDelegateModelAttachedMetaObject(QQmlDelegateModelItemMetaType *metaType, QMetaObject *metaObject)
int metaCall(QObject *, QMetaObject::Call, int _id, void **) override
QQmlDelegateModelAttached(QQmlDelegateModelItem *cacheItem, QObject *parent)
void setGroups(const QStringList &groups)
bool isUnresolved() const
\qmlattachedproperty bool QtQml.Models::DelegateModel::isUnresolved
void emitChanges()
\qmlattachedproperty bool QtQml.Models::DelegateModel::inItems
void setInPersistedItems(bool inPersisted)
QQmlDelegateModel * model() const
\qmlattachedproperty model QtQml.Models::DelegateModel::model
QStringList groups() const
\qmlattachedproperty list<string> QtQml.Models::DelegateModel::groups
QQmlDelegateModelItem * m_cacheItem
QV4::ReturnedValue array(QV4::ExecutionEngine *engine, const QList< QQmlChangeSet::Change > &changes)
QQmlDelegateModelEngineData(QV4::ExecutionEngine *v4)
virtual void initPackage(int, QQuickPackage *)
virtual void destroyingPackage(QQuickPackage *)
virtual void createdPackage(int, QQuickPackage *)
bool parseIndex(const QV4::Value &value, int *index, Compositor::Group *group) const
void createdPackage(int index, QQuickPackage *package)
static QQmlDelegateModelGroupPrivate * get(QQmlDelegateModelGroup *group)
bool parseGroupArgs(QQmlV4FunctionPtr args, Compositor::Group *group, int *index, int *count, int *groups) const
void initPackage(int index, QQuickPackage *package)
QQmlDelegateModelGroupEmitterList emitters
void destroyingPackage(QQuickPackage *package)
void emitChanges(QV4::ExecutionEngine *engine)
void propertyCreated(int, QMetaPropertyBuilder &) override
void setInitialState(QQDMIncubationTask *incubationTask, QObject *o)
void removeCacheItem(QQmlDelegateModelItem *cacheItem)
QVariant variantValue(Compositor::Group group, int index, const QString &name)
void emitCreatedPackage(QQDMIncubationTask *incubationTask, QQuickPackage *package)
void itemsMoved(const QList< Compositor::Remove > &removes, const QList< Compositor::Insert > &inserts)
QQmlDelegateModelParts * m_parts
QQmlAbstractDelegateComponent * m_delegateChooser
void itemsInserted(const QList< Compositor::Insert > &inserts)
void addCacheItem(QQmlDelegateModelItem *item, Compositor::iterator it)
void reuseItem(QQmlDelegateModelItem *item, int newModelIndex, int newGroups)
void drainReusableItemsPool(int maxPoolTime)
void itemsRemoved(const QList< Compositor::Remove > &removes, QVarLengthArray< QList< QQmlChangeSet::Change >, Compositor::MaximumGroupCount > *translatedRemoves, QHash< int, QList< QQmlDelegateModelItem * > > *movedItems=nullptr)
QQmlDelegateModelGroupEmitterList m_pendingParts
void emitModelUpdated(const QQmlChangeSet &changeSet, bool reset) override
QObject * object(Compositor::Group group, int index, QQmlIncubator::IncubationMode incubationMode)
void destroyCacheItem(QQmlDelegateModelItem *cacheItem)
void itemsRemoved(const QList< Compositor::Remove > &removes)
InsertionResult insert(Compositor::insert_iterator &before, const QV4::Value &object, int groups)
void setGroups(Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
void delegateChanged(bool add=true, bool remove=true)
void releaseIncubator(QQDMIncubationTask *incubationTask)
void itemsInserted(const QList< Compositor::Insert > &inserts, QVarLengthArray< QList< QQmlChangeSet::Change >, Compositor::MaximumGroupCount > *translatedInserts, QHash< int, QList< QQmlDelegateModelItem * > > *movedItems=nullptr)
void incubatorStatusChanged(QQDMIncubationTask *incubationTask, QQmlIncubator::Status status)
void emitInitPackage(QQDMIncubationTask *incubationTask, QQuickPackage *package)
void addGroups(Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
void emitDestroyingPackage(QQuickPackage *package)
QQmlComponent * resolveDelegate(int index)
void removeGroups(Compositor::iterator from, int count, Compositor::Group group, int groupFlags)
void itemsChanged(const QList< Compositor::Change > &changes)
void emitModelUpdated(const QQmlChangeSet &changeSet, bool reset) override
QVariant variantValue(int index, const QString &role) override
int count() const override
QObject * object(int index, QQmlIncubator::IncubationMode incubationMode=QQmlIncubator::AsynchronousIfNested) override
void updateFilterGroup(Compositor::Group group, const QQmlChangeSet &changeSet)
void setFilterGroup(const QString &group)
QQmlIncubator::Status incubationStatus(int index) override
int indexOf(QObject *item, QObject *objectContext) const override
void destroyingPackage(QQuickPackage *package) override
void setWatchedRoles(const QList< QByteArray > &roles) override
ReleaseFlags release(QObject *item, ReusableFlag reusable=NotReusable) override
void createdPackage(int index, QQuickPackage *package) override
void initPackage(int index, QQuickPackage *package) override
QString filterGroup() const
bool isValid() const override
bool insertItem(QQmlDelegateModelItem *modelItem)
void drain(int maxPoolTime, std::function< void(QQmlDelegateModelItem *cacheItem)> releaseItem)
QQmlDelegateModelItem * takeItem(const QQmlComponent *delegate, int newIndexHint)
Combined button and popup list for selecting options.
Definition qjsvalue.h:24
static bool isDoneIncubating(QQmlIncubator::Status status)
DEFINE_OBJECT_VTABLE(QQmlDelegateModelGroupChange)
DEFINE_OBJECT_VTABLE(QV4::DelegateModelGroupFunction)
DEFINE_OBJECT_VTABLE(QQmlDelegateModelItemObject)
static void incrementIndexes(QQmlDelegateModelItem *cacheItem, int count, const int *deltas)
DEFINE_OBJECT_VTABLE(QQmlDelegateModelGroupChangeArray)
QQmlDelegateModelGroupEmitterList::iterator GroupEmitterListIt
static QV4::ReturnedValue method_get_index(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
static QV4::ReturnedValue method_get_moveId(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
static QV4::Heap::QQmlDelegateModelGroupChange * create(QV4::ExecutionEngine *e)
static QV4::ReturnedValue method_get_count(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
static ReturnedValue virtualCall(const QV4::FunctionObject *that, const Value *thisObject, const Value *argv, int argc)
static Heap::DelegateModelGroupFunction * create(QV4::ExecutionEngine *engine, uint flag, QV4::ReturnedValue(*code)(QQmlDelegateModelItem *, uint, const QV4::Value &))
void init(ExecutionEngine *engine, uint flag, QV4::ReturnedValue(*code)(QQmlDelegateModelItem *item, uint flag, const QV4::Value &arg))
QV4::ReturnedValue(*) code(QQmlDelegateModelItem *item, uint flag, const QV4::Value &arg)
void init(const QList< QQmlChangeSet::Change > &changes)