-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqobjecttreemodel.cpp
More file actions
1576 lines (1346 loc) · 55.5 KB
/
qobjecttreemodel.cpp
File metadata and controls
1576 lines (1346 loc) · 55.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "qobjecttreemodel.h"
#include <algorithm>
#include <memory>
#include <ranges>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QEvent>
#include <QtCore/QThread>
#include <QtCore/private/qabstractitemmodel_p.h>
#include <QtCore/private/qobject_p.h>
#include <QtCore/qnamespace.h>
#ifdef QT_WIDGETS_LIB
#include <QtWidgets/QWidget>
#endif
using namespace Qt::Literals::StringLiterals;
namespace {
void InsertUniqueEventFilter(QObject *object, QObject *filter)
{
#if defined(QT_DEBUG)
Q_ASSERT(object);
Q_ASSERT(filter);
auto *objectPriv = QObjectPrivate::get(object);
if (auto *extraData = objectPriv->extraData) {
Q_ASSERT(!extraData->eventFilters.contains(filter));
}
#endif
object->installEventFilter(filter);
}
void CheckRemoveEventFilter(QObject *object, QObject *filter)
{
#if defined(QT_DEBUG)
Q_ASSERT(object);
Q_ASSERT(filter);
auto *objectPriv = QObjectPrivate::get(object);
auto *extraData = objectPriv->extraData;
Q_ASSERT(extraData);
Q_ASSERT(extraData->eventFilters.contains(filter));
#endif
object->removeEventFilter(filter);
}
bool IsValid(const QObject *obj)
{
const auto *objPriv = QObjectPrivate::get(obj);
return !(objPriv->deleteLaterCalled || objPriv->wasDeleted);
}
// Returns true if object1 is a descendant of object2.
bool IsDescendantOf(QObject *object1, QObject *object2)
{
QObject *obj{object1};
while (obj) {
if (obj == object2) {
return true;
}
obj = obj->parent();
}
return false;
}
// Clamp the requested index into the valid range for the parent's children
// list. Negative values index from the end (-1 = last, -2 = second-to-last).
// Values beyond the end are clamped.
qsizetype BoundIndex(QObject *object, QObject *parent, int index)
{
qsizetype siblingCount{parent->children().count()};
if (object->parent() == parent)
siblingCount -= 1; // The object itself doesn't count.
qsizetype b{std::min(static_cast<qsizetype>(index), siblingCount)};
if (b < 0) {
b = siblingCount + 1 + index;
b = std::max(b, qsizetype{0});
}
return b;
}
// Minimal event filter that suppresses ChildRemoved / ChildAdded events for a
// specific target object and records which events were sent. Used by SetParent
// to defer events until after the children list has been reordered so that the
// model can detect move operations.
struct EventDeferrer final : QObject
{
QObject *target;
bool removedSeen = false;
bool addedSeen = false;
explicit EventDeferrer(QObject *t)
: target(t)
{}
bool eventFilter(QObject *, QEvent *event) override
{
if (event->type() == QEvent::ChildRemoved) {
if (static_cast<QChildEvent *>(event)->child() == target) {
removedSeen = true;
return true; // suppress
}
} else if (event->type() == QEvent::ChildAdded) {
if (static_cast<QChildEvent *>(event)->child() == target) {
addedSeen = true;
return true; // suppress
}
}
return false;
}
};
// Cross-parent reparent for plain QObjects (non-widgets).
//
// Installs a temporary event filter to defer the ChildRemoved / ChildAdded
// events that |setParent_helper| sends inline, calls |QObject::setParent|,
// reorders the children list to honour the requested index, then replays the
// deferred events. By replay time child->parent() already points to the new
// parent so |handleChildRemovedEvent| can detect the move.
void SetQObjectParent(QObject *object, QObject *parent, qsizetype boundedIndex)
{
auto *oldParent = object->parent();
EventDeferrer deferrer(object);
if (oldParent)
oldParent->installEventFilter(&deferrer);
parent->installEventFilter(&deferrer);
object->setParent(parent);
// Move the child from the append position to the requested index.
auto &newSiblings = QObjectPrivate::get(parent)->children;
const qsizetype currentIndex = newSiblings.indexOf(object);
if (currentIndex >= 0 && currentIndex != boundedIndex)
newSiblings.move(currentIndex, boundedIndex);
// Remove the deferrer before replaying so the events reach the real
// event filters (including the model's).
if (oldParent)
oldParent->removeEventFilter(&deferrer);
parent->removeEventFilter(&deferrer);
// Replay in the original order: ChildRemoved first, then ChildAdded.
if (deferrer.removedSeen) {
QChildEvent e(QEvent::ChildRemoved, object);
QCoreApplication::sendEvent(oldParent, &e);
}
if (deferrer.addedSeen) {
QChildEvent e(QEvent::ChildAdded, object);
QCoreApplication::sendEvent(parent, &e);
}
}
#ifdef QT_WIDGETS_LIB
// Cross-parent reparent for QWidgets.
//
// Delegates to |QWidget::setParent| to ensure proper window-system setup,
// visibility propagation, style inheritance, etc.
//
// |QWidget::setParent| may or may not send ChildRemoved / ChildAdded through
// platform-specific code paths (|setParent_sys|). Rather than assuming which
// events fire, we install the deferrer on BOTH old and new parents to catch
// whatever is sent, then replay after the children list is reordered. If
// ChildRemoved was not sent during |QWidget::setParent| (as is expected from
// |setParent_helper|'s suppression for widgets), we send it manually so the
// model can detect the move.
void SetQWidgetParent(QObject *object, QObject *parent, qsizetype boundedIndex)
{
auto *widget = static_cast<QWidget *>(object);
auto *widgetParent = static_cast<QWidget *>(parent);
auto *oldParent = object->parent();
// Install on both parents. Event filters are LIFO so the deferrer
// (installed last) runs before the model's own filter.
EventDeferrer deferrer(object);
if (oldParent)
oldParent->installEventFilter(&deferrer);
parent->installEventFilter(&deferrer);
widget->setParent(widgetParent);
// Move the child from the append position to the requested index.
auto &newSiblings = QObjectPrivate::get(parent)->children;
const qsizetype currentIndex = newSiblings.indexOf(object);
if (currentIndex >= 0 && currentIndex != boundedIndex)
newSiblings.move(currentIndex, boundedIndex);
// Remove the deferrer before replaying so the events reach the real
// event filters (including the model's).
if (oldParent)
oldParent->removeEventFilter(&deferrer);
parent->removeEventFilter(&deferrer);
// Ensure ChildRemoved reaches the old parent. If QWidget::setParent
// already sent it (caught by the deferrer), we replay. If it was
// suppressed (the typical case for widgets in setParent_helper), we
// send it manually. Either way the model needs to see it for move
// detection — child->parent() already points to the new parent.
if (oldParent) {
auto *pObject = QObjectPrivate::get(object);
auto *pOldParent = QObjectPrivate::get(oldParent);
if (pObject->sendChildEvents && pOldParent->receiveChildEvents) {
QChildEvent e(QEvent::ChildRemoved, object);
QCoreApplication::sendEvent(oldParent, &e);
}
}
// Replay or send ChildAdded. The deferrer may or may not have seen it
// depending on the platform; the model's handleChildAddedEvent is
// idempotent (no-op if already tracked after the move above).
if (deferrer.addedSeen) {
QChildEvent e(QEvent::ChildAdded, object);
QCoreApplication::sendEvent(parent, &e);
}
}
#endif
} // namespace
QObject *QObjectTreeModel::GetParent(QObject *object)
{
if (!object) {
return nullptr;
}
return object->parent();
}
bool QObjectTreeModel::IsAncestorOf(QObject *ancestor, QObject *descendant)
{
if (!ancestor || !descendant)
return false;
return IsDescendantOf(descendant, ancestor);
}
// Reparents |object| under |parent| at a specific child index.
//
// Supports both QObject and QWidget children. For QWidgets, delegates to
// |QWidget::setParent| to ensure proper window-system setup; for plain
// QObjects, delegates to |QObject::setParent|. In both cases a temporary event
// filter defers ChildRemoved / ChildAdded events until after the children list
// has been reordered so that the model can detect move operations.
//
// A QWidget can only be a child of another QWidget. A plain QObject can be a
// child of either a QObject or a QWidget.
//
// For same-parent reorders both |QObject::setParent| and |QWidget::setParent|
// are no-ops (they return early when the parent hasn't changed) so the children
// list is reordered directly and a ChildRemoved event is sent manually so the
// model can detect the in-place move.
bool QObjectTreeModel::SetParent(QObject *object, QObject *parent, const int index)
{
Q_ASSERT(object);
if (!object) {
return false;
}
// Validate the QWidget parentage rule: a QWidget can only be a child of
// another QWidget. A plain QObject can be a child of anything.
if (object->isWidgetType() && parent && !parent->isWidgetType()) {
Q_ASSERT_X(false, "SetParent", "A QWidget can only be parented to a QWidget.");
return false;
}
// Delegate unparenting directly — no reordering needed, and the model's
// existing event filter on the old parent will handle ChildRemoved.
if (!parent) {
#ifdef QT_WIDGETS_LIB
if (object->isWidgetType()) {
static_cast<QWidget *>(object)->setParent(static_cast<QWidget *>(nullptr));
return true;
}
#endif
object->setParent(nullptr);
return true;
}
const bool isDescendantOf = IsDescendantOf(parent, object);
if (isDescendantOf) {
const auto error = "Cannot set parent: would create a circular hierarchy.";
Q_ASSERT_X(!isDescendantOf, "SetParent", error);
qWarning() << error;
return false;
}
const bool isOnSameThread = object->thread() == parent->thread();
if (!isOnSameThread) {
const auto error = "Cannot set parent, new parent is in a different thread.";
Q_ASSERT_X(isOnSameThread, "SetParent", error);
qWarning() << error;
return false;
}
const bool isOnCurrentThread = object->thread() == QThread::currentThread();
if (!isOnCurrentThread) {
const auto error = "Cannot call SetParent from different thread to object thread.";
Q_ASSERT_X(isOnCurrentThread, "SetParent", error);
qWarning() << error;
return false;
}
const qsizetype boundedIndex = BoundIndex(object, parent, index);
auto *oldParent = object->parent();
// -----------------------------------------------------------------------
// Same-parent reorder
// -----------------------------------------------------------------------
// Both |QObject::setParent| and |QWidget::setParent| are no-ops when the
// parent hasn't changed, so we reorder |QObjectPrivate::children| directly
// and send a |ChildRemoved| event manually so that the model's
// |handleChildRemovedEvent| can detect the in-place move.
if (oldParent == parent) {
auto &siblings = QObjectPrivate::get(parent)->children;
const qsizetype oldIndex = siblings.indexOf(object);
if (oldIndex == boundedIndex)
return true;
siblings.move(oldIndex, boundedIndex);
auto *pObject = QObjectPrivate::get(object);
if (pObject->sendChildEvents && QObjectPrivate::get(parent)->receiveChildEvents) {
QChildEvent e(QEvent::ChildRemoved, object);
QCoreApplication::sendEvent(parent, &e);
}
return true;
}
// -----------------------------------------------------------------------
// Cross-parent move / fresh insertion (oldParent may be nullptr)
// -----------------------------------------------------------------------
// Dispatch to the appropriate implementation based on whether the object
// is a QWidget. The QWidget path uses QWidget::setParent for proper
// window-system setup; the QObject path uses QObject::setParent.
if (object->isWidgetType() && parent->isWidgetType()) {
#ifdef QT_WIDGETS_LIB
SetQWidgetParent(object, parent, boundedIndex);
return true;
#else
qWarning() << "Cannot set QWidget parent without linking to Qt::Widgets.";
return false;
#endif
}
SetQObjectParent(object, parent, boundedIndex);
return true;
}
bool QObjectTreeModel::SetParent(QObject *object, QObject *parent)
{
int index = 0;
if (parent) {
index = static_cast<int>(parent->children().size());
}
return SetParent(object, parent, index);
}
QObjectTreeModel::QObjectTreeModel(QObject *parent)
: QAbstractItemModel(parent)
{
setRoot(nullptr);
}
std::unique_ptr<QObjectTreeModel> QObjectTreeModel::CreateWithRoot(QObject *root, QObject *parent)
{
std::unique_ptr<QObjectTreeModel> model(new QObjectTreeModel(parent));
if (root)
model->setRoot(root);
return model;
}
QObjectTreeModel::~QObjectTreeModel()
{
// Remove event filters and signal connections from every tracked
// object. For an external root whose subtree outlives the model.
for (const auto &[child, parent] : m_childParentMap) {
disconnectObject(child);
}
}
// Q_INVOKABLE
QObject *QObjectTreeModel::objectFromIndex(const QModelIndex &index) const
{
if (!index.isValid())
return nullptr;
if (index.model() != this)
return nullptr;
auto *object = static_cast<QObject *>(index.internalPointer());
return object;
}
QVariant QObjectTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return {};
if (index.model() != this)
return {};
auto *object = static_cast<QObject *>(index.internalPointer());
if (role == Qt::DisplayRole)
return object->objectName();
if (role == static_cast<int>(QObjectTreeModel::Roles::ObjectName))
return object->objectName();
if (role == static_cast<int>(QObjectTreeModel::Roles::MetaTypeName))
return QString::fromUtf8(object->metaObject()->className());
return {};
}
int QObjectTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid() && parent.model() != this)
return 0;
auto *parentObject = static_cast<QObject *>(parent.internalPointer());
if (!parent.isValid()) {
// Only the root object (i.e. invalid parent QModelIndex) can be
// accessed via nullptr from the |m_parentChildMap|.
Q_ASSERT(parentObject == nullptr);
// During setRoot() the maps are transiently empty between clear() and
// populateFromObjectRecursive(). Views may query during
// beginResetModel/endResetModel, so only assert the invariant when
// the map is populated.
if (m_parentChildMap.contains(nullptr)) {
Q_ASSERT(m_parentChildMap.at(nullptr).size() == 1);
Q_ASSERT(m_parentChildMap.at(nullptr)[0] == m_root);
}
}
const auto it = m_parentChildMap.find(parentObject);
if (it == m_parentChildMap.end()) {
return 0;
}
return static_cast<int>(it->second.size());
}
int QObjectTreeModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid() && parent.model() != this)
return 0;
// We only have one data column (i.e. the Object*).
return 1;
}
bool QObjectTreeModel::hasChildren(const QModelIndex &parent) const
{
if (parent.isValid() && parent.model() != this)
return false;
auto *parentObject = static_cast<QObject *>(parent.internalPointer());
const auto it = m_parentChildMap.find(parentObject);
return it != m_parentChildMap.end() && !it->second.empty();
}
QModelIndex QObjectTreeModel::parent(const QModelIndex &child) const
{
if (!child.isValid()) {
return QModelIndex();
}
if (child.model() != this)
return QModelIndex();
// From docs:
// > If the model index specified corresponds to a top-level item in the
// > model, or if there is no valid parent item in the model, the function
// > must return an invalid model index, created with the empty QModelIndex()
// > constructor.
// https://doc.qt.io/qt-6/model-view-programming.html#navigation-and-model-index-creation
//
// The below will meet the above requirement as if internalPointer() returns
// |m_root| then |m_childParentMap| will give |nullptr| as the
// parent causing |indexOf| to return an invalid model index.
auto *childObject = static_cast<QObject *>(child.internalPointer());
// Use find() rather than at() so that a stale QModelIndex (one whose
// internal pointer is no longer tracked by the model) does not throw
// std::out_of_range.
auto it = m_childParentMap.find(childObject);
if (it == m_childParentMap.end())
return QModelIndex();
auto *parentObject = it->second;
if (childObject == m_root) {
Q_ASSERT(parentObject == nullptr);
}
return indexOf(parentObject);
}
QModelIndex QObjectTreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid() && parent.model() != this)
return {};
auto *parentObject = static_cast<QObject *>(parent.internalPointer());
if (!parent.isValid()) {
// Only the root object (i.e. invalid parent QModelIndex) can be
// accessed via nullptr from the |m_parentChildMap|.
Q_ASSERT(parentObject == nullptr);
// During setRoot() the maps are transiently empty between clear() and
// populateFromObjectRecursive(). Views may query during
// beginResetModel/endResetModel, so only assert the invariant when
// the map is populated.
if (m_parentChildMap.contains(nullptr)) {
Q_ASSERT(m_parentChildMap.at(nullptr).size() == 1);
Q_ASSERT(m_parentChildMap.at(nullptr)[0] == m_root);
}
}
auto it = m_parentChildMap.find(parentObject);
if (it == m_parentChildMap.end()) {
return {};
}
const QObjectList &children{it->second};
if (row < 0 || column < 0 || row >= static_cast<int>(children.size())
|| column >= columnCount()) {
return {};
}
return createIndex(row, column, children[row]);
}
QModelIndex QObjectTreeModel::sibling(int row, int column, const QModelIndex &index) const
{
if (!index.isValid())
return {};
if (index.model() != this)
return {};
if (row < 0 || column < 0 || column >= columnCount())
return {};
// Look up the parent of the object at |idx|.
auto *object = static_cast<QObject *>(index.internalPointer());
auto childIt = m_childParentMap.find(object);
if (childIt == m_childParentMap.end())
return {};
// Look up the sibling list from the parent.
auto *parentObject = childIt->second;
auto parentIt = m_parentChildMap.find(parentObject);
if (parentIt == m_parentChildMap.end())
return {};
const QObjectList &siblings{parentIt->second};
if (row >= static_cast<int>(siblings.size()))
return {};
return createIndex(row, column, siblings[row]);
}
QMap<int, QVariant> QObjectTreeModel::itemData(const QModelIndex &index) const
{
if (index.isValid() && index.model() != this)
return {};
// Start with the standard roles provided by the base class.
QMap<int, QVariant> result = QAbstractItemModel::itemData(index);
// The base implementation only queries the standard Qt roles. Append our
// custom roles so that callers (and QAbstractItemModelTester) see a
// complete picture.
static constexpr int customRoles[] = {
static_cast<int>(Roles::ObjectName),
static_cast<int>(Roles::MetaTypeName),
};
for (int role : customRoles) {
const QVariant value = data(index, role);
if (value.isValid())
result.insert(role, value);
}
return result;
}
QHash<int, QByteArray> QObjectTreeModel::roleNames() const
{
static QHash<int, QByteArray> s_roleNames = []() {
auto roleNames = QAbstractItemModelPrivate::defaultRoleNames();
roleNames[static_cast<int>(QObjectTreeModel::Roles::ObjectName)] = "objectName";
roleNames[static_cast<int>(QObjectTreeModel::Roles::MetaTypeName)] = "metaTypeName";
return roleNames;
}();
return s_roleNames;
}
bool QObjectTreeModel::moveRows(const QModelIndex &sourceParent,
int sourceRow,
int count,
const QModelIndex &destinationParent,
int destinationRow)
{
if ((sourceParent.isValid() && sourceParent.model() != this)
|| (destinationParent.isValid() && destinationParent.model() != this))
return false;
if (count != 1) {
qWarning() << u"QObjectTreeModel::moveRows only supports a count of 1 (count = %0)"_s.arg(
count);
return false;
}
if (!sourceParent.isValid()) {
qWarning() << "QObjectTreeModel::moveRows does not support an invalid "
"sourceParent index. Use indexOf(root()) to move objects "
"under the root.";
return false;
}
if (!destinationParent.isValid()) {
qWarning() << "QObjectTreeModel::moveRows does not support an invalid "
"destinationParent index. Use indexOf(root()) to move "
"objects under the root.";
return false;
}
if (sourceRow < 0) {
qWarning() << u"QObjectTreeModel::moveRows does not support negative sourceRow values (sourceRow = %0)"_s
.arg(sourceRow);
return false;
}
if (destinationRow < 0) {
qWarning() << u"QObjectTreeModel::moveRows does not support negative destinationRow values (destinationRow = %0)"_s
.arg(destinationRow);
return false;
}
if (sourceRow >= rowCount(sourceParent)) {
qWarning() << u"QObjectTreeModel::moveRows: sourceRow (%0) is out of range (rowCount = %1)"_s
.arg(sourceRow)
.arg(rowCount(sourceParent));
return false;
}
if (destinationRow > rowCount(destinationParent)) {
qWarning() << u"QObjectTreeModel::moveRows: destinationRow (%0) exceeds row count (%1)"_s
.arg(destinationRow)
.arg(rowCount(destinationParent));
return false;
}
auto *destParent = static_cast<QObject *>(destinationParent.internalPointer());
// Get the child that is being moved.
auto modelIndex = index(sourceRow, 0, sourceParent);
if (!modelIndex.isValid())
return false;
QObject *child = static_cast<QObject *>(modelIndex.internalPointer());
int index{destinationRow};
// If moving within the same parent then we need to modify index to take into
// account no-ops.
QObject *currentParent{static_cast<QObject *>(sourceParent.internalPointer())};
if (currentParent == destParent) {
if (destinationRow > sourceRow) {
index--;
}
// Skip no-op moves.
if (currentParent->children().indexOf(child) == static_cast<qsizetype>(index)) {
return false;
}
}
return QObjectTreeModel::SetParent(child, destParent, index);
}
QModelIndex QObjectTreeModel::indexOf(QObject *object) const
{
if (!object)
return {};
// Get the parent for the Object.
QObject *parent{nullptr};
if (auto it = m_childParentMap.find(object); it != m_childParentMap.end())
parent = it->second;
// Only the root object can have nullptr for the parent.
if (!parent && object != m_root) {
return {};
}
// Get the objects known siblings. Use find() rather than at() to avoid
// throwing if the parent is not (or no longer) tracked.
auto it = m_parentChildMap.find(parent);
if (it == m_parentChildMap.end())
return {};
const QObjectList &siblings{it->second};
// If the object does not exist among the parents known children then return
// an invalid model index.
qsizetype index{siblings.indexOf(object)};
if (index < 0)
return {};
return createIndex(static_cast<int>(index), 0, object);
}
QObject *QObjectTreeModel::root() const
{
return m_root;
}
void QObjectTreeModel::setRoot(QObject *root)
{
if (m_root && m_root == root) {
return;
}
if (root && root->thread() != this->thread()) {
// Qt guarantees that all children share their parent's thread affinity,
// so asserting the root alone is sufficient to guarantee the entire
// subtree is on the model's thread.
Q_ASSERT_X(false,
"QObjectTreeModel::setRoot",
"The root QObject must have the same thread affinity as the model. "
"All tracked objects rely on DirectConnection signals and event "
"filters which require same-thread affinity.");
return;
}
beginResetModel();
// Clean up old state: disconnect event filters and signal connections from
// all objects currently tracked by the model.
for (const auto &[object, parent] : m_childParentMap) {
disconnectObject(object);
}
m_childParentMap.clear();
m_parentChildMap.clear();
// If the previous root was internally created (parented to this model),
// delete it to avoid a memory leak.
QObject *oldRoot = m_root;
// If root is null then create and manage an internal root object that
// children can be parented to.
if (!root) {
m_root = new QObject(this);
m_root->setObjectName("Root");
} else {
m_root = root;
}
// Delete the old internal root after setting m_root so that any events
// triggered by the deletion don't reference stale state.
if (oldRoot && oldRoot->parent() == this) {
// If the new root is a descendant of the old internal root, reparent it
// first so that deleteLater() on the old root doesn't destroy the new
// root along with the rest of its subtree.
for (QObject *ancestor = m_root->parent(); ancestor; ancestor = ancestor->parent()) {
if (ancestor == oldRoot) {
m_root->setParent(this);
break;
}
}
oldRoot->deleteLater();
}
populateFromObjectRecursive(m_root);
endResetModel();
Q_EMIT rootChanged();
}
bool QObjectTreeModel::insertRows(int, int, const QModelIndex & /*index*/)
{
constexpr auto error = "QObjectTreeModel::insertRows Not implemented";
Q_ASSERT_X(false, "QObjectTreeModel::insertRows", error);
qWarning() << error;
return false;
}
bool QObjectTreeModel::insertColumns(int, int, const QModelIndex & /*index*/)
{
constexpr auto error = "QObjectTreeModel::insertColumns Not implemented";
Q_ASSERT_X(false, "QObjectTreeModel::insertColumns", error);
qWarning() << error;
return false;
}
bool QObjectTreeModel::removeRows(int row, int count, const QModelIndex &parent)
{
if (parent.isValid() && parent.model() != this)
return false;
if (count < 0) {
qWarning() << u"QObjectTreeModel::removeRows does not support negative counts (count = %0)"_s
.arg(count);
return false;
}
if (row < 0) {
qWarning() << u"QObjectTreeModel::removeRows does not support negative row values (row = %0)"_s
.arg(row);
return false;
}
if (count == 0)
return true;
// An invalid parent means the caller is potentially trying to remove the
// root, which is not supported.
if (!parent.isValid()) {
qWarning() << "QObjectTreeModel::removeRows does not support an invalid "
"parent index. Removing the root object is prohibited.";
return false;
}
auto *parentObject = static_cast<QObject *>(parent.internalPointer());
auto siblingIt = m_parentChildMap.find(parentObject);
Q_ASSERT(siblingIt != m_parentChildMap.end());
if (siblingIt == m_parentChildMap.end())
return false;
QObjectList &siblings{siblingIt->second};
if (row + count > static_cast<int>(siblings.size())) {
qWarning() << u"QObjectTreeModel::removeRows: row (%0) + count (%1) exceeds row count (%2)"_s
.arg(row)
.arg(count)
.arg(static_cast<int>(siblings.size()));
return false;
}
// Collect the children to be removed, disconnect them from the model, and
// unparent them in a single begin/endRemoveRows block so that views only
// receive one notification.
QObjectList toDelete;
toDelete.reserve(count);
beginRemoveRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++) {
QObject *child{siblings[row]};
siblings.removeAt(row);
removeAndDisconnectSubtree(child);
// Unparent the child. This will trigger a ChildRemoved event on the
// parent but since we have already removed the child from the maps,
// handleChildRemovedEvent will find nothing and return immediately.
Q_ASSERT(!m_childParentMap.contains(child));
child->setParent(nullptr);
toDelete.push_back(child);
}
endRemoveRows();
// Schedule deletion after the model has finished updating so that
// delegates and views have a chance to clean up before the objects
// are destroyed.
for (QObject *child : toDelete)
child->deleteLater();
return true;
}
QObjectList QObjectTreeModel::takeRows(int row, int count, const QModelIndex &parent)
{
auto result = QObjectList{};
if (parent.isValid() && parent.model() != this)
return result;
if (count < 0) {
qWarning() << u"TakeRows does not support negative counts (count = %0)"_s.arg(count);
return result;
}
if (row < 0) {
qWarning() << u"QObjectTreeModel::TakeRows does not support negative row values (row = %0)"_s
.arg(row);
return result;
}
// If the count is zero then there is no work to do.
if (count == 0) {
return result;
}
// An invalid parent means that the caller is potentially trying to remove
// |m_root| which is not supported.
if (!parent.isValid()) {
qWarning() << "QObjectTreeModel::TakeRows does not support an invalid "
"parent index. Removing "
"the root object is prohibited.";
return result;
}
auto *parentObject = static_cast<QObject *>(parent.internalPointer());
auto siblingIt = m_parentChildMap.find(parentObject);
Q_ASSERT(siblingIt != m_parentChildMap.end());
if (siblingIt == m_parentChildMap.end())
return result;
QObjectList &siblings{siblingIt->second};
if (row + count > static_cast<int>(siblings.size())) {
qWarning() << u"QObjectTreeModel::takeRows: row (%0) + count (%1) exceeds row count (%2)"_s
.arg(row)
.arg(count)
.arg(static_cast<int>(siblings.size()));
return result;
}
result.reserve(count);
beginRemoveRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++) {
QObject *child{siblings[row]};
// Remove the child from the model.
siblings.removeAt(row); // Removes it from the parents child map
removeAndDisconnectSubtree(child); // Removes it as a key value in all maps
// Set the parent to nullptr, this will cause a child removed event for the
// parent but given we have already removed the object sub-tree from the
// model |handleChildRemovedEvent| will do nothing.
Q_ASSERT(!m_childParentMap.contains(child));
child->setParent(nullptr);
// We now take ownership of the |child| object and delete it after calling
// |endRemoveRows| so that delegates have a chance to be deleted before the
// model objects.
result.push_back(child);
}
endRemoveRows();
return result;
}
QObjectList QObjectTreeModel::takeAllRows(const QModelIndex &parent)
{
if (parent.isValid() && parent.model() != this)
return {};
// If called with empty args (default index constructor) then take all rows
// from the root.
auto adjustedParent = parent.isValid() ? parent : indexOf(m_root);
return takeRows(0, rowCount(adjustedParent), adjustedParent);
}
bool QObjectTreeModel::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::ChildAdded) {
auto *childEvent = static_cast<QChildEvent *>(event);
auto *child = childEvent->child();
Q_ASSERT(child);
// If the added child has already had deleteLater called on it then don't
// add it to the model to avoid churn.
if (!IsValid(child)) {
return QObject::eventFilter(object, event);
}
// Check Qt has setup the parent relationship correctly.
Q_ASSERT_X(object == child->parent(),
"QObjectTreeModel::eventFilter",
"Added child has the wrong parent.");
handleChildAddedEvent(child);
} else if (event->type() == QEvent::ChildRemoved) {
auto *childEvent = static_cast<QChildEvent *>(event);
auto *child = childEvent->child();
handleChildRemovedEvent(child, object);
} else if (event->type() == QEvent::DeferredDelete) {
Q_ASSERT(object);
if (object != m_root) {
// Verify that Qt has not removed the object from the parent's "children"
// list by this point.
Q_ASSERT_X(object->parent(),
"QObjectTreeModel::eventFilter",
(QDebug::toString(object) + " has no parent.").toStdString().c_str());
Q_ASSERT(object->parent()->children().contains(object));
}
// Remove the child from the model.
handleDeferredDeleteEvent(object);
} else if (event->type() == QEvent::ThreadChange) {
// If an object is moving thread then it must have started on the
// QObjectTreeModels thread for it to be in the model and have an event
// filter installed..
//
// This should never happen for any child objects in the tree as the
// docs state that:
//
// > "The object cannot be moved if it has a parent."
//
// and also:
//
// > "This is the last event sent to the object in the previous thread."
//
// So the only object valid for moving would be an external root object
// with no parent. That is the case handled here.
Q_ASSERT(object == m_root);
setRoot(nullptr);
} else if (event->type() == QEvent::ParentChange) {
// QWidget::setParent sends ParentChange to the reparented widget after
// the parent has been updated. Qt suppresses the ChildAdded/ChildRemoved
// events for QWidgets in QObjectPrivate::setParent_helper, so this event