-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqtreetotablemodel.cpp
More file actions
1228 lines (1027 loc) · 43.6 KB
/
Copy pathqtreetotablemodel.cpp
File metadata and controls
1228 lines (1027 loc) · 43.6 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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026, Meld Studio, Inc.
#include "qtreetotablemodel.h"
#include <QtCore/QLoggingCategory>
using namespace Qt::Literals::StringLiterals;
Q_LOGGING_CATEGORY(lcTreeToTable, "QTreeToTableModel")
// =============================================================================
// Construction / Destruction
// =============================================================================
QTreeToTableModel::QTreeToTableModel(QObject *parent)
: QAbstractTableModel(parent)
{
// Keep the count property in sync with any row changes. These connections
// fire after the model signals complete, ensuring m_items is up-to-date.
connect(this, &QAbstractItemModel::rowsInserted, this, &QTreeToTableModel::updateCount);
connect(this, &QAbstractItemModel::rowsRemoved, this, &QTreeToTableModel::updateCount);
connect(this, &QAbstractItemModel::modelReset, this, &QTreeToTableModel::updateCount);
connect(this, &QAbstractItemModel::layoutChanged, this, &QTreeToTableModel::updateCount);
}
QTreeToTableModel::~QTreeToTableModel()
{
disconnectFromSourceModel();
}
// =============================================================================
// Source Model
// =============================================================================
QAbstractItemModel *QTreeToTableModel::sourceModel() const
{
return m_sourceModel.data();
}
void QTreeToTableModel::setSourceModel(QAbstractItemModel *model)
{
if (m_sourceModel == model)
return;
const bool rootWasValid = m_rootIndex.isValid();
beginResetModel();
disconnectFromSourceModel();
m_sourceModel = model;
// Changing the source model invalidates the root index, since it belonged
// to the previous model.
m_rootIndex = QPersistentModelIndex();
if (m_sourceModel)
connectToSourceModel();
rebuildFlatList();
endResetModel();
Q_EMIT sourceModelChanged();
if (rootWasValid)
Q_EMIT rootIndexChanged();
}
// =============================================================================
// Root Index
// =============================================================================
QModelIndex QTreeToTableModel::rootIndex() const
{
return m_rootIndex;
}
void QTreeToTableModel::setRootIndex(const QModelIndex &index)
{
if (m_rootIndex == index)
return;
if (index.isValid() && index.model() != m_sourceModel) {
qCWarning(lcTreeToTable) << "setRootIndex: index belongs to a different model";
return;
}
beginResetModel();
m_rootIndex = index;
rebuildFlatList();
endResetModel();
Q_EMIT rootIndexChanged();
}
void QTreeToTableModel::resetRootIndex()
{
setRootIndex(QModelIndex());
}
// =============================================================================
// Max Depth
// =============================================================================
int QTreeToTableModel::maxDepth() const
{
return m_maxDepth;
}
void QTreeToTableModel::setMaxDepth(int depth)
{
// Negative values are not meaningful; clamp to 0 (unlimited).
if (depth < 0)
depth = 0;
if (m_maxDepth == depth)
return;
beginResetModel();
m_maxDepth = depth;
rebuildFlatList();
endResetModel();
Q_EMIT maxDepthChanged();
}
// =============================================================================
// Count
// =============================================================================
int QTreeToTableModel::count() const
{
return m_count;
}
void QTreeToTableModel::updateCount()
{
const int newCount = m_items.size();
if (m_count != newCount) {
m_count = newCount;
Q_EMIT countChanged();
}
}
// =============================================================================
// QAbstractTableModel Interface
// =============================================================================
bool QTreeToTableModel::hasChildren(const QModelIndex &parent) const
{
// In a flat table, only the invisible root can have children.
return !parent.isValid() && !m_items.isEmpty();
}
int QTreeToTableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0; // Flat table items have no children
return m_items.size();
}
int QTreeToTableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid() || !m_sourceModel)
return 0;
// Ask the source model for the column count at the effective root.
// When a rootIndex is set, its children define the columns.
return m_sourceModel->columnCount(m_rootIndex);
}
QVariant QTreeToTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return {};
const int row = index.row();
if (row < 0 || row >= m_items.size())
return {};
const FlatItem &item = m_items.at(row);
// Handle our additional roles before forwarding to source.
switch (role) {
case static_cast<int>(Roles::Depth):
return item.depth;
case static_cast<int>(Roles::SourceIndex):
return QVariant::fromValue(item.sourceIndex);
default:
break;
}
// Forward all other roles to the source model.
if (!item.sourceIndex.isValid())
return {};
// For column > 0, construct the appropriate source index at the correct
// column since FlatItem always stores column-0 indexes.
QModelIndex sourceIdx = item.sourceIndex;
if (index.column() != 0)
sourceIdx = m_sourceModel->index(sourceIdx.row(), index.column(), sourceIdx.parent());
return m_sourceModel->data(sourceIdx, role);
}
bool QTreeToTableModel::setData(const QModelIndex &index,
const QVariant &value,
int role)
{
if (!index.isValid())
return false;
const int row = index.row();
if (row < 0 || row >= m_items.size())
return false;
// Our additional roles are read-only.
if (role == static_cast<int>(Roles::Depth)
|| role == static_cast<int>(Roles::SourceIndex))
return false;
const FlatItem &item = m_items.at(row);
if (!item.sourceIndex.isValid())
return false;
QModelIndex sourceIdx = item.sourceIndex;
if (index.column() != 0)
sourceIdx = m_sourceModel->index(sourceIdx.row(), index.column(), sourceIdx.parent());
return m_sourceModel->setData(sourceIdx, value, role);
}
QVariant QTreeToTableModel::headerData(int section,
Qt::Orientation orientation,
int role) const
{
if (!m_sourceModel)
return {};
return m_sourceModel->headerData(section, orientation, role);
}
Qt::ItemFlags QTreeToTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
const int row = index.row();
if (row < 0 || row >= m_items.size())
return Qt::NoItemFlags;
const FlatItem &item = m_items.at(row);
if (!item.sourceIndex.isValid())
return Qt::NoItemFlags;
QModelIndex sourceIdx = item.sourceIndex;
if (index.column() != 0)
sourceIdx = m_sourceModel->index(sourceIdx.row(), index.column(), sourceIdx.parent());
return m_sourceModel->flags(sourceIdx);
}
QHash<int, QByteArray> QTreeToTableModel::roleNames() const
{
QHash<int, QByteArray> roles;
if (m_sourceModel)
roles = m_sourceModel->roleNames();
roles.insert(static_cast<int>(Roles::Depth), "depth");
roles.insert(static_cast<int>(Roles::SourceIndex), "sourceIndex");
return roles;
}
// =============================================================================
// Mapping Functions
// =============================================================================
QModelIndex QTreeToTableModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid())
return {};
const int row = proxyIndex.row();
if (row < 0 || row >= m_items.size())
return {};
const FlatItem &item = m_items.at(row);
QModelIndex sourceIdx = item.sourceIndex;
// Remap to the correct column if the proxy index has column > 0.
if (proxyIndex.column() != 0 && sourceIdx.isValid())
sourceIdx = m_sourceModel->index(sourceIdx.row(), proxyIndex.column(), sourceIdx.parent());
return sourceIdx;
}
QModelIndex QTreeToTableModel::mapFromSource(const QModelIndex &sourceIndex) const
{
if (!sourceIndex.isValid())
return {};
const int row = findFlatRow(sourceIndex);
if (row < 0)
return QModelIndex();
return createIndex(row, sourceIndex.column());
}
QModelIndex QTreeToTableModel::sourceIndexForRow(int row) const
{
if (row < 0 || row >= m_items.size())
return {};
return m_items.at(row).sourceIndex;
}
int QTreeToTableModel::rowForSourceIndex(const QModelIndex &sourceIndex) const
{
return findFlatRow(sourceIndex);
}
int QTreeToTableModel::depthForRow(int row) const
{
if (row < 0 || row >= m_items.size())
return -1;
return m_items.at(row).depth;
}
bool QTreeToTableModel::isSourceIndexVisible(const QModelIndex &sourceIndex) const
{
return findFlatRow(sourceIndex) >= 0;
}
bool QTreeToTableModel::isAncestorOf(const QModelIndex &ancestor,
const QModelIndex &descendant) const
{
if (!ancestor.isValid() || !descendant.isValid())
return false;
// Walk up from descendant itself (not parent) looking for ancestor.
// This means isAncestorOf(A, A) returns true, which is the correct
// behavior for drag-and-drop: you cannot drop an item onto itself.
QModelIndex idx = descendant;
while (idx.isValid()) {
if (idx == ancestor)
return true;
idx = idx.parent();
}
return false;
}
bool QTreeToTableModel::moveSourceRow(const QModelIndex &sourceIndex,
const QModelIndex &destinationParent,
int destinationChild)
{
if (!m_sourceModel || !sourceIndex.isValid())
return false;
// Cannot move into own subtree (isAncestorOf(A,A) returns true,
// covering self-drop as well).
if (destinationParent.isValid() && isAncestorOf(sourceIndex, destinationParent))
return false;
// Normalize: -1 or out-of-range means "append as last child."
// moveRows() expects rowCount(parent) for "after the last child."
int destChild = destinationChild;
if (destChild < 0 || destChild > m_sourceModel->rowCount(destinationParent))
destChild = m_sourceModel->rowCount(destinationParent);
// Delegate to the source model's standard moveRows() API.
// The source model will call beginMoveRows/endMoveRows, which emit
// rowsAboutToBeMoved/rowsMoved. Our onSourceRowsAboutToBeMoved and
// onSourceRowsMoved handlers translate these into the correct
// flat-table operations.
const bool result = m_sourceModel->moveRows(sourceIndex.parent(), // sourceParent
sourceIndex.row(), // sourceRow
1, // count (single row; subtree moves implicitly)
destinationParent, // destinationParent
destChild); // destinationChild
if (!result)
qCDebug(lcTreeToTable) << "moveSourceRow: source model moveRows() returned false";
return result;
}
void QTreeToTableModel::dump() const
{
qCInfo(lcTreeToTable) << "=== QTreeToTableModel Dump ===";
qCInfo(lcTreeToTable) << "Source model:" << m_sourceModel;
qCInfo(lcTreeToTable) << "Root index valid:" << m_rootIndex.isValid();
if (m_rootIndex.isValid())
qCInfo(lcTreeToTable) << "Root index data:" << m_rootIndex.data();
qCInfo(lcTreeToTable) << "Max depth:" << m_maxDepth;
qCInfo(lcTreeToTable) << "Item count:" << m_items.size();
qCInfo(lcTreeToTable) << "---";
for (int i = 0; i < m_items.size(); ++i) {
const FlatItem &item = m_items.at(i);
QString indent(item.depth * 2, u' ');
qCInfo(lcTreeToTable).noquote()
<< QString(u"[%1] %2depth=%3 data=%4"_s)
.arg(i, 3)
.arg(indent)
.arg(item.depth)
.arg(item.sourceIndex.data().toString());
}
qCInfo(lcTreeToTable) << "==============================";
}
// =============================================================================
// Connection Management
// =============================================================================
void QTreeToTableModel::connectToSourceModel()
{
if (!m_sourceModel)
return;
// Connect to all relevant source model signals. We store the connections
// so they can be cleanly disconnected when the source model changes.
m_connections = {
connect(m_sourceModel,
&QAbstractItemModel::destroyed,
this,
&QTreeToTableModel::onSourceModelDestroyed),
connect(m_sourceModel,
&QAbstractItemModel::modelAboutToBeReset,
this,
&QTreeToTableModel::onSourceModelAboutToBeReset),
connect(m_sourceModel,
&QAbstractItemModel::modelReset,
this,
&QTreeToTableModel::onSourceModelReset),
connect(m_sourceModel,
&QAbstractItemModel::dataChanged,
this,
&QTreeToTableModel::onSourceDataChanged),
connect(m_sourceModel,
&QAbstractItemModel::layoutAboutToBeChanged,
this,
&QTreeToTableModel::onSourceLayoutAboutToBeChanged),
connect(m_sourceModel,
&QAbstractItemModel::layoutChanged,
this,
&QTreeToTableModel::onSourceLayoutChanged),
connect(m_sourceModel,
&QAbstractItemModel::rowsInserted,
this,
&QTreeToTableModel::onSourceRowsInserted),
connect(m_sourceModel,
&QAbstractItemModel::rowsAboutToBeRemoved,
this,
&QTreeToTableModel::onSourceRowsAboutToBeRemoved),
connect(m_sourceModel,
&QAbstractItemModel::rowsRemoved,
this,
&QTreeToTableModel::onSourceRowsRemoved),
connect(m_sourceModel,
&QAbstractItemModel::rowsAboutToBeMoved,
this,
&QTreeToTableModel::onSourceRowsAboutToBeMoved),
connect(m_sourceModel,
&QAbstractItemModel::rowsMoved,
this,
&QTreeToTableModel::onSourceRowsMoved),
connect(m_sourceModel,
&QAbstractItemModel::columnsAboutToBeInserted,
this,
&QTreeToTableModel::onSourceColumnsAboutToBeInserted),
connect(m_sourceModel,
&QAbstractItemModel::columnsInserted,
this,
&QTreeToTableModel::onSourceColumnsInserted),
connect(m_sourceModel,
&QAbstractItemModel::columnsAboutToBeRemoved,
this,
&QTreeToTableModel::onSourceColumnsAboutToBeRemoved),
connect(m_sourceModel,
&QAbstractItemModel::columnsRemoved,
this,
&QTreeToTableModel::onSourceColumnsRemoved),
// Header data changes need no transformation — forward directly.
connect(m_sourceModel,
&QAbstractItemModel::headerDataChanged,
this,
&QTreeToTableModel::headerDataChanged),
};
}
void QTreeToTableModel::disconnectFromSourceModel()
{
for (const auto &conn : m_connections)
disconnect(conn);
m_connections.clear();
}
// =============================================================================
// Source Model Signal Handlers
// =============================================================================
void QTreeToTableModel::onSourceModelDestroyed()
{
// The source model is being destroyed. Clear all state and emit a reset
// so views know to discard everything.
beginResetModel();
m_sourceModel = nullptr;
m_rootIndex = QPersistentModelIndex();
m_items.clear();
m_connections.clear(); // Connections are already dead, just clear the list.
endResetModel();
Q_EMIT sourceModelChanged();
Q_EMIT rootIndexChanged();
}
void QTreeToTableModel::onSourceModelAboutToBeReset()
{
// Record whether we had a valid root index before the reset. After the
// reset, QPersistentModelIndex will be invalidated if the root item no
// longer exists. We use this flag to detect that case and emit
// rootIndexChanged().
m_rootWasValidBeforeReset = m_rootIndex.isValid();
}
void QTreeToTableModel::onSourceModelReset()
{
const bool rootInvalidated = m_rootWasValidBeforeReset && !m_rootIndex.isValid();
m_rootWasValidBeforeReset = false;
beginResetModel();
if (rootInvalidated)
m_rootIndex = QPersistentModelIndex();
rebuildFlatList();
endResetModel();
// Emit after endResetModel so slots see consistent model state.
if (rootInvalidated)
Q_EMIT rootIndexChanged();
}
void QTreeToTableModel::onSourceDataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight,
const QList<int> &roles)
{
if (!topLeft.isValid() || !bottomRight.isValid())
return;
Q_ASSERT(topLeft.parent() == bottomRight.parent());
// Map the source range to proxy rows. The source range may span multiple
// rows under the same parent; we find the first and last proxy rows that
// correspond to visible items in the range and emit a single dataChanged
// covering the contiguous proxy range.
int firstProxyRow = -1;
int lastProxyRow = -1;
const QModelIndex parent = topLeft.parent();
for (int srcRow = topLeft.row(); srcRow <= bottomRight.row(); ++srcRow) {
const QModelIndex srcIdx = m_sourceModel->index(srcRow, 0, parent);
const int proxyRow = findFlatRow(srcIdx);
if (proxyRow >= 0) {
if (firstProxyRow < 0 || proxyRow < firstProxyRow)
firstProxyRow = proxyRow;
if (proxyRow > lastProxyRow)
lastProxyRow = proxyRow;
}
}
if (firstProxyRow >= 0 && lastProxyRow >= 0) {
const QModelIndex proxyTopLeft = createIndex(firstProxyRow, topLeft.column());
const QModelIndex proxyBottomRight = createIndex(lastProxyRow, bottomRight.column());
Q_EMIT dataChanged(proxyTopLeft, proxyBottomRight, roles);
}
}
void QTreeToTableModel::onSourceLayoutAboutToBeChanged(
const QList<QPersistentModelIndex> & /*parents*/,
QAbstractItemModel::LayoutChangeHint /*hint*/)
{
Q_EMIT layoutAboutToBeChanged();
// Save the current persistent indexes so we can remap them after the
// layout change. For each persistent proxy index, we store the
// corresponding source index and the old proxy row.
const auto persistentIndexes = persistentIndexList();
m_layoutChangePersistentIndexes.clear();
m_layoutChangeProxyIndexes.clear();
m_layoutChangePersistentIndexes.reserve(persistentIndexes.size());
m_layoutChangeProxyIndexes.reserve(persistentIndexes.size());
for (const QModelIndex &proxyIdx : persistentIndexes) {
const int row = proxyIdx.row();
if (row >= 0 && row < m_items.size()) {
m_layoutChangePersistentIndexes.append(m_items.at(row).sourceIndex);
m_layoutChangeProxyIndexes.append(proxyIdx);
}
}
}
void QTreeToTableModel::onSourceLayoutChanged(
const QList<QPersistentModelIndex> & /*parents*/,
QAbstractItemModel::LayoutChangeHint /*hint*/)
{
// Rebuild the flat list from scratch -- the source model's ordering may
// have changed arbitrarily.
rebuildFlatList();
// Remap persistent indexes: for each saved source index, find its new
// position in the rebuilt flat list and update the persistent index.
QModelIndexList oldIndexes;
QModelIndexList newIndexes;
for (int i = 0; i < m_layoutChangePersistentIndexes.size(); ++i) {
const QPersistentModelIndex &srcIdx = m_layoutChangePersistentIndexes.at(i);
const QModelIndex &oldProxyIdx = m_layoutChangeProxyIndexes.at(i);
oldIndexes.append(oldProxyIdx);
if (srcIdx.isValid()) {
const int newRow = findFlatRow(srcIdx);
if (newRow >= 0) {
newIndexes.append(createIndex(newRow, oldProxyIdx.column()));
} else {
// Item left the flat list (e.g. pushed past maxDepth) — invalidate.
newIndexes.append(QModelIndex());
}
} else {
// Source item no longer exists — invalidate.
newIndexes.append(QModelIndex());
}
}
changePersistentIndexList(oldIndexes, newIndexes);
m_layoutChangePersistentIndexes.clear();
m_layoutChangeProxyIndexes.clear();
Q_EMIT layoutChanged();
}
// -- Row insertion handling --
//
// Qt's insert protocol is a two-phase signal: rowsAboutToBeInserted fires
// before the rows exist, and rowsInserted fires after they are in place. We
// do all our work in the "inserted" handler because we need to read the
// newly-inserted items from the source model.
void QTreeToTableModel::onSourceRowsInserted(const QModelIndex &parent, int first, int last)
{
// Note: we intentionally do not connect to rowsAboutToBeInserted because
// we can only read the newly-inserted items after they exist in the source.
// Ignore insertions under parents that are not visible (outside root
// subtree or hidden by a non-visible ancestor).
if (!isParentVisible(parent))
return;
// Check maxDepth: the parent's depth + 1 is the depth of children being
// inserted. If that depth would be at or beyond maxDepth, skip.
const int depth = calculateDepth(m_sourceModel->index(first, 0, parent));
if (m_maxDepth > 0 && depth >= m_maxDepth)
return;
// Find the position in the flat list where the new items should go.
const int insertPos = findInsertPosition(parent, first);
// Flatten the newly-inserted rows and their subtrees.
QList<FlatItem> newItems;
for (int row = first; row <= last; ++row) {
const QModelIndex childIdx = m_sourceModel->index(row, 0, parent);
newItems.append(FlatItem(childIdx, depth));
if (m_sourceModel->hasChildren(childIdx))
flattenSubtree(childIdx, depth + 1, newItems);
}
if (newItems.isEmpty())
return;
beginInsertRows(QModelIndex(), insertPos, insertPos + newItems.size() - 1);
m_items.insert(insertPos, newItems.size(), FlatItem{});
for (int i = 0; i < newItems.size(); ++i)
m_items[insertPos + i] = newItems[i];
endInsertRows();
m_lastLookupRow = -1; // Invalidate cache -- row positions have shifted.
}
// -- Row removal handling --
//
// Removal is the reverse of insertion. We do all our work in the "aboutTo"
// handler because we need to find the items in the flat list while they
// still exist in the source model (QPersistentModelIndex is still valid).
void QTreeToTableModel::onSourceRowsAboutToBeRemoved(const QModelIndex &parent,
int first,
int last)
{
// Record whether we have a valid root index before the removal. If the
// root item itself is being removed, QPersistentModelIndex will be
// invalidated after the removal completes, and we detect that in
// onSourceRowsRemoved.
m_rootWasValid = m_rootIndex.isValid();
// If the root index is among the items being removed, don't try to remove
// items from the flat list now -- we'll handle the full reset in
// onSourceRowsRemoved once the persistent index is actually invalidated.
if (m_rootWasValid) {
for (int row = first; row <= last; ++row) {
const QModelIndex idx = m_sourceModel->index(row, 0, parent);
if (idx == m_rootIndex)
return;
}
}
if (!isParentVisible(parent))
return;
removeFlatRange(parent, first, last);
}
void QTreeToTableModel::onSourceRowsRemoved(const QModelIndex &parent, int first, int last)
{
Q_UNUSED(parent)
Q_UNUSED(first)
Q_UNUSED(last)
// If the root index was valid before removal but is now invalid, the root
// item was removed from the source model. Reset to show the entire tree.
if (m_rootWasValid && !m_rootIndex.isValid()) {
beginResetModel();
m_rootIndex = QPersistentModelIndex();
rebuildFlatList();
endResetModel();
Q_EMIT rootIndexChanged();
}
m_rootWasValid = false;
m_lastLookupRow = -1; // Invalidate lookup cache after removal.
}
// -- Move handling --
//
// Move operations are the most complex signal to handle because we want to
// preserve them as moves in the flat table (rather than emitting separate
// remove + insert signals) to allow views to animate the operation.
//
// The move is a two-phase operation:
// 1. aboutToBeMoved: Items are still at their old positions. We calculate
// the flat list range, destination position, and depth delta. We save
// copies of the moved items in m_pendingMove.
// 2. moved: Items have been relocated in the source model. We use the
// captured state to emit beginMoveRows/endMoveRows or fall back to
// remove+insert if the move is a no-op in flat space.
//
// There are four visibility cases:
// - Both visible: Emit move (preferred) or remove+insert fallback.
// - Source visible, dest not: Emit remove (items leave the visible area).
// - Source not visible, dest visible: Emit insert (items enter visible area).
// - Neither visible: No-op.
void QTreeToTableModel::onSourceRowsAboutToBeMoved(const QModelIndex &sourceParent,
int sourceFirst,
int sourceLast,
const QModelIndex &destParent,
int destRow)
{
const bool sourceVisible = isParentVisible(sourceParent);
const bool destVisible = isParentVisible(destParent);
// Reset pending move state for this operation.
m_pendingMove = PendingMove{};
if (!sourceVisible && !destVisible)
return; // Neither end is visible, nothing to do.
if (sourceVisible && destVisible) {
// Both source and destination are visible. Find the flat list range
// of the items being moved, including their entire subtrees.
int flatSourceFirst = -1;
int flatSourceLast = -1;
for (int row = sourceFirst; row <= sourceLast; ++row) {
const QModelIndex childIdx = m_sourceModel->index(row, 0, sourceParent);
const int flatRow = findFlatRow(childIdx);
if (flatRow >= 0) {
const int depth = m_items.at(flatRow).depth;
const int subtreeCount = countSubtreeItems(flatRow, depth);
if (flatSourceFirst < 0 || flatRow < flatSourceFirst)
flatSourceFirst = flatRow;
if (flatRow + subtreeCount - 1 > flatSourceLast)
flatSourceLast = flatRow + subtreeCount - 1;
}
}
if (flatSourceFirst < 0 || flatSourceLast < flatSourceFirst)
return; // Items not found in flat list (e.g. hidden by maxDepth).
// Calculate the destination position in the flat list.
int flatDestRow = findInsertPosition(destParent, destRow);
// Determine the old and new depths. Moving between parents can change
// the depth of all items in the subtree.
const int oldDepth = m_items.at(flatSourceFirst).depth;
int newDepth;
if (!destParent.isValid() && !m_rootIndex.isValid()) {
// Moving to the invisible root (top level) with no root index set.
newDepth = 0;
} else if (destParent == m_rootIndex) {
// Moving to the root index's children (depth 0 relative to root).
newDepth = 0;
} else {
// Moving under a visible parent -- depth is parent's depth + 1.
const int parentFlatRow = findFlatRow(destParent);
if (parentFlatRow >= 0)
newDepth = m_items.at(parentFlatRow).depth + 1;
else
newDepth = oldDepth; // Fallback: keep original depth.
}
// If maxDepth limits prevent the destination from being visible,
// treat this as a visible-to-invisible move (just remove).
if (m_maxDepth > 0 && newDepth >= m_maxDepth) {
beginRemoveRows(QModelIndex(), flatSourceFirst, flatSourceLast);
m_items.remove(flatSourceFirst, flatSourceLast - flatSourceFirst + 1);
endRemoveRows();
m_lastLookupRow = -1;
return;
}
// When maxDepth is active and depth changes, descendants may cross
// the maxDepth boundary in either direction: moving deeper can push
// visible descendants beyond the limit, and moving shallower can
// reveal previously-hidden descendants. Fall back to remove + re-
// flatten (handled in onSourceRowsMoved) to ensure correct filtering.
if (m_maxDepth > 0 && newDepth != oldDepth) {
removeFlatRange(sourceParent, sourceFirst, sourceLast);
return;
}
// Save copies of the moved items for use in onSourceRowsMoved.
QList<FlatItem> movedItems;
for (int i = flatSourceFirst; i <= flatSourceLast; ++i)
movedItems.append(m_items.at(i));
m_pendingMove.active = true;
m_pendingMove.sourceFirst = flatSourceFirst;
m_pendingMove.sourceLast = flatSourceLast;
m_pendingMove.destRow = flatDestRow;
m_pendingMove.oldDepth = oldDepth;
m_pendingMove.newDepth = newDepth;
m_pendingMove.movedItems = movedItems;
} else if (sourceVisible && !destVisible) {
// Items are moving from a visible area to an invisible area.
// This looks like a removal to the flat table.
removeFlatRange(sourceParent, sourceFirst, sourceLast);
}
// !sourceVisible && destVisible: handled in onSourceRowsMoved as insertion,
// because we can only read the items from their new position after the
// move completes.
}
void QTreeToTableModel::onSourceRowsMoved(const QModelIndex &sourceParent,
int sourceFirst,
int sourceLast,
const QModelIndex &destParent,
int destRow)
{
const bool sourceVisible = isParentVisible(sourceParent);
const bool destVisible = isParentVisible(destParent);
if (!sourceVisible && !destVisible)
return;
if (sourceVisible && destVisible) {
if (m_pendingMove.active) {
// Normal case: we captured the move in aboutToBeMoved. Now apply
// it to the flat list.
const int flatSourceFirst = m_pendingMove.sourceFirst;
const int flatSourceLast = m_pendingMove.sourceLast;
const int flatDestRow = m_pendingMove.destRow;
const int moveCount = flatSourceLast - flatSourceFirst + 1;
// Adjust depths of all moved items if the depth changed.
const int depthDelta = m_pendingMove.newDepth - m_pendingMove.oldDepth;
if (depthDelta != 0) {
for (FlatItem &item : m_pendingMove.movedItems)
item.depth += depthDelta;
}
// Try to emit a proper move signal. beginMoveRows will return
// false if the move is a no-op (source == dest in flat space).
if (beginMoveRows(QModelIndex(),
flatSourceFirst,
flatSourceLast,
QModelIndex(),
flatDestRow)) {
// Remove items from old position and re-insert at new position.
m_items.remove(flatSourceFirst, moveCount);
// Adjust insertion position: if we removed items before the
// destination, the destination shifts left by moveCount.
int insertAt = flatDestRow;
if (flatSourceFirst < flatDestRow)
insertAt -= moveCount;
m_items.insert(insertAt, moveCount, FlatItem{});
for (int i = 0; i < moveCount; ++i)
m_items[insertAt + i] = m_pendingMove.movedItems[i];
endMoveRows();
// Notify views that depth changed for all moved items.
if (depthDelta != 0) {
const int lastCol = columnCount() - 1;
Q_EMIT dataChanged(createIndex(insertAt, 0),
createIndex(insertAt + moveCount - 1, lastCol),
{static_cast<int>(Roles::Depth)});
}
} else {
// beginMoveRows failed (no-op move in flat space). Fall back
// to separate remove + insert signals so the state stays
// consistent.
beginRemoveRows(QModelIndex(), flatSourceFirst, flatSourceLast);
m_items.remove(flatSourceFirst, moveCount);
endRemoveRows();
int insertAt = flatDestRow;
if (flatSourceFirst < flatDestRow)
insertAt -= moveCount;
beginInsertRows(QModelIndex(), insertAt, insertAt + moveCount - 1);
m_items.insert(insertAt, moveCount, FlatItem{});
for (int i = 0; i < moveCount; ++i)
m_items[insertAt + i] = m_pendingMove.movedItems[i];
endInsertRows();
// Notify views that depth changed in the fallback path too.
if (depthDelta != 0) {
const int lastCol = columnCount() - 1;
Q_EMIT dataChanged(createIndex(insertAt, 0),
createIndex(insertAt + moveCount - 1, lastCol),
{static_cast<int>(Roles::Depth)});
}
}
m_pendingMove = PendingMove{};
} else {
// No items are recorded in m_pendingMove — either they were hidden
// by maxDepth at the source location, or they were found but
// intentionally removed by the maxDepth depth-change path (so a
// fresh re-flatten is cheaper than a move). Both parents are
// visible, so check whether items are visible at their destination
// and insert them.
insertFlatItems(destParent, destRow, sourceLast - sourceFirst + 1);
}
} else if (!sourceVisible && destVisible) {
// Items are moving from an invisible area into the visible area.
// This looks like an insertion to the flat table.
insertFlatItems(destParent, destRow, sourceLast - sourceFirst + 1);
}
m_lastLookupRow = -1; // Invalidate lookup cache after move.
}
// -- Column change handling --
//
// Column changes are only forwarded when they occur at the effective root of
// the flattened table, because QTreeToTableModel flattens the column count
// from the root level only.
void QTreeToTableModel::onSourceColumnsAboutToBeInserted(const QModelIndex &parent,
int first,
int last)
{
if (isColumnChangeAtRoot(parent))
beginInsertColumns(QModelIndex(), first, last);
}
void QTreeToTableModel::onSourceColumnsInserted(const QModelIndex &parent, int first, int last)
{
Q_UNUSED(first)
Q_UNUSED(last)
if (isColumnChangeAtRoot(parent))
endInsertColumns();
}
void QTreeToTableModel::onSourceColumnsAboutToBeRemoved(const QModelIndex &parent,
int first,
int last)
{
if (isColumnChangeAtRoot(parent))
beginRemoveColumns(QModelIndex(), first, last);
}
void QTreeToTableModel::onSourceColumnsRemoved(const QModelIndex &parent, int first, int last)
{
Q_UNUSED(first)
Q_UNUSED(last)