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
qstandarditemmodel.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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 reason:default
4
6
7#include <QtCore/qdatetime.h>
8#include <QtCore/qlist.h>
9#include <QtCore/qmap.h>
10#include <QtCore/qvariant.h>
11#include <QtCore/qstringlist.h>
12#include <QtCore/qbitarray.h>
13#include <QtCore/qmimedata.h>
14#include <QtCore/qscopedvaluerollback.h>
15#include <QtCore/qiodevice.h>
16#include <private/qduplicatetracker_p.h>
17#include <private/qstandarditemmodel_p.h>
18#include <qdebug.h>
19#include <algorithm>
20
21QT_BEGIN_NAMESPACE
22
23static inline QString qStandardItemModelDataListMimeType()
24{
25 return QStringLiteral("application/x-qstandarditemmodeldatalist");
26}
27
29{
30public:
33
34 inline bool operator()(const std::pair<QStandardItem*, int> &l,
35 const std::pair<QStandardItem*, int> &r) const
36 {
37 return *(l.first) < *(r.first);
38 }
39};
40
42{
43public:
46
47 inline bool operator()(const std::pair<QStandardItem*, int> &l,
48 const std::pair<QStandardItem*, int> &r) const
49 {
50 return *(r.first) < *(l.first);
51 }
52};
53
54/*!
55 \internal
56*/
57std::pair<int, int> QStandardItemPrivate::position() const
58{
59 if (QStandardItem *par = parent) {
60 int idx = par->d_func()->childIndex(q_func());
61 if (idx == -1)
62 return std::pair<int, int>(-1, -1);
63 return std::pair<int, int>(idx / par->columnCount(), idx % par->columnCount());
64 }
65 // ### support header items?
66 return std::pair<int, int>(-1, -1);
67}
68
69/*!
70 \internal
71*/
72void QStandardItemPrivate::setChild(int row, int column, QStandardItem *item,
73 bool emitChanged)
74{
75 Q_Q(QStandardItem);
76 if (item == q) {
77 qWarning("QStandardItem::setChild: Can't make an item a child of itself %p",
78 item);
79 return;
80 }
81 if ((row < 0) || (column < 0))
82 return;
83 if (rows <= row)
84 q->setRowCount(row + 1);
85 if (columns <= column)
86 q->setColumnCount(column + 1);
87 int index = childIndex(row, column);
88 Q_ASSERT(index != -1);
89 QStandardItem *oldItem = children.at(index);
90 if (item == oldItem)
91 return;
92
93 if (model && emitChanged) {
94 emit model->layoutAboutToBeChanged();
95 }
96
97 if (item) {
98 if (item->d_func()->parent == nullptr) {
99 item->d_func()->setParentAndModel(q, model);
100 } else {
101 qWarning("QStandardItem::setChild: Ignoring duplicate insertion of item %p",
102 item);
103 return;
104 }
105 }
106
107 // setting the model to nullptr invalidates the persistent index which we want to avoid
108 if (!item && oldItem)
109 oldItem->d_func()->setModel(nullptr);
110
111 children.replace(index, item);
112
113 // since now indexFromItem() does no longer return a valid index, the persistent index
114 // will not be invalidated anymore
115 if (oldItem)
116 oldItem->d_func()->setModel(nullptr);
117 delete oldItem;
118
119 if (item)
120 item->d_func()->lastKnownIndex = index;
121
122 if (model && emitChanged)
123 emit model->layoutChanged();
124
125 if (emitChanged && model) {
126 if (item) {
127 model->d_func()->itemChanged(item);
128 } else {
129 const QModelIndex idx = model->index(row, column, q->index());
130 emit model->dataChanged(idx, idx);
131 }
132 if (column == 0)
133 notifyChildrenChanged();
134 }
135}
136
137
138/*!
139 \internal
140*/
141void QStandardItemPrivate::changeFlags(bool enable, Qt::ItemFlags f)
142{
143 Q_Q(QStandardItem);
144 Qt::ItemFlags flags = q->flags();
145 if (enable)
146 flags |= f;
147 else
148 flags &= ~f;
149 q->setFlags(flags);
150}
151
152/*!
153 \internal
154
155 Returns the parent of this item if this item is in the first column,
156 where the children of an auto-tristate item are.
157*/
158QStandardItem *QStandardItemPrivate::checkStateParent() const
159{
160 return parent && position().second == 0 ? parent : nullptr;
161}
162
163/*!
164 \internal
165
166 Returns the check state that results from the check state of the children
167 of \a item, or an invalid QVariant if one of them has no check state.
168*/
169static QVariant childrenCheckState(const QStandardItem *item)
170{
171 bool checkedChildren = false;
172 bool uncheckedChildren = false;
173 const int rowCount = item->rowCount();
174 for (int row = 0; row < rowCount; ++row) {
175 const QStandardItem *child = item->child(row);
176 if (!child)
177 return QVariant();
178 const QVariant value = child->data(Qt::CheckStateRole);
179 if (!value.isValid())
180 return QVariant();
181
182 switch (value.toInt()) {
183 case Qt::Unchecked:
184 uncheckedChildren = true;
185 break;
186 case Qt::Checked:
187 checkedChildren = true;
188 break;
189 default:
190 return Qt::PartiallyChecked;
191 }
192
193 if (uncheckedChildren && checkedChildren)
194 return Qt::PartiallyChecked;
195 }
196 return uncheckedChildren ? Qt::Unchecked : Qt::Checked;
197}
198
199/*!
200 \internal
201
202 If this item is auto-tristate and \a value is Qt::Checked or Qt::Unchecked,
203 sets \a value as the check state of the children of this item that have
204 a check state.
205 Returns \c true if the check state of one of them changed.
206*/
207bool QStandardItemPrivate::setChildrenCheckState(const QVariant &value)
208{
209 Q_Q(QStandardItem);
210 if (rows == 0 || !value.isValid() || value.toInt() == Qt::PartiallyChecked
211 || !q->isAutoTristate()) {
212 return false;
213 }
214 // The children don't notify this item, setData() does it once at the end
215 const QScopedValueRollback guard(settingChildrenCheckState, true);
216 bool changed = false;
217 for (int row = 0; row < rows; ++row) {
218 QStandardItem *child = q->child(row);
219 if (!child)
220 continue;
221 const QVariant oldState = child->data(Qt::CheckStateRole);
222 if (oldState.isValid()) {
223 child->setData(value, Qt::CheckStateRole);
224 changed = changed || oldState.toInt() != value.toInt();
225 }
226 }
227 return changed;
228}
229
230/*!
231 \internal
232
233 Makes the model emit dataChanged() for the auto-tristate ancestors whose
234 check state depends on the check state of this item.
235*/
236void QStandardItemPrivate::notifyAutoTristateAncestors()
237{
238 if (!model)
239 return;
240 for (QStandardItem *p = checkStateParent();
241 p && p->isAutoTristate() && !p->d_func()->settingChildrenCheckState;
242 p = p->d_func()->checkStateParent()) {
243 model->d_func()->itemChanged(p, {Qt::CheckStateRole});
244 }
245}
246
247/*!
248 \internal
249
250 Makes the model emit dataChanged() for this item, if it is auto-tristate,
251 and for its auto-tristate ancestors.
252 Called after children in the first column were added, removed or replaced.
253*/
254void QStandardItemPrivate::notifyChildrenChanged()
255{
256 Q_Q(QStandardItem);
257 if (!model || !q->isAutoTristate())
258 return;
259 model->d_func()->itemChanged(q, {Qt::CheckStateRole});
260 notifyAutoTristateAncestors();
261}
262
263/*!
264 \internal
265*/
266void QStandardItemPrivate::childDeleted(QStandardItem *child)
267{
268 int index = childIndex(child);
269 Q_ASSERT(index != -1);
270 const auto modelIndex = child->index();
271 children.replace(index, nullptr);
272 emit model->dataChanged(modelIndex, modelIndex);
273 if (index % columnCount() == 0)
274 notifyChildrenChanged();
275}
276
277namespace {
278
279 struct ByNormalizedRole
280 {
281 static int normalizedRole(int role)
282 {
283 return role == Qt::EditRole ? Qt::DisplayRole : role;
284 }
285
286 bool operator()(const QStandardItemData& standardItemData, const std::pair<const int &, const QVariant&>& roleMapIt) const
287 {
288 return standardItemData.role < normalizedRole(roleMapIt.first);
289 }
290 bool operator()(const std::pair<const int&, const QVariant &>& roleMapIt, const QStandardItemData& standardItemData) const
291 {
292 return normalizedRole(roleMapIt.first) < standardItemData.role;
293 }
294
295 };
296
297 /*
298 Based on std::transform with a twist. The inputs are iterators of <int, QVariant> pair.
299 The variant is checked for validity and if not valid, that element is not taken into account
300 which means that the resulting output might be shorter than the input.
301 */
302 template<class Input, class OutputIt>
303 OutputIt roleMapStandardItemDataTransform(Input first1, Input last1, OutputIt d_first)
304 {
305 while (first1 != last1) {
306 if ((*first1).second.isValid())
307 *d_first++ = QStandardItemData(*first1);
308 ++first1;
309 }
310 return d_first;
311 }
312
313
314 /*
315 Based on std::set_union with a twist. The idea is to create a union of both inputs
316 with an additional constraint: if an input contains an invalid variant, it means
317 that this one should not be taken into account for generating the output.
318 */
319 template<class Input1, class Input2,
320 class OutputIt, class Compare>
321 OutputIt roleMapStandardItemDataUnion(Input1 first1, Input1 last1,
322 Input2 first2, Input2 last2,
323 OutputIt d_first, Compare comp)
324 {
325 for (; first1 != last1; ++d_first) {
326 if (first2 == last2) {
327 return roleMapStandardItemDataTransform(first1, last1, d_first);
328 }
329 if (comp(*first2, *first1)) {
330 *d_first = *first2++;
331 } else {
332 if ((*first1).second.isValid())
333 *d_first = QStandardItemData(*first1);
334 if (!comp(*first1, *first2))
335 ++first2;
336 ++first1;
337 }
338 }
339 return std::copy(first2, last2, d_first);
340 }
341}
342
343/*!
344 \internal
345*/
346void QStandardItemPrivate::setItemData(const QMap<int, QVariant> &roles)
347{
348 Q_Q(QStandardItem);
349
350 auto byRole = [](const QStandardItemData& item1, const QStandardItemData& item2) {
351 return item1.role < item2.role;
352 };
353
354 const auto checkState = roles.constFind(Qt::CheckStateRole);
355 const bool hasCheckState = checkState != roles.cend();
356 const bool childrenChanged = hasCheckState && setChildrenCheckState(*checkState);
357
358 std::sort(values.begin(), values.end(), byRole);
359
360 /*
361 Create a list of QStandardItemData that will contain the original values
362 if the matching role is not contained in roles, the new value if it is and
363 if the new value is an invalid QVariant, it will be removed.
364 */
365 QList<QStandardItemData> newValues;
366 newValues.reserve(values.size());
367 roleMapStandardItemDataUnion(roles.keyValueBegin(),
368 roles.keyValueEnd(),
369 values.cbegin(), values.cend(),
370 std::back_inserter(newValues), ByNormalizedRole());
371
372 if (newValues != values) {
373 values.swap(newValues);
374 if (model) {
375 QList<int> roleKeys;
376 roleKeys.reserve(roles.size() + 1);
377 bool hasEditRole = false;
378 bool hasDisplayRole = false;
379 for (auto it = roles.keyBegin(); it != roles.keyEnd(); ++it) {
380 roleKeys.push_back(*it);
381 if (*it == Qt::EditRole)
382 hasEditRole = true;
383 else if (*it == Qt::DisplayRole)
384 hasDisplayRole = true;
385 }
386 if (hasEditRole && !hasDisplayRole)
387 roleKeys.push_back(Qt::DisplayRole);
388 else if (!hasEditRole && hasDisplayRole)
389 roleKeys.push_back(Qt::EditRole);
390 model->d_func()->itemChanged(q, roleKeys);
391 if (hasCheckState)
392 notifyAutoTristateAncestors();
393 }
394 } else if (childrenChanged && model) {
395 model->d_func()->itemChanged(q, {Qt::CheckStateRole});
396 notifyAutoTristateAncestors();
397 }
398}
399
400/*!
401 \internal
402*/
403QMap<int, QVariant> QStandardItemPrivate::itemData() const
404{
405 Q_Q(const QStandardItem);
406 QMap<int, QVariant> result;
407 for (const auto &data : values) {
408 if (data.role != Qt::StandardItemFlagsRole)
409 result.insert(data.role, data.value);
410 }
411 if (rows > 0 && q->isAutoTristate()) {
412 if (const QVariant state = childrenCheckState(q); state.isValid())
413 result.insert(Qt::CheckStateRole, state);
414 else
415 result.remove(Qt::CheckStateRole);
416 }
417 return result;
418}
419
420/*!
421 \internal
422*/
423void QStandardItemPrivate::sortChildren(int column, Qt::SortOrder order)
424{
425 Q_Q(QStandardItem);
426 if (column >= columnCount())
427 return;
428
429 QList<std::pair<QStandardItem*, int> > sortable;
430 QList<int> unsortable;
431
432 sortable.reserve(rowCount());
433 unsortable.reserve(rowCount());
434
435 for (int row = 0; row < rowCount(); ++row) {
436 QStandardItem *itm = q->child(row, column);
437 if (itm)
438 sortable.emplace_back(itm, row);
439 else
440 unsortable.append(row);
441 }
442
443 if (order == Qt::AscendingOrder) {
444 QStandardItemModelLessThan lt;
445 std::stable_sort(sortable.begin(), sortable.end(), lt);
446 } else {
447 QStandardItemModelGreaterThan gt;
448 std::stable_sort(sortable.begin(), sortable.end(), gt);
449 }
450
451 QModelIndexList changedPersistentIndexesFrom, changedPersistentIndexesTo;
452 QList<QStandardItem*> sorted_children(children.size());
453 for (int i = 0; i < rowCount(); ++i) {
454 int r = (i < sortable.size()
455 ? sortable.at(i).second
456 : unsortable.at(i - sortable.size()));
457 for (int c = 0; c < columnCount(); ++c) {
458 QStandardItem *itm = q->child(r, c);
459 sorted_children[childIndex(i, c)] = itm;
460 if (model) {
461 QModelIndex from = model->createIndex(r, c, q);
462 if (model->d_func()->persistent.indexes.contains(from)) {
463 QModelIndex to = model->createIndex(i, c, q);
464 changedPersistentIndexesFrom.append(from);
465 changedPersistentIndexesTo.append(to);
466 }
467 }
468 }
469 }
470
471 children = sorted_children;
472
473 if (model) {
474 model->changePersistentIndexList(changedPersistentIndexesFrom, changedPersistentIndexesTo);
475 }
476
477 QList<QStandardItem*>::iterator it;
478 for (it = children.begin(); it != children.end(); ++it) {
479 if (*it)
480 (*it)->d_func()->sortChildren(column, order);
481 }
482}
483
484/*!
485 \internal
486 set the model of this item and all its children
487 */
488void QStandardItemPrivate::setModel(QStandardItemModel *mod)
489{
490 if (children.isEmpty()) {
491 if (model)
492 model->d_func()->invalidatePersistentIndex(model->indexFromItem(q_ptr));
493 model = mod;
494 } else {
495 QStack<QStandardItem*> stack;
496 stack.push(q_ptr);
497 while (!stack.isEmpty()) {
498 QStandardItem *itm = stack.pop();
499 if (itm->d_func()->model) {
500 itm->d_func()->model->d_func()->invalidatePersistentIndex(itm->d_func()->model->indexFromItem(itm));
501 }
502 itm->d_func()->model = mod;
503 const QList<QStandardItem*> &childList = itm->d_func()->children;
504 for (int i = 0; i < childList.size(); ++i) {
505 QStandardItem *chi = childList.at(i);
506 if (chi)
507 stack.push(chi);
508 }
509 }
510 }
511}
512
513/*!
514 \internal
515*/
516QStandardItemModelPrivate::QStandardItemModelPrivate()
517 : root(new QStandardItem), itemPrototype(nullptr)
518{
519 root->setFlags(Qt::ItemIsDropEnabled);
520}
521
522/*!
523 \internal
524*/
525QStandardItemModelPrivate::~QStandardItemModelPrivate()
526{
527}
528
529/*!
530 \internal
531*/
532void QStandardItemModelPrivate::init()
533{
534 Q_Q(QStandardItemModel);
535 QObject::connect(q, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
536 q, SLOT(_q_emitItemChanged(QModelIndex,QModelIndex)));
537 roleNames = QAbstractItemModelPrivate::defaultRoleNames();
538}
539
540/*!
541 \internal
542*/
543void QStandardItemModelPrivate::_q_emitItemChanged(const QModelIndex &topLeft,
544 const QModelIndex &bottomRight)
545{
546 Q_Q(QStandardItemModel);
547 QModelIndex parent = topLeft.parent();
548 for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
549 for (int column = topLeft.column(); column <= bottomRight.column(); ++column) {
550 QModelIndex index = q->index(row, column, parent);
551 if (QStandardItem *item = itemFromIndex(index))
552 emit q->itemChanged(item);
553 }
554 }
555}
556
557/*!
558 \internal
559*/
560bool QStandardItemPrivate::insertRows(int row, const QList<QStandardItem*> &items)
561{
562 Q_Q(QStandardItem);
563 if ((row < 0) || (row > rowCount()) || items.isEmpty())
564 return false;
565 int count = items.size();
566 if (model)
567 model->d_func()->rowsAboutToBeInserted(q, row, row + count - 1);
568 if (rowCount() == 0) {
569 if (columnCount() == 0)
570 q->setColumnCount(1);
571 children.resize(columnCount() * count);
572 rows = count;
573 } else {
574 rows += count;
575 int index = childIndex(row, 0);
576 if (index != -1)
577 children.insert(index, columnCount() * count, nullptr);
578 }
579 for (int i = 0; i < items.size(); ++i) {
580 QStandardItem *item = items.at(i);
581 item->d_func()->setParentAndModel(q, model);
582 int index = childIndex(i + row, 0);
583 children.replace(index, item);
584 if (item)
585 item->d_func()->lastKnownIndex = index;
586 }
587 if (model)
588 model->d_func()->rowsInserted(q, row, count);
589 return true;
590}
591
592bool QStandardItemPrivate::insertRows(int row, int count, const QList<QStandardItem*> &items)
593{
594 Q_Q(QStandardItem);
595 if ((count < 1) || (row < 0) || (row > rowCount()) || count == 0)
596 return false;
597 if (model)
598 model->d_func()->rowsAboutToBeInserted(q, row, row + count - 1);
599 if (rowCount() == 0) {
600 children.resize(columnCount() * count);
601 rows = count;
602 } else {
603 rows += count;
604 int index = childIndex(row, 0);
605 if (index != -1)
606 children.insert(index, columnCount() * count, nullptr);
607 }
608 if (!items.isEmpty()) {
609 int index = childIndex(row, 0);
610 int limit = qMin(items.size(), columnCount() * count);
611 for (int i = 0; i < limit; ++i) {
612 QStandardItem *item = items.at(i);
613 if (item) {
614 if (item->d_func()->parent == nullptr) {
615 item->d_func()->setParentAndModel(q, model);
616 } else {
617 qWarning("QStandardItem::insertRows: Ignoring duplicate insertion of item %p",
618 item);
619 item = nullptr;
620 }
621 }
622 children.replace(index, item);
623 if (item)
624 item->d_func()->lastKnownIndex = index;
625 ++index;
626 }
627 }
628 if (model)
629 model->d_func()->rowsInserted(q, row, count);
630 return true;
631}
632
633/*!
634 \internal
635*/
636bool QStandardItemPrivate::insertColumns(int column, int count, const QList<QStandardItem*> &items)
637{
638 Q_Q(QStandardItem);
639 if ((count < 1) || (column < 0) || (column > columnCount()) || count == 0)
640 return false;
641 if (model)
642 model->d_func()->columnsAboutToBeInserted(q, column, column + count - 1);
643 if (columnCount() == 0) {
644 children.resize(rowCount() * count);
645 columns = count;
646 } else {
647 columns += count;
648 int index = childIndex(0, column);
649 for (int row = 0; row < rowCount(); ++row) {
650 children.insert(index, count, nullptr);
651 index += columnCount();
652 }
653 }
654 if (!items.isEmpty()) {
655 int limit = qMin(items.size(), rowCount() * count);
656 for (int i = 0; i < limit; ++i) {
657 QStandardItem *item = items.at(i);
658 if (item) {
659 if (item->d_func()->parent == nullptr) {
660 item->d_func()->setParentAndModel(q, model);
661 } else {
662 qWarning("QStandardItem::insertColumns: Ignoring duplicate insertion of item %p",
663 item);
664 item = nullptr;
665 }
666 }
667 int r = i / count;
668 int c = column + (i % count);
669 int index = childIndex(r, c);
670 children.replace(index, item);
671 if (item)
672 item->d_func()->lastKnownIndex = index;
673 }
674 }
675 if (model)
676 model->d_func()->columnsInserted(q, column, count);
677 return true;
678}
679
680/*!
681 \internal
682*/
683void QStandardItemModelPrivate::itemChanged(QStandardItem *item, const QList<int> &roles)
684{
685 Q_Q(QStandardItemModel);
686 Q_ASSERT(item);
687 if (item->d_func()->parent == nullptr) {
688 // Header item
689 int idx = columnHeaderItems.indexOf(item);
690 if (idx != -1) {
691 emit q->headerDataChanged(Qt::Horizontal, idx, idx);
692 } else {
693 idx = rowHeaderItems.indexOf(item);
694 if (idx != -1)
695 emit q->headerDataChanged(Qt::Vertical, idx, idx);
696 }
697 } else {
698 // Normal item
699 const QModelIndex index = q->indexFromItem(item);
700 emit q->dataChanged(index, index, roles);
701 }
702}
703
704/*!
705 \internal
706*/
707void QStandardItemModelPrivate::rowsAboutToBeInserted(QStandardItem *parent,
708 int start, int end)
709{
710 Q_Q(QStandardItemModel);
711 QModelIndex index = q->indexFromItem(parent);
712 q->beginInsertRows(index, start, end);
713}
714
715/*!
716 \internal
717*/
718void QStandardItemModelPrivate::columnsAboutToBeInserted(QStandardItem *parent,
719 int start, int end)
720{
721 Q_Q(QStandardItemModel);
722 QModelIndex index = q->indexFromItem(parent);
723 q->beginInsertColumns(index, start, end);
724}
725
726/*!
727 \internal
728*/
729void QStandardItemModelPrivate::rowsAboutToBeRemoved(QStandardItem *parent,
730 int start, int end)
731{
732 Q_Q(QStandardItemModel);
733 QModelIndex index = q->indexFromItem(parent);
734 q->beginRemoveRows(index, start, end);
735}
736
737/*!
738 \internal
739*/
740void QStandardItemModelPrivate::columnsAboutToBeRemoved(QStandardItem *parent,
741 int start, int end)
742{
743 Q_Q(QStandardItemModel);
744 QModelIndex index = q->indexFromItem(parent);
745 q->beginRemoveColumns(index, start, end);
746}
747
748/*!
749 \internal
750*/
751void QStandardItemModelPrivate::rowsInserted(QStandardItem *parent,
752 int row, int count)
753{
754 Q_Q(QStandardItemModel);
755 if (parent == root.data())
756 rowHeaderItems.insert(row, count, nullptr);
757 q->endInsertRows();
758 parent->d_func()->notifyChildrenChanged();
759}
760
761/*!
762 \internal
763*/
764void QStandardItemModelPrivate::columnsInserted(QStandardItem *parent,
765 int column, int count)
766{
767 Q_Q(QStandardItemModel);
768 if (parent == root.data())
769 columnHeaderItems.insert(column, count, nullptr);
770 q->endInsertColumns();
771 if (column == 0)
772 parent->d_func()->notifyChildrenChanged();
773}
774
775/*!
776 \internal
777*/
778void QStandardItemModelPrivate::rowsRemoved(QStandardItem *parent,
779 int row, int count)
780{
781 Q_Q(QStandardItemModel);
782 if (parent == root.data()) {
783 for (int i = row; i < row + count; ++i) {
784 QStandardItem *oldItem = rowHeaderItems.at(i);
785 if (oldItem)
786 oldItem->d_func()->setModel(nullptr);
787 delete oldItem;
788 }
789 rowHeaderItems.remove(row, count);
790 }
791 q->endRemoveRows();
792 parent->d_func()->notifyChildrenChanged();
793}
794
795/*!
796 \internal
797*/
798void QStandardItemModelPrivate::columnsRemoved(QStandardItem *parent,
799 int column, int count)
800{
801 Q_Q(QStandardItemModel);
802 if (parent == root.data()) {
803 for (int i = column; i < column + count; ++i) {
804 QStandardItem *oldItem = columnHeaderItems.at(i);
805 if (oldItem)
806 oldItem->d_func()->setModel(nullptr);
807 delete oldItem;
808 }
809 columnHeaderItems.remove(column, count);
810 }
811 q->endRemoveColumns();
812 if (column == 0)
813 parent->d_func()->notifyChildrenChanged();
814}
815
816/*!
817 \class QStandardItem
818 \brief The QStandardItem class provides an item for use with the
819 QStandardItemModel class.
820 \since 4.2
821 \ingroup model-view
822 \inmodule QtGui
823
824 Items usually contain text, icons, or checkboxes.
825
826 Each item can have its own background brush which is set with the
827 setBackground() function. The current background brush can be found with
828 background(). The text label for each item can be rendered with its own
829 font and brush. These are specified with the setFont() and setForeground()
830 functions, and read with font() and foreground().
831
832 By default, items are enabled, editable, selectable, checkable, and can be
833 used both as the source of a drag and drop operation and as a drop target.
834 Each item's flags can be changed by calling setFlags(). Checkable items
835 can be checked and unchecked with the setCheckState() function. The
836 corresponding checkState() function indicates whether the item is
837 currently checked.
838
839 You can store application-specific data in an item by calling setData().
840
841 Each item can have a two-dimensional table of child items. This makes it
842 possible to build hierarchies of items. The typical hierarchy is the tree,
843 in which case the child table is a table with a single column (a list).
844
845 The dimensions of the child table can be set with setRowCount() and
846 setColumnCount(). Items can be positioned in the child table with
847 setChild(). Get a pointer to a child item with child(). New rows and
848 columns of children can also be inserted with insertRow() and
849 insertColumn(), or appended with appendRow() and appendColumn(). When
850 using the append and insert functions, the dimensions of the child table
851 will grow as needed.
852
853 An existing row of children can be removed with removeRow() or takeRow();
854 correspondingly, a column can be removed with removeColumn() or
855 takeColumn().
856
857 An item's children can be sorted by calling sortChildren().
858
859 \section1 Subclassing
860
861 When subclassing QStandardItem to provide custom items, it is possible to
862 define new types for them so that they can be distinguished from the base
863 class. The type() function should be reimplemented to return a new type
864 value equal to or greater than \l UserType.
865
866 Reimplement data() and setData() if you want to perform custom handling of
867 data queries and/or control how an item's data is represented.
868
869 Reimplement clone() if you want QStandardItemModel to be able to create
870 instances of your custom item class on demand (see
871 QStandardItemModel::setItemPrototype()).
872
873 Reimplement read() and write() if you want to control how items are
874 represented in their serialized form.
875
876 Reimplement \l{operator<()} if you want to control the semantics of item
877 comparison. \l{operator<()} determines the sorted order when sorting items
878 with sortChildren() or with QStandardItemModel::sort().
879
880 \sa QStandardItemModel, {Item View Convenience Classes}, {Model/View Programming}
881*/
882
883/*!
884 \enum QStandardItem::ItemType
885
886 This enum describes the types that are used to describe standard items.
887
888 \value Type The default type for standard items.
889 \value UserType The minimum value for custom types. Values below UserType are
890 reserved by Qt.
891
892 You can define new user types in QStandardItem subclasses to ensure that
893 custom items are treated specially; for example, when items are sorted.
894
895 \sa type()
896*/
897
898/*!
899 Constructs an item.
900*/
901QStandardItem::QStandardItem()
902 : QStandardItem(*new QStandardItemPrivate)
903{
904}
905
906/*!
907 Constructs an item with the given \a text.
908*/
909QStandardItem::QStandardItem(const QString &text)
910 : QStandardItem(*new QStandardItemPrivate)
911{
912 setText(text);
913}
914
915/*!
916 Constructs an item with the given \a icon and \a text.
917*/
918QStandardItem::QStandardItem(const QIcon &icon, const QString &text)
919 : QStandardItem(text)
920{
921 setIcon(icon);
922}
923
924/*!
925 Constructs an item with \a rows rows and \a columns columns of child items.
926*/
927QStandardItem::QStandardItem(int rows, int columns)
928 : QStandardItem(*new QStandardItemPrivate)
929{
930 setRowCount(rows);
931 setColumnCount(columns);
932}
933
934/*!
935 \internal
936*/
937QStandardItem::QStandardItem(QStandardItemPrivate &dd)
938 : d_ptr(&dd)
939{
940 Q_D(QStandardItem);
941 d->q_ptr = this;
942}
943
944/*!
945 Constructs a copy of \a other. Note that model() is
946 not copied.
947
948 This function is useful when reimplementing clone().
949*/
950QStandardItem::QStandardItem(const QStandardItem &other)
951 : d_ptr(new QStandardItemPrivate)
952{
953 Q_D(QStandardItem);
954 d->q_ptr = this;
955 operator=(other);
956}
957
958/*!
959 Assigns \a other's data and flags to this item. Note that
960 type() and model() are not copied.
961
962 This function is useful when reimplementing clone().
963*/
964QStandardItem &QStandardItem::operator=(const QStandardItem &other)
965{
966 Q_D(QStandardItem);
967 d->values = other.d_func()->values;
968 return *this;
969}
970
971/*!
972 Destructs the item.
973 This causes the item's children to be destructed as well.
974*/
975QStandardItem::~QStandardItem()
976{
977 Q_D(QStandardItem);
978 for (QStandardItem *child : std::as_const(d->children)) {
979 if (child)
980 child->d_func()->setModel(nullptr);
981 delete child;
982 }
983 d->children.clear();
984 if (d->parent && d->model)
985 d->parent->d_func()->childDeleted(this);
986}
987
988/*!
989 Returns the item's parent item, or \nullptr if the item has no parent.
990 \note For toplevel items parent() returns \nullptr. To receive toplevel
991 item's parent use QStandardItemModel::invisibleRootItem() instead.
992
993 \sa child(), QStandardItemModel::invisibleRootItem()
994*/
995QStandardItem *QStandardItem::parent() const
996{
997 Q_D(const QStandardItem);
998 if (!d->model || (d->model->d_func()->root.data() != d->parent))
999 return d->parent;
1000 return nullptr;
1001}
1002
1003/*!
1004 Sets the item's data for the given \a role to the specified \a value.
1005
1006 If you subclass QStandardItem and reimplement this function, your
1007 reimplementation should:
1008 \list
1009 \li call emitDataChanged() if you do not call the base implementation of
1010 setData(). This will ensure that e.g. views using the model are notified
1011 of the changes
1012 \li call the base implementation for roles you don't handle, otherwise
1013 setting flags, e.g. by calling setFlags(), setCheckable(), setEditable()
1014 etc., will not work.
1015 \endlist
1016
1017 \note The default implementation treats Qt::EditRole and Qt::DisplayRole
1018 as referring to the same data.
1019
1020 \sa Qt::ItemDataRole, data(), setFlags()
1021*/
1022void QStandardItem::setData(const QVariant &value, int role)
1023{
1024 Q_D(QStandardItem);
1025 role = (role == Qt::EditRole) ? Qt::DisplayRole : role;
1026 const QList<int> roles((role == Qt::DisplayRole) ?
1027 QList<int>({Qt::DisplayRole, Qt::EditRole}) :
1028 QList<int>({role}));
1029 const bool childrenChanged = role == Qt::CheckStateRole && d->setChildrenCheckState(value);
1030 const bool wasAutoTristate = role == Qt::StandardItemFlagsRole && isAutoTristate();
1031 auto notifyModel = [&] {
1032 if (!d->model)
1033 return;
1034 // Turning auto-tristate on or off changes the check state
1035 const bool autoTristateChanged = role == Qt::StandardItemFlagsRole
1036 && wasAutoTristate != isAutoTristate();
1037 const QList<int> changedRoles = autoTristateChanged
1038 ? QList<int>{role, Qt::CheckStateRole} : roles;
1039 d->model->d_func()->itemChanged(this, changedRoles);
1040 if (role == Qt::CheckStateRole || autoTristateChanged)
1041 d->notifyAutoTristateAncestors();
1042 };
1043 for (auto it = d->values.begin(); it != d->values.end(); ++it) {
1044 if ((*it).role == role) {
1045 if (value.isValid()) {
1046 if ((*it).value.userType() == value.userType() && (*it).value == value) {
1047 if (childrenChanged)
1048 notifyModel();
1049 return;
1050 }
1051 (*it).value = value;
1052 } else {
1053 // Don't need to assign proper it after erase() since we
1054 // return unconditionally in this code path.
1055 d->values.erase(it);
1056 }
1057 notifyModel();
1058 return;
1059 }
1060 }
1061 d->values.append(QStandardItemData(role, value));
1062 notifyModel();
1063}
1064
1065/*!
1066 \since 5.12
1067 Removes all the data from all roles previously set.
1068 \sa data(), setData()
1069*/
1070void QStandardItem::clearData()
1071{
1072 Q_D(QStandardItem);
1073 if (d->values.isEmpty())
1074 return;
1075 const bool hadCheckState = data(Qt::CheckStateRole).isValid();
1076 d->values.clear();
1077 if (d->model) {
1078 d->model->d_func()->itemChanged(this, QList<int>{});
1079 if (hadCheckState)
1080 d->notifyAutoTristateAncestors();
1081 }
1082}
1083
1084/*!
1085 Returns the item's data for the given \a role, or an invalid
1086 QVariant if there is no data for the role.
1087
1088 If you reimplement this function, your reimplementation should call
1089 the base implementation for roles you don't handle, otherwise getting
1090 flags, e.g. by calling flags(), isCheckable(), isEditable() etc.,
1091 will not work.
1092
1093 \note The default implementation treats Qt::EditRole and Qt::DisplayRole
1094 as referring to the same data.
1095*/
1096QVariant QStandardItem::data(int role) const
1097{
1098 Q_D(const QStandardItem);
1099 const int r = (role == Qt::EditRole) ? Qt::DisplayRole : role;
1100 if (r == Qt::CheckStateRole && d->rows > 0 && isAutoTristate())
1101 return childrenCheckState(this);
1102 for (const auto &value : d->values) {
1103 if (value.role == r)
1104 return value.value;
1105 }
1106 return QVariant();
1107}
1108
1109/*!
1110 \since 6.0
1111
1112 Fills the \a roleDataSpan span with the data from this item.
1113
1114 The default implementation simply calls data() for each role
1115 in the span.
1116
1117 \sa data()
1118*/
1119void QStandardItem::multiData(QModelRoleDataSpan roleDataSpan) const
1120{
1121 for (auto &roleData : roleDataSpan)
1122 roleData.setData(data(roleData.role()));
1123}
1124
1125/*!
1126 \since 4.4
1127
1128 Causes the model associated with this item to emit a
1129 \l{QAbstractItemModel::dataChanged()}{dataChanged}() signal for this
1130 item.
1131
1132 You normally only need to call this function if you have subclassed
1133 QStandardItem and reimplemented data() and/or setData().
1134
1135 \sa setData()
1136*/
1137void QStandardItem::emitDataChanged()
1138{
1139 Q_D(QStandardItem);
1140 if (d->model)
1141 d->model->d_func()->itemChanged(this);
1142}
1143
1144/*!
1145 Sets the item flags for the item to \a flags.
1146
1147 The item flags determine how the user can interact with the item.
1148 This is often used to disable an item.
1149
1150 \sa flags(), setData()
1151*/
1152void QStandardItem::setFlags(Qt::ItemFlags flags)
1153{
1154 setData((int)flags, Qt::StandardItemFlagsRole);
1155}
1156
1157/*!
1158 Returns the item flags for the item.
1159
1160 The item flags determine how the user can interact with the item.
1161
1162 By default, items are enabled, editable, selectable, checkable, and can be
1163 used both as the source of a drag and drop operation and as a drop target.
1164
1165 \sa setFlags()
1166*/
1167Qt::ItemFlags QStandardItem::flags() const
1168{
1169 QVariant v = data(Qt::StandardItemFlagsRole);
1170 if (!v.isValid())
1171 return (Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable
1172 |Qt::ItemIsDragEnabled|Qt::ItemIsDropEnabled);
1173 return Qt::ItemFlags(v.toInt());
1174}
1175
1176/*!
1177 \fn QString QStandardItem::text() const
1178
1179 Returns the item's text. This is the text that's presented to the user
1180 in a view.
1181
1182 \sa setText()
1183*/
1184
1185/*!
1186 \fn void QStandardItem::setText(const QString &text)
1187
1188 Sets the item's text to the \a text specified.
1189
1190 \sa text(), setFont(), setForeground()
1191*/
1192
1193/*!
1194 \fn QIcon QStandardItem::icon() const
1195
1196 Returns the item's icon.
1197
1198 \sa setIcon(), {QAbstractItemView::iconSize}{iconSize}
1199*/
1200
1201/*!
1202 \fn void QStandardItem::setIcon(const QIcon &icon)
1203
1204 Sets the item's icon to the \a icon specified.
1205*/
1206
1207/*!
1208 \fn QString QStandardItem::statusTip() const
1209
1210 Returns the item's status tip.
1211
1212 \sa setStatusTip(), toolTip(), whatsThis()
1213*/
1214
1215/*!
1216 \fn void QStandardItem::setStatusTip(const QString &statusTip)
1217
1218 Sets the item's status tip to the string specified by \a statusTip.
1219
1220 \sa statusTip(), setToolTip(), setWhatsThis()
1221*/
1222
1223/*!
1224 \fn QString QStandardItem::toolTip() const
1225
1226 Returns the item's tooltip.
1227
1228 \sa setToolTip(), statusTip(), whatsThis()
1229*/
1230
1231/*!
1232 \fn void QStandardItem::setToolTip(const QString &toolTip)
1233
1234 Sets the item's tooltip to the string specified by \a toolTip.
1235
1236 \sa toolTip(), setStatusTip(), setWhatsThis()
1237*/
1238
1239/*!
1240 \fn QString QStandardItem::whatsThis() const
1241
1242 Returns the item's "What's This?" help.
1243
1244 \sa setWhatsThis(), toolTip(), statusTip()
1245*/
1246
1247/*!
1248 \fn void QStandardItem::setWhatsThis(const QString &whatsThis)
1249
1250 Sets the item's "What's This?" help to the string specified by \a whatsThis.
1251
1252 \sa whatsThis(), setStatusTip(), setToolTip()
1253*/
1254
1255/*!
1256 \fn QFont QStandardItem::font() const
1257
1258 Returns the font used to render the item's text.
1259
1260 \sa setFont()
1261*/
1262
1263/*!
1264 \fn void QStandardItem::setFont(const QFont &font)
1265
1266 Sets the font used to display the item's text to the given \a font.
1267
1268 \sa font(), setText(), setForeground()
1269*/
1270
1271/*!
1272 \fn QBrush QStandardItem::background() const
1273
1274 Returns the brush used to render the item's background.
1275
1276 \sa foreground(), setBackground()
1277*/
1278
1279/*!
1280 \fn void QStandardItem::setBackground(const QBrush &brush)
1281
1282 Sets the item's background brush to the specified \a brush.
1283
1284 \sa background(), setForeground()
1285*/
1286
1287/*!
1288 \fn QBrush QStandardItem::foreground() const
1289
1290 Returns the brush used to render the item's foreground (e.g. text).
1291
1292 \sa setForeground(), background()
1293*/
1294
1295/*!
1296 \fn void QStandardItem::setForeground(const QBrush &brush)
1297
1298 Sets the brush used to display the item's foreground (e.g. text) to the
1299 given \a brush.
1300
1301 \sa foreground(), setBackground(), setFont()
1302*/
1303
1304/*!
1305 \fn int QStandardItem::textAlignment() const
1306
1307 Returns the text alignment for the item's text.
1308*/
1309
1310/*!
1311 \fn void QStandardItem::setTextAlignment(Qt::Alignment alignment)
1312
1313 Sets the text alignment for the item's text to the \a alignment
1314 specified.
1315
1316 \sa textAlignment()
1317*/
1318
1319/*!
1320 \fn QSize QStandardItem::sizeHint() const
1321
1322 Returns the size hint set for the item, or an invalid QSize if no
1323 size hint has been set.
1324
1325 If no size hint has been set, the item delegate will compute the
1326 size hint based on the item data.
1327
1328 \sa setSizeHint()
1329*/
1330
1331/*!
1332 \fn void QStandardItem::setSizeHint(const QSize &size)
1333
1334 Sets the size hint for the item to be \a size.
1335 If no size hint is set, the item delegate will compute the
1336 size hint based on the item data.
1337
1338 \sa sizeHint()
1339*/
1340
1341/*!
1342 \fn Qt::CheckState QStandardItem::checkState() const
1343
1344 Returns the checked state of the item.
1345
1346 \sa setCheckState(), isCheckable()
1347*/
1348
1349/*!
1350 \fn void QStandardItem::setCheckState(Qt::CheckState state)
1351
1352 Sets the check state of the item to be \a state.
1353
1354 \sa checkState(), setCheckable()
1355*/
1356
1357/*!
1358 \fn QString QStandardItem::accessibleText() const
1359
1360 Returns the item's accessible text.
1361
1362 The accessible text is used by assistive technologies (i.e. for users who
1363 cannot use conventional means of interaction).
1364
1365 \sa setAccessibleText(), accessibleDescription()
1366*/
1367
1368/*!
1369 \fn void QStandardItem::setAccessibleText(const QString &accessibleText)
1370
1371 Sets the item's accessible text to the string specified by \a accessibleText.
1372
1373 The accessible text is used by assistive technologies (i.e. for users who
1374 cannot use conventional means of interaction).
1375
1376 \sa accessibleText(), setAccessibleDescription()
1377*/
1378
1379/*!
1380 \fn QString QStandardItem::accessibleDescription() const
1381
1382 Returns the item's accessible description.
1383
1384 The accessible description is used by assistive technologies (i.e. for
1385 users who cannot use conventional means of interaction).
1386
1387 \sa setAccessibleDescription(), accessibleText()
1388*/
1389
1390/*!
1391 \fn void QStandardItem::setAccessibleDescription(const QString &accessibleDescription)
1392
1393 Sets the item's accessible description to the string specified by \a
1394 accessibleDescription.
1395
1396 The accessible description is used by assistive technologies (i.e. for
1397 users who cannot use conventional means of interaction).
1398
1399 \sa accessibleDescription(), setAccessibleText()
1400*/
1401
1402/*!
1403 Sets whether the item is enabled. If \a enabled is true, the item is enabled,
1404 meaning that the user can interact with the item; if \a enabled is false, the
1405 user cannot interact with the item.
1406
1407 This flag takes precedence over the other item flags; e.g. if an item is not
1408 enabled, it cannot be selected by the user, even if the Qt::ItemIsSelectable
1409 flag has been set.
1410
1411 \sa isEnabled(), Qt::ItemIsEnabled, setFlags()
1412*/
1413void QStandardItem::setEnabled(bool enabled)
1414{
1415 Q_D(QStandardItem);
1416 d->changeFlags(enabled, Qt::ItemIsEnabled);
1417}
1418
1419/*!
1420 \fn bool QStandardItem::isEnabled() const
1421
1422 Returns whether the item is enabled.
1423
1424 When an item is enabled, the user can interact with it. The possible
1425 types of interaction are specified by the other item flags, such as
1426 isEditable() and isSelectable().
1427
1428 The default value is true.
1429
1430 \sa setEnabled(), flags()
1431*/
1432
1433/*!
1434 Sets whether the item is editable. If \a editable is true, the item can be
1435 edited by the user; otherwise, the user cannot edit the item.
1436
1437 How the user can edit items in a view is determined by the view's edit
1438 triggers; see QAbstractItemView::editTriggers.
1439
1440 \sa isEditable(), setFlags()
1441*/
1442void QStandardItem::setEditable(bool editable)
1443{
1444 Q_D(QStandardItem);
1445 d->changeFlags(editable, Qt::ItemIsEditable);
1446}
1447
1448/*!
1449 \fn bool QStandardItem::isEditable() const
1450
1451 Returns whether the item can be edited by the user.
1452
1453 When an item is editable (and enabled), the user can edit the item by
1454 invoking one of the view's edit triggers; see
1455 QAbstractItemView::editTriggers.
1456
1457 The default value is true.
1458
1459 \sa setEditable(), flags()
1460*/
1461
1462/*!
1463 Sets whether the item is selectable. If \a selectable is true, the item
1464 can be selected by the user; otherwise, the user cannot select the item.
1465
1466 You can control the selection behavior and mode by manipulating their
1467 view properties; see QAbstractItemView::selectionMode and
1468 QAbstractItemView::selectionBehavior.
1469
1470 \sa isSelectable(), setFlags()
1471*/
1472void QStandardItem::setSelectable(bool selectable)
1473{
1474 Q_D(QStandardItem);
1475 d->changeFlags(selectable, Qt::ItemIsSelectable);
1476}
1477
1478/*!
1479 \fn bool QStandardItem::isSelectable() const
1480
1481 Returns whether the item is selectable by the user.
1482
1483 The default value is true.
1484
1485 \sa setSelectable(), flags()
1486*/
1487
1488/*!
1489 Sets whether the item is user-checkable. If \a checkable is true, the
1490 item can be checked by the user; otherwise, the user cannot check
1491 the item.
1492
1493 The item delegate will render a checkable item with a check box next to the
1494 item's text.
1495
1496 \sa isCheckable(), setCheckState(), setUserTristate(), setAutoTristate()
1497*/
1498void QStandardItem::setCheckable(bool checkable)
1499{
1500 Q_D(QStandardItem);
1501 if (checkable && !isCheckable()) {
1502 // make sure there's data for the checkstate role
1503 if (!data(Qt::CheckStateRole).isValid())
1504 setData(Qt::Unchecked, Qt::CheckStateRole);
1505 }
1506 d->changeFlags(checkable, Qt::ItemIsUserCheckable);
1507}
1508
1509/*!
1510 \fn bool QStandardItem::isCheckable() const
1511
1512 Returns whether the item is user-checkable.
1513
1514 The default value is false.
1515
1516 \sa setCheckable(), checkState(), isUserTristate(), isAutoTristate()
1517*/
1518
1519/*!
1520 Determines that the check state of the item depends on the check state of
1521 its children if \a tristate is \c true: checked if all children are checked,
1522 unchecked if all children are unchecked, or partially checked if only some
1523 children are checked. Setting the item to checked or unchecked sets the
1524 children that have a check state to that state too.
1525
1526 Each child row counts once, through its item in the first column. An item
1527 without children keeps its own check state.
1528
1529 \since 5.6
1530 \sa isAutoTristate(), setCheckable(), setCheckState()
1531*/
1532void QStandardItem::setAutoTristate(bool tristate)
1533{
1534 Q_D(QStandardItem);
1535 d->changeFlags(tristate, Qt::ItemIsAutoTristate);
1536}
1537
1538/*!
1539 \fn bool QStandardItem::isAutoTristate() const
1540
1541 Returns whether the check state of the item depends on the check state of
1542 its children.
1543
1544 The default value is false.
1545
1546 \since 5.6
1547 \sa setAutoTristate(), isCheckable(), checkState()
1548*/
1549
1550/*!
1551 Sets whether the item is tristate and controlled by the user.
1552 If \a tristate is true, the user can cycle through three separate states;
1553 otherwise, the item is checkable with two states.
1554 (Note that this also requires that the item is checkable; see isCheckable().)
1555
1556 \since 5.6
1557 \sa isUserTristate(), setCheckable(), setCheckState()
1558*/
1559void QStandardItem::setUserTristate(bool tristate)
1560{
1561 Q_D(QStandardItem);
1562 d->changeFlags(tristate, Qt::ItemIsUserTristate);
1563}
1564
1565/*!
1566 \fn bool QStandardItem::isUserTristate() const
1567 \since 5.6
1568
1569 Returns whether the item is tristate; that is, if it's checkable with three
1570 separate states and the user can cycle through all three states.
1571
1572 The default value is false.
1573
1574 \sa setUserTristate(), isCheckable(), checkState()
1575*/
1576
1577#if QT_CONFIG(draganddrop)
1578
1579/*!
1580 Sets whether the item is drag enabled. If \a dragEnabled is true, the item
1581 can be dragged by the user; otherwise, the user cannot drag the item.
1582
1583 Note that you also need to ensure that item dragging is enabled in the view;
1584 see QAbstractItemView::dragEnabled.
1585
1586 \sa isDragEnabled(), setDropEnabled(), setFlags()
1587*/
1588void QStandardItem::setDragEnabled(bool dragEnabled)
1589{
1590 Q_D(QStandardItem);
1591 d->changeFlags(dragEnabled, Qt::ItemIsDragEnabled);
1592}
1593
1594/*!
1595 \fn bool QStandardItem::isDragEnabled() const
1596
1597 Returns whether the item is drag enabled. An item that is drag enabled can
1598 be dragged by the user.
1599
1600 The default value is true.
1601
1602 Note that item dragging must be enabled in the view for dragging to work;
1603 see QAbstractItemView::dragEnabled.
1604
1605 \sa setDragEnabled(), isDropEnabled(), flags()
1606*/
1607
1608/*!
1609 Sets whether the item is drop enabled. If \a dropEnabled is true, the item
1610 can be used as a drop target; otherwise, it cannot.
1611
1612 Note that you also need to ensure that drops are enabled in the view; see
1613 QWidget::acceptDrops(); and that the model supports the desired drop actions;
1614 see QAbstractItemModel::supportedDropActions().
1615
1616 \sa isDropEnabled(), setDragEnabled(), setFlags()
1617*/
1618void QStandardItem::setDropEnabled(bool dropEnabled)
1619{
1620 Q_D(QStandardItem);
1621 d->changeFlags(dropEnabled, Qt::ItemIsDropEnabled);
1622}
1623
1624/*!
1625 \fn bool QStandardItem::isDropEnabled() const
1626
1627 Returns whether the item is drop enabled. When an item is drop enabled, it
1628 can be used as a drop target.
1629
1630 The default value is true.
1631
1632 \sa setDropEnabled(), isDragEnabled(), flags()
1633*/
1634
1635#endif // QT_CONFIG(draganddrop)
1636
1637/*!
1638 Returns the row where the item is located in its parent's child table, or
1639 -1 if the item has no parent.
1640
1641 \sa column(), parent()
1642*/
1643int QStandardItem::row() const
1644{
1645 Q_D(const QStandardItem);
1646 std::pair<int, int> pos = d->position();
1647 return pos.first;
1648}
1649
1650/*!
1651 Returns the column where the item is located in its parent's child table,
1652 or -1 if the item has no parent.
1653
1654 \sa row(), parent()
1655*/
1656int QStandardItem::column() const
1657{
1658 Q_D(const QStandardItem);
1659 std::pair<int, int> pos = d->position();
1660 return pos.second;
1661}
1662
1663/*!
1664 Returns the QModelIndex associated with this item.
1665
1666 When you need to invoke item functionality in a QModelIndex-based API (e.g.
1667 QAbstractItemView), you can call this function to obtain an index that
1668 corresponds to the item's location in the model.
1669
1670 If the item is not associated with a model, an invalid QModelIndex is
1671 returned.
1672
1673 \sa model(), QStandardItemModel::itemFromIndex()
1674*/
1675QModelIndex QStandardItem::index() const
1676{
1677 Q_D(const QStandardItem);
1678 return d->model ? d->model->indexFromItem(this) : QModelIndex();
1679}
1680
1681/*!
1682 Returns the QStandardItemModel that this item belongs to.
1683
1684 If the item is not a child of another item that belongs to the model, this
1685 function returns \nullptr.
1686
1687 \sa index()
1688*/
1689QStandardItemModel *QStandardItem::model() const
1690{
1691 Q_D(const QStandardItem);
1692 return d->model;
1693}
1694
1695/*!
1696 Sets the number of child item rows to \a rows. If this is less than
1697 rowCount(), the data in the unwanted rows is discarded.
1698
1699 \sa rowCount(), setColumnCount()
1700*/
1701void QStandardItem::setRowCount(int rows)
1702{
1703 int rc = rowCount();
1704 if (rc == rows)
1705 return;
1706 if (rc < rows)
1707 insertRows(qMax(rc, 0), rows - rc);
1708 else
1709 removeRows(qMax(rows, 0), rc - rows);
1710}
1711
1712/*!
1713 Returns the number of child item rows that the item has.
1714
1715 \sa setRowCount(), columnCount()
1716*/
1717int QStandardItem::rowCount() const
1718{
1719 Q_D(const QStandardItem);
1720 return d->rowCount();
1721}
1722
1723/*!
1724 Sets the number of child item columns to \a columns. If this is less than
1725 columnCount(), the data in the unwanted columns is discarded.
1726
1727 \sa columnCount(), setRowCount()
1728*/
1729void QStandardItem::setColumnCount(int columns)
1730{
1731 int cc = columnCount();
1732 if (cc == columns)
1733 return;
1734 if (cc < columns)
1735 insertColumns(qMax(cc, 0), columns - cc);
1736 else
1737 removeColumns(qMax(columns, 0), cc - columns);
1738}
1739
1740/*!
1741 Returns the number of child item columns that the item has.
1742
1743 \sa setColumnCount(), rowCount()
1744*/
1745int QStandardItem::columnCount() const
1746{
1747 Q_D(const QStandardItem);
1748 return d->columnCount();
1749}
1750
1751/*!
1752 Inserts a row at \a row containing \a items. If necessary, the column
1753 count is increased to the size of \a items.
1754
1755 \sa insertRows(), insertColumn()
1756*/
1757void QStandardItem::insertRow(int row, const QList<QStandardItem*> &items)
1758{
1759 Q_D(QStandardItem);
1760 if (row < 0)
1761 return;
1762 if (columnCount() < items.size())
1763 setColumnCount(items.size());
1764 d->insertRows(row, 1, items);
1765}
1766
1767/*!
1768 Inserts \a items at \a row. The column count won't be changed.
1769
1770 \sa insertRow(), insertColumn()
1771*/
1772void QStandardItem::insertRows(int row, const QList<QStandardItem*> &items)
1773{
1774 Q_D(QStandardItem);
1775 if (row < 0)
1776 return;
1777 d->insertRows(row, items);
1778}
1779
1780/*!
1781 Inserts a column at \a column containing \a items. If necessary,
1782 the row count is increased to the size of \a items.
1783
1784 \sa insertColumns(), insertRow()
1785*/
1786void QStandardItem::insertColumn(int column, const QList<QStandardItem*> &items)
1787{
1788 Q_D(QStandardItem);
1789 if (column < 0)
1790 return;
1791 if (rowCount() < items.size())
1792 setRowCount(items.size());
1793 d->insertColumns(column, 1, items);
1794}
1795
1796/*!
1797 Inserts \a count rows of child items at row \a row.
1798
1799 \sa insertRow(), insertColumns()
1800*/
1801void QStandardItem::insertRows(int row, int count)
1802{
1803 Q_D(QStandardItem);
1804 if (rowCount() < row) {
1805 count += row - rowCount();
1806 row = rowCount();
1807 }
1808 d->insertRows(row, count, QList<QStandardItem*>());
1809}
1810
1811/*!
1812 Inserts \a count columns of child items at column \a column.
1813
1814 \sa insertColumn(), insertRows()
1815*/
1816void QStandardItem::insertColumns(int column, int count)
1817{
1818 Q_D(QStandardItem);
1819 if (columnCount() < column) {
1820 count += column - columnCount();
1821 column = columnCount();
1822 }
1823 d->insertColumns(column, count, QList<QStandardItem*>());
1824}
1825
1826/*!
1827 \fn void QStandardItem::appendRow(const QList<QStandardItem*> &items)
1828
1829 Appends a row containing \a items. If necessary, the column count is
1830 increased to the size of \a items.
1831
1832 \sa insertRow()
1833*/
1834
1835/*!
1836 \fn void QStandardItem::appendRows(const QList<QStandardItem*> &items)
1837
1838 Appends rows containing \a items. The column count will not change.
1839
1840 \sa insertRow()
1841*/
1842
1843/*!
1844 \fn void QStandardItem::appendColumn(const QList<QStandardItem*> &items)
1845
1846 Appends a column containing \a items. If necessary, the row count is
1847 increased to the size of \a items.
1848
1849 \sa insertColumn()
1850*/
1851
1852/*!
1853 \fn bool QStandardItemModel::insertRow(int row, const QModelIndex &parent)
1854
1855 Inserts a single row before the given \a row in the child items of the
1856 \a parent specified. Returns \c true if the row is inserted; otherwise
1857 returns \c false.
1858
1859 \sa insertRows(), insertColumn(), removeRow()
1860*/
1861
1862/*!
1863 \fn bool QStandardItemModel::insertColumn(int column, const QModelIndex &parent)
1864
1865 Inserts a single column before the given \a column in the child items of
1866 the \a parent specified. Returns \c true if the column is inserted; otherwise
1867 returns \c false.
1868
1869 \sa insertColumns(), insertRow(), removeColumn()
1870*/
1871
1872/*!
1873 \fn QStandardItem::insertRow(int row, QStandardItem *item)
1874 \overload
1875
1876 Inserts a row at \a row containing \a item.
1877
1878 When building a list or a tree that has only one column, this function
1879 provides a convenient way to insert a single new item.
1880*/
1881
1882/*!
1883 \fn QStandardItem::appendRow(QStandardItem *item)
1884 \overload
1885
1886 Appends a row containing \a item.
1887
1888 When building a list or a tree that has only one column, this function
1889 provides a convenient way to append a single new item.
1890*/
1891
1892/*!
1893 Removes the given \a row. The items that were in the row are deleted.
1894
1895 \sa takeRow(), removeRows(), removeColumn()
1896*/
1897void QStandardItem::removeRow(int row)
1898{
1899 removeRows(row, 1);
1900}
1901
1902/*!
1903 Removes the given \a column. The items that were in the
1904 column are deleted.
1905
1906 \sa takeColumn(), removeColumns(), removeRow()
1907*/
1908void QStandardItem::removeColumn(int column)
1909{
1910 removeColumns(column, 1);
1911}
1912
1913/*!
1914 Removes \a count rows at row \a row. The items that were in those rows are
1915 deleted.
1916
1917 \sa removeRow(), removeColumn()
1918*/
1919void QStandardItem::removeRows(int row, int count)
1920{
1921 Q_D(QStandardItem);
1922 if ((count < 1) || (row < 0) || ((row + count) > rowCount()))
1923 return;
1924 if (d->model)
1925 d->model->d_func()->rowsAboutToBeRemoved(this, row, row + count - 1);
1926 int i = d->childIndex(row, 0);
1927 int n = count * d->columnCount();
1928 for (int j = i; j < n+i; ++j) {
1929 QStandardItem *oldItem = d->children.at(j);
1930 if (oldItem)
1931 oldItem->d_func()->setModel(nullptr);
1932 delete oldItem;
1933 }
1934 d->children.remove(qMax(i, 0), n);
1935 d->rows -= count;
1936 if (d->model)
1937 d->model->d_func()->rowsRemoved(this, row, count);
1938}
1939
1940/*!
1941 Removes \a count columns at column \a column. The items that were in those
1942 columns are deleted.
1943
1944 \sa removeColumn(), removeRows()
1945*/
1946void QStandardItem::removeColumns(int column, int count)
1947{
1948 Q_D(QStandardItem);
1949 if ((count < 1) || (column < 0) || ((column + count) > columnCount()))
1950 return;
1951 if (d->model)
1952 d->model->d_func()->columnsAboutToBeRemoved(this, column, column + count - 1);
1953 for (int row = d->rowCount() - 1; row >= 0; --row) {
1954 int i = d->childIndex(row, column);
1955 for (int j=i; j<i+count; ++j) {
1956 QStandardItem *oldItem = d->children.at(j);
1957 if (oldItem)
1958 oldItem->d_func()->setModel(nullptr);
1959 delete oldItem;
1960 }
1961 d->children.remove(i, count);
1962 }
1963 d->columns -= count;
1964 if (d->model)
1965 d->model->d_func()->columnsRemoved(this, column, count);
1966}
1967
1968/*!
1969 Returns \c true if this item has any children; otherwise returns \c false.
1970
1971 \sa rowCount(), columnCount(), child()
1972*/
1973bool QStandardItem::hasChildren() const
1974{
1975 return (rowCount() > 0) && (columnCount() > 0);
1976}
1977
1978/*!
1979 Sets the child item at (\a row, \a column) to \a item. This item (the parent
1980 item) takes ownership of \a item. If necessary, the row count and column
1981 count are increased to fit the item.
1982
1983 \note Passing \nullptr as \a item removes the item.
1984
1985 \sa child()
1986*/
1987void QStandardItem::setChild(int row, int column, QStandardItem *item)
1988{
1989 Q_D(QStandardItem);
1990 d->setChild(row, column, item, true);
1991}
1992
1993/*!
1994 \fn QStandardItem::setChild(int row, QStandardItem *item)
1995 \overload
1996
1997 Sets the child at \a row to \a item.
1998*/
1999
2000/*!
2001 Returns the child item at (\a row, \a column) if one has been set; otherwise
2002 returns \nullptr.
2003
2004 \sa setChild(), takeChild(), parent()
2005*/
2006QStandardItem *QStandardItem::child(int row, int column) const
2007{
2008 Q_D(const QStandardItem);
2009 int index = d->childIndex(row, column);
2010 if (index == -1)
2011 return nullptr;
2012 return d->children.at(index);
2013}
2014
2015/*!
2016 Removes the child item at (\a row, \a column) without deleting it, and returns
2017 a pointer to the item. If there was no child at the given location, then
2018 this function returns \nullptr.
2019
2020 Note that this function, unlike takeRow() and takeColumn(), does not affect
2021 the dimensions of the child table.
2022
2023 \sa child(), takeRow(), takeColumn()
2024*/
2025QStandardItem *QStandardItem::takeChild(int row, int column)
2026{
2027 Q_D(QStandardItem);
2028 QStandardItem *item = nullptr;
2029 int index = d->childIndex(row, column);
2030 if (index != -1) {
2031 QModelIndex changedIdx;
2032 item = d->children.at(index);
2033 if (item) {
2034 QStandardItemPrivate *const item_d = item->d_func();
2035 if (d->model) {
2036 QStandardItemModelPrivate *const model_d = d->model->d_func();
2037 const int savedRows = item_d->rows;
2038 const int savedCols = item_d->columns;
2039 const QVector<QStandardItem*> savedChildren = item_d->children;
2040 if (savedRows > 0) {
2041 model_d->rowsAboutToBeRemoved(item, 0, savedRows - 1);
2042 item_d->rows = 0;
2043 item_d->children = QVector<QStandardItem*>(); //slightly faster than clear
2044 // Not rowsRemoved(): the children come back right below
2045 d->model->endRemoveRows();
2046 }
2047 if (savedCols > 0) {
2048 model_d->columnsAboutToBeRemoved(item, 0, savedCols - 1);
2049 item_d->columns = 0;
2050 item_d->children = QVector<QStandardItem*>(); //slightly faster than clear
2051 d->model->endRemoveColumns();
2052 }
2053 item_d->rows = savedRows;
2054 item_d->columns = savedCols;
2055 item_d->children = savedChildren;
2056 changedIdx = d->model->indexFromItem(item);
2057 }
2058 item_d->setParentAndModel(nullptr, nullptr);
2059 }
2060 d->children.replace(index, nullptr);
2061 if (changedIdx.isValid())
2062 d->model->dataChanged(changedIdx, changedIdx);
2063 if (item && column == 0)
2064 d->notifyChildrenChanged();
2065 }
2066 return item;
2067}
2068
2069/*!
2070 Removes \a row without deleting the row items, and returns a list of
2071 pointers to the removed items. For items in the row that have not been
2072 set, the corresponding pointers in the list will be \nullptr.
2073
2074 \sa removeRow(), insertRow(), takeColumn()
2075*/
2076QList<QStandardItem*> QStandardItem::takeRow(int row)
2077{
2078 Q_D(QStandardItem);
2079 QList<QStandardItem*> items;
2080 if ((row < 0) || (row >= rowCount()))
2081 return items;
2082 if (d->model)
2083 d->model->d_func()->rowsAboutToBeRemoved(this, row, row);
2084
2085 int index = d->childIndex(row, 0); // Will return -1 if there are no columns
2086 if (index != -1) {
2087 int col_count = d->columnCount();
2088 items.reserve(col_count);
2089 for (int column = 0; column < col_count; ++column) {
2090 QStandardItem *ch = d->children.at(index + column);
2091 if (ch)
2092 ch->d_func()->setParentAndModel(nullptr, nullptr);
2093 items.append(ch);
2094 }
2095 d->children.remove(index, col_count);
2096 }
2097 d->rows--;
2098 if (d->model)
2099 d->model->d_func()->rowsRemoved(this, row, 1);
2100 return items;
2101}
2102
2103/*!
2104 Removes \a column without deleting the column items, and returns a list of
2105 pointers to the removed items. For items in the column that have not been
2106 set, the corresponding pointers in the list will be \nullptr.
2107
2108 \sa removeColumn(), insertColumn(), takeRow()
2109*/
2110QList<QStandardItem*> QStandardItem::takeColumn(int column)
2111{
2112 Q_D(QStandardItem);
2113 QList<QStandardItem*> items;
2114 if ((column < 0) || (column >= columnCount()))
2115 return items;
2116 if (d->model)
2117 d->model->d_func()->columnsAboutToBeRemoved(this, column, column);
2118
2119 const int rowCount = d->rowCount();
2120 items.reserve(rowCount);
2121 for (int row = rowCount - 1; row >= 0; --row) {
2122 int index = d->childIndex(row, column);
2123 QStandardItem *ch = d->children.at(index);
2124 if (ch)
2125 ch->d_func()->setParentAndModel(nullptr, nullptr);
2126 d->children.remove(index);
2127 items.prepend(ch);
2128 }
2129 d->columns--;
2130 if (d->model)
2131 d->model->d_func()->columnsRemoved(this, column, 1);
2132 return items;
2133}
2134
2135/*!
2136 Returns \c true if this item is less than \a other; otherwise returns \c false.
2137
2138 The default implementation uses the data for the item's sort role (see
2139 QStandardItemModel::sortRole) to perform the comparison if the item
2140 belongs to a model; otherwise, the data for the item's Qt::DisplayRole
2141 (text()) is used to perform the comparison.
2142
2143 sortChildren() and QStandardItemModel::sort() use this function when
2144 sorting items. If you want custom sorting, you can subclass QStandardItem
2145 and reimplement this function.
2146*/
2147bool QStandardItem::operator<(const QStandardItem &other) const
2148{
2149 const int role = model() ? model()->sortRole() : Qt::DisplayRole;
2150 const QVariant l = data(role), r = other.data(role);
2151 return QStandardItemModel::compareData(l, r) < 0;
2152}
2153
2154/*!
2155 Sorts the children of the item using the given \a order, by the values in
2156 the given \a column.
2157
2158 \note This function is recursive, therefore it sorts the children of the
2159 item, its grandchildren, etc.
2160
2161 \sa {operator<()}
2162*/
2163void QStandardItem::sortChildren(int column, Qt::SortOrder order)
2164{
2165 Q_D(QStandardItem);
2166 if ((column < 0) || (rowCount() == 0))
2167 return;
2168
2169 QList<QPersistentModelIndex> parents;
2170 if (d->model) {
2171 parents << index();
2172 emit d->model->layoutAboutToBeChanged(parents, QAbstractItemModel::VerticalSortHint);
2173 }
2174 d->sortChildren(column, order);
2175 if (d->model)
2176 emit d->model->layoutChanged(parents, QAbstractItemModel::VerticalSortHint);
2177}
2178
2179/*!
2180 Returns a copy of this item. The item's children are not copied.
2181
2182 When subclassing QStandardItem, you can reimplement this function
2183 to provide QStandardItemModel with a factory that it can use to
2184 create new items on demand.
2185
2186 \sa QStandardItemModel::setItemPrototype(), operator=()
2187*/
2188QStandardItem *QStandardItem::clone() const
2189{
2190 return new QStandardItem(*this);
2191}
2192
2193/*!
2194 Returns the type of this item. The type is used to distinguish custom
2195 items from the base class. When subclassing QStandardItem, you should
2196 reimplement this function and return a new value greater than or equal
2197 to \l UserType.
2198
2199 \sa QStandardItem::Type
2200*/
2201int QStandardItem::type() const
2202{
2203 return Type;
2204}
2205
2206#ifndef QT_NO_DATASTREAM
2207
2208/*!
2209 Reads the item from stream \a in. Only the data and flags of the item are
2210 read, not the child items.
2211
2212 \sa write()
2213*/
2214void QStandardItem::read(QDataStream &in)
2215{
2216 Q_D(QStandardItem);
2217 in >> d->values;
2218 qint32 flags;
2219 in >> flags;
2220 setFlags(Qt::ItemFlags(flags));
2221}
2222
2223/*!
2224 Writes the item to stream \a out. Only the data and flags of the item
2225 are written, not the child items.
2226
2227 \sa read()
2228*/
2229void QStandardItem::write(QDataStream &out) const
2230{
2231 Q_D(const QStandardItem);
2232 out << d->values;
2233 out << flags();
2234}
2235
2236/*!
2237 \relates QStandardItem
2238 \since 4.2
2239
2240 Reads a QStandardItem from stream \a in into \a item.
2241
2242 This operator uses QStandardItem::read().
2243
2244 \sa {Serializing Qt Data Types}
2245*/
2246QDataStream &operator>>(QDataStream &in, QStandardItem &item)
2247{
2248 item.read(in);
2249 return in;
2250}
2251
2252/*!
2253 \relates QStandardItem
2254 \since 4.2
2255
2256 Writes the QStandardItem \a item to stream \a out.
2257
2258 This operator uses QStandardItem::write().
2259
2260 \sa {Serializing Qt Data Types}
2261*/
2262QDataStream &operator<<(QDataStream &out, const QStandardItem &item)
2263{
2264 item.write(out);
2265 return out;
2266}
2267
2268#endif // QT_NO_DATASTREAM
2269
2270/*!
2271 \class QStandardItemModel
2272 \brief The QStandardItemModel class provides a generic model for storing custom data.
2273 \ingroup model-view
2274 \inmodule QtGui
2275
2276 QStandardItemModel can be used as a repository for standard Qt
2277 data types. It is one of the \l {Model/View Classes} and is part
2278 of Qt's \l {Model/View Programming}{model/view} framework.
2279
2280 QStandardItemModel provides a classic item-based approach to working with
2281 the model. The items in a QStandardItemModel are provided by
2282 QStandardItem.
2283
2284 QStandardItemModel implements the QAbstractItemModel interface, which
2285 means that the model can be used to provide data in any view that supports
2286 that interface (such as QListView, QTableView and QTreeView, and your own
2287 custom views). For performance and flexibility, you may want to subclass
2288 QAbstractItemModel to provide support for different kinds of data
2289 repositories. For example, the QFileSystemModel provides a model interface
2290 to the underlying file system.
2291
2292 When you want a list or tree, you typically create an empty
2293 QStandardItemModel and use appendRow() to add items to the model, and
2294 item() to access an item. If your model represents a table, you typically
2295 pass the dimensions of the table to the QStandardItemModel constructor and
2296 use setItem() to position items into the table. You can also use setRowCount()
2297 and setColumnCount() to alter the dimensions of the model. To insert items,
2298 use insertRow() or insertColumn(), and to remove items, use removeRow() or
2299 removeColumn().
2300
2301 You can set the header labels of your model with setHorizontalHeaderLabels()
2302 and setVerticalHeaderLabels().
2303
2304 You can search for items in the model with findItems(), and sort the model by
2305 calling sort().
2306
2307 Call clear() to remove all items from the model.
2308
2309 An example usage of QStandardItemModel to create a table:
2310
2311 \snippet code/src_gui_itemviews_qstandarditemmodel.cpp 0
2312
2313 An example usage of QStandardItemModel to create a tree:
2314
2315 \snippet code/src_gui_itemviews_qstandarditemmodel.cpp 1
2316
2317 After setting the model on a view, you typically want to react to user
2318 actions, such as an item being clicked. Since a QAbstractItemView provides
2319 QModelIndex-based signals and functions, you need a way to obtain the
2320 QStandardItem that corresponds to a given QModelIndex, and vice
2321 versa. itemFromIndex() and indexFromItem() provide this mapping. Typical
2322 usage of itemFromIndex() includes obtaining the item at the current index
2323 in a view, and obtaining the item that corresponds to an index carried by
2324 a QAbstractItemView signal, such as QAbstractItemView::clicked(). First
2325 you connect the view's signal to a slot in your class:
2326
2327 \snippet code/src_gui_itemviews_qstandarditemmodel.cpp 2
2328
2329 When you receive the signal, you call itemFromIndex() on the given model
2330 index to get a pointer to the item:
2331
2332 \snippet code/src_gui_itemviews_qstandarditemmodel.cpp 3
2333
2334 Conversely, you must obtain the QModelIndex of an item when you want to
2335 invoke a model/view function that takes an index as argument. You can
2336 obtain the index either by using the model's indexFromItem() function, or,
2337 equivalently, by calling QStandardItem::index():
2338
2339 \snippet code/src_gui_itemviews_qstandarditemmodel.cpp 4
2340
2341 You are, of course, not required to use the item-based approach; you could
2342 instead rely entirely on the QAbstractItemModel interface when working with
2343 the model, or use a combination of the two as appropriate.
2344
2345 \sa QStandardItem, {Model/View Programming}, QAbstractItemModel, QRangeModel,
2346 {itemviews/simpletreemodel}{Simple Tree Model example},
2347 {Item View Convenience Classes}
2348*/
2349
2350/*!
2351 \fn void QStandardItemModel::itemChanged(QStandardItem *item)
2352 \since 4.2
2353
2354 This signal is emitted whenever the data of \a item has changed.
2355*/
2356
2357/*!
2358 Constructs a new item model with the given \a parent.
2359*/
2360QStandardItemModel::QStandardItemModel(QObject *parent)
2361 : QAbstractItemModel(*new QStandardItemModelPrivate, parent)
2362{
2363 Q_D(QStandardItemModel);
2364 d->init();
2365 d->root->d_func()->setModel(this);
2366}
2367
2368/*!
2369 Constructs a new item model that initially has \a rows rows and \a columns
2370 columns, and that has the given \a parent.
2371*/
2372QStandardItemModel::QStandardItemModel(int rows, int columns, QObject *parent)
2373 : QAbstractItemModel(*new QStandardItemModelPrivate, parent)
2374{
2375 Q_D(QStandardItemModel);
2376 d->init();
2377 d->root->insertColumns(0, columns);
2378 d->columnHeaderItems.insert(0, columns, nullptr);
2379 d->root->insertRows(0, rows);
2380 d->rowHeaderItems.insert(0, rows, nullptr);
2381 d->root->d_func()->setModel(this);
2382}
2383
2384/*!
2385 \internal
2386*/
2387QStandardItemModel::QStandardItemModel(QStandardItemModelPrivate &dd, QObject *parent)
2388 : QAbstractItemModel(dd, parent)
2389{
2390 Q_D(QStandardItemModel);
2391 d->init();
2392}
2393
2394/*!
2395 Destructs the model. The model destroys all its items.
2396*/
2397QStandardItemModel::~QStandardItemModel()
2398{
2399 Q_D(QStandardItemModel);
2400 delete d->itemPrototype;
2401 qDeleteAll(d->columnHeaderItems);
2402 qDeleteAll(d->rowHeaderItems);
2403 d->root.reset();
2404}
2405
2406/*!
2407 Sets the item role names to \a roleNames.
2408*/
2409void QStandardItemModel::setItemRoleNames(const QHash<int,QByteArray> &roleNames)
2410{
2411 Q_D(QStandardItemModel);
2412 d->roleNames = roleNames;
2413}
2414
2415/*!
2416 \reimp
2417*/
2418QHash<int, QByteArray> QStandardItemModel::roleNames() const
2419{
2420 Q_D(const QStandardItemModel);
2421 return d->roleNames;
2422}
2423
2424/*!
2425 Removes all items (including header items) from the model and sets the
2426 number of rows and columns to zero.
2427
2428 \sa removeColumns(), removeRows()
2429*/
2430void QStandardItemModel::clear()
2431{
2432 Q_D(QStandardItemModel);
2433 beginResetModel();
2434 d->root.reset(new QStandardItem);
2435 d->root->setFlags(Qt::ItemIsDropEnabled);
2436 d->root->d_func()->setModel(this);
2437 qDeleteAll(d->columnHeaderItems);
2438 d->columnHeaderItems.clear();
2439 qDeleteAll(d->rowHeaderItems);
2440 d->rowHeaderItems.clear();
2441 endResetModel();
2442}
2443
2444/*!
2445 \since 4.2
2446
2447 Returns a pointer to the QStandardItem associated with the given \a index.
2448
2449 Calling this function is typically the initial step when processing
2450 QModelIndex-based signals from a view, such as
2451 QAbstractItemView::activated(). In your slot, you call itemFromIndex(),
2452 with the QModelIndex carried by the signal as argument, to obtain a
2453 pointer to the corresponding QStandardItem.
2454
2455 Note that this function will lazily create an item for the index (using
2456 itemPrototype()), and set it in the parent item's child table, if no item
2457 already exists at that index.
2458
2459 If \a index is an invalid index, this function returns \nullptr.
2460
2461 \sa indexFromItem()
2462*/
2463QStandardItem *QStandardItemModel::itemFromIndex(const QModelIndex &index) const
2464{
2465 Q_D(const QStandardItemModel);
2466 if ((index.row() < 0) || (index.column() < 0) || (index.model() != this))
2467 return nullptr;
2468 QStandardItem *parent = static_cast<QStandardItem*>(index.internalPointer());
2469 if (parent == nullptr)
2470 return nullptr;
2471 QStandardItem *item = parent->child(index.row(), index.column());
2472 // lazy part
2473 if (item == nullptr) {
2474 item = d->createItem();
2475 parent->d_func()->setChild(index.row(), index.column(), item);
2476 }
2477 return item;
2478}
2479
2480/*!
2481 \since 4.2
2482
2483 Returns the QModelIndex associated with the given \a item.
2484
2485 Use this function when you want to perform an operation that requires the
2486 QModelIndex of the item, such as
2487 QAbstractItemView::scrollTo(). QStandardItem::index() is provided as
2488 convenience; it is equivalent to calling this function.
2489
2490 \sa itemFromIndex(), QStandardItem::index()
2491*/
2492QModelIndex QStandardItemModel::indexFromItem(const QStandardItem *item) const
2493{
2494 if (item && item->d_func()->parent) {
2495 std::pair<int, int> pos = item->d_func()->position();
2496 return createIndex(pos.first, pos.second, item->d_func()->parent);
2497 }
2498 return QModelIndex();
2499}
2500
2501/*!
2502 \since 4.2
2503
2504 Sets the number of rows in this model to \a rows. If
2505 this is less than rowCount(), the data in the unwanted rows
2506 is discarded.
2507
2508 \sa setColumnCount()
2509*/
2510void QStandardItemModel::setRowCount(int rows)
2511{
2512 Q_D(QStandardItemModel);
2513 d->root->setRowCount(rows);
2514}
2515
2516/*!
2517 \since 4.2
2518
2519 Sets the number of columns in this model to \a columns. If
2520 this is less than columnCount(), the data in the unwanted columns
2521 is discarded.
2522
2523 \sa setRowCount()
2524*/
2525void QStandardItemModel::setColumnCount(int columns)
2526{
2527 Q_D(QStandardItemModel);
2528 d->root->setColumnCount(columns);
2529}
2530
2531/*!
2532 \since 4.2
2533
2534 Sets the item for the given \a row and \a column to \a item. The model
2535 takes ownership of the item. If necessary, the row count and column count
2536 are increased to fit the item. The previous item at the given location (if
2537 there was one) is deleted.
2538
2539 \sa item()
2540*/
2541void QStandardItemModel::setItem(int row, int column, QStandardItem *item)
2542{
2543 Q_D(QStandardItemModel);
2544 d->root->d_func()->setChild(row, column, item, true);
2545}
2546
2547/*!
2548 \fn QStandardItemModel::setItem(int row, QStandardItem *item)
2549 \overload
2550*/
2551
2552/*!
2553 \since 4.2
2554
2555 Returns the item for the given \a row and \a column if one has been set;
2556 otherwise returns \nullptr.
2557
2558 \sa setItem(), takeItem(), itemFromIndex()
2559*/
2560QStandardItem *QStandardItemModel::item(int row, int column) const
2561{
2562 Q_D(const QStandardItemModel);
2563 return d->root->child(row, column);
2564}
2565
2566/*!
2567 \since 4.2
2568
2569 Returns the model's invisible root item.
2570
2571 The invisible root item provides access to the model's top-level items
2572 through the QStandardItem API, making it possible to write functions that
2573 can treat top-level items and their children in a uniform way; for
2574 example, recursive functions involving a tree model.
2575
2576 \note Calling \l{QAbstractItemModel::index()}{index()} on the QStandardItem object
2577 retrieved from this function is not valid.
2578*/
2579QStandardItem *QStandardItemModel::invisibleRootItem() const
2580{
2581 Q_D(const QStandardItemModel);
2582 return d->root.data();
2583}
2584
2585/*!
2586 \since 4.2
2587
2588 Sets the horizontal header item for \a column to \a item. The model takes
2589 ownership of the item. If necessary, the column count is increased to fit
2590 the item. The previous header item (if there was one) is deleted.
2591
2592 \sa horizontalHeaderItem(), setHorizontalHeaderLabels(),
2593 setVerticalHeaderItem()
2594*/
2595void QStandardItemModel::setHorizontalHeaderItem(int column, QStandardItem *item)
2596{
2597 Q_D(QStandardItemModel);
2598 if (column < 0)
2599 return;
2600 if (columnCount() <= column)
2601 setColumnCount(column + 1);
2602
2603 QStandardItem *oldItem = d->columnHeaderItems.at(column);
2604 if (item == oldItem)
2605 return;
2606
2607 if (item) {
2608 if (item->model() == nullptr) {
2609 item->d_func()->setModel(this);
2610 } else {
2611 qWarning("QStandardItem::setHorizontalHeaderItem: Ignoring duplicate insertion of item %p",
2612 item);
2613 return;
2614 }
2615 }
2616
2617 if (oldItem)
2618 oldItem->d_func()->setModel(nullptr);
2619 delete oldItem;
2620
2621 d->columnHeaderItems.replace(column, item);
2622 emit headerDataChanged(Qt::Horizontal, column, column);
2623}
2624
2625/*!
2626 \since 4.2
2627
2628 Returns the horizontal header item for \a column if one has been set;
2629 otherwise returns \nullptr.
2630
2631 \sa setHorizontalHeaderItem(), verticalHeaderItem()
2632*/
2633QStandardItem *QStandardItemModel::horizontalHeaderItem(int column) const
2634{
2635 Q_D(const QStandardItemModel);
2636 if ((column < 0) || (column >= columnCount()))
2637 return nullptr;
2638 return d->columnHeaderItems.at(column);
2639}
2640
2641/*!
2642 \since 4.2
2643
2644 Sets the vertical header item for \a row to \a item. The model takes
2645 ownership of the item. If necessary, the row count is increased to fit the
2646 item. The previous header item (if there was one) is deleted.
2647
2648 \sa verticalHeaderItem(), setVerticalHeaderLabels(),
2649 setHorizontalHeaderItem()
2650*/
2651void QStandardItemModel::setVerticalHeaderItem(int row, QStandardItem *item)
2652{
2653 Q_D(QStandardItemModel);
2654 if (row < 0)
2655 return;
2656 if (rowCount() <= row)
2657 setRowCount(row + 1);
2658
2659 QStandardItem *oldItem = d->rowHeaderItems.at(row);
2660 if (item == oldItem)
2661 return;
2662
2663 if (item) {
2664 if (item->model() == nullptr) {
2665 item->d_func()->setModel(this);
2666 } else {
2667 qWarning("QStandardItem::setVerticalHeaderItem: Ignoring duplicate insertion of item %p",
2668 item);
2669 return;
2670 }
2671 }
2672
2673 if (oldItem)
2674 oldItem->d_func()->setModel(nullptr);
2675 delete oldItem;
2676
2677 d->rowHeaderItems.replace(row, item);
2678 emit headerDataChanged(Qt::Vertical, row, row);
2679}
2680
2681/*!
2682 \since 4.2
2683
2684 Returns the vertical header item for row \a row if one has been set;
2685 otherwise returns \nullptr.
2686
2687 \sa setVerticalHeaderItem(), horizontalHeaderItem()
2688*/
2689QStandardItem *QStandardItemModel::verticalHeaderItem(int row) const
2690{
2691 Q_D(const QStandardItemModel);
2692 if ((row < 0) || (row >= rowCount()))
2693 return nullptr;
2694 return d->rowHeaderItems.at(row);
2695}
2696
2697/*!
2698 \since 4.2
2699
2700 Sets the horizontal header labels using \a labels. If necessary, the
2701 column count is increased to the size of \a labels.
2702
2703 \sa setHorizontalHeaderItem()
2704*/
2705void QStandardItemModel::setHorizontalHeaderLabels(const QStringList &labels)
2706{
2707 Q_D(QStandardItemModel);
2708 if (columnCount() < labels.size())
2709 setColumnCount(labels.size());
2710 for (int i = 0; i < labels.size(); ++i) {
2711 QStandardItem *item = horizontalHeaderItem(i);
2712 if (!item) {
2713 item = d->createItem();
2714 setHorizontalHeaderItem(i, item);
2715 }
2716 item->setText(labels.at(i));
2717 }
2718}
2719
2720/*!
2721 \since 4.2
2722
2723 Sets the vertical header labels using \a labels. If necessary, the row
2724 count is increased to the size of \a labels.
2725
2726 \sa setVerticalHeaderItem()
2727*/
2728void QStandardItemModel::setVerticalHeaderLabels(const QStringList &labels)
2729{
2730 Q_D(QStandardItemModel);
2731 if (rowCount() < labels.size())
2732 setRowCount(labels.size());
2733 for (int i = 0; i < labels.size(); ++i) {
2734 QStandardItem *item = verticalHeaderItem(i);
2735 if (!item) {
2736 item = d->createItem();
2737 setVerticalHeaderItem(i, item);
2738 }
2739 item->setText(labels.at(i));
2740 }
2741}
2742
2743/*!
2744 \since 4.2
2745
2746 Sets the item prototype for the model to the specified \a item. The model
2747 takes ownership of the prototype.
2748
2749 The item prototype acts as a QStandardItem factory, by relying on the
2750 QStandardItem::clone() function. To provide your own prototype, subclass
2751 QStandardItem, reimplement QStandardItem::clone() and set the prototype to
2752 be an instance of your custom class. Whenever QStandardItemModel needs to
2753 create an item on demand (for instance, when a view or item delegate calls
2754 setData())), the new items will be instances of your custom class.
2755
2756 \sa itemPrototype(), QStandardItem::clone()
2757*/
2758void QStandardItemModel::setItemPrototype(const QStandardItem *item)
2759{
2760 Q_D(QStandardItemModel);
2761 if (d->itemPrototype != item) {
2762 delete d->itemPrototype;
2763 d->itemPrototype = item;
2764 }
2765}
2766
2767/*!
2768 \since 4.2
2769
2770 Returns the item prototype used by the model. The model uses the item
2771 prototype as an item factory when it needs to construct new items on
2772 demand (for instance, when a view or item delegate calls setData()).
2773
2774 \sa setItemPrototype()
2775*/
2776const QStandardItem *QStandardItemModel::itemPrototype() const
2777{
2778 Q_D(const QStandardItemModel);
2779 return d->itemPrototype;
2780}
2781
2782/*!
2783 \since 4.2
2784
2785 Returns a list of items that match the given \a text, using the given \a
2786 flags, in the given \a column.
2787*/
2788QList<QStandardItem*> QStandardItemModel::findItems(const QString &text,
2789 Qt::MatchFlags flags, int column) const
2790{
2791 QModelIndexList indexes = match(index(0, column, QModelIndex()),
2792 Qt::DisplayRole, text, -1, flags);
2793 QList<QStandardItem*> items;
2794 const int numIndexes = indexes.size();
2795 items.reserve(numIndexes);
2796 for (int i = 0; i < numIndexes; ++i)
2797 items.append(itemFromIndex(indexes.at(i)));
2798 return items;
2799}
2800
2801/*!
2802 \since 4.2
2803
2804 Appends a row containing \a items. If necessary, the column count is
2805 increased to the size of \a items.
2806
2807 \sa insertRow(), appendColumn()
2808*/
2809void QStandardItemModel::appendRow(const QList<QStandardItem*> &items)
2810{
2811 invisibleRootItem()->appendRow(items);
2812}
2813
2814/*!
2815 \since 4.2
2816
2817 Appends a column containing \a items. If necessary, the row count is
2818 increased to the size of \a items.
2819
2820 \sa insertColumn(), appendRow()
2821*/
2822void QStandardItemModel::appendColumn(const QList<QStandardItem*> &items)
2823{
2824 invisibleRootItem()->appendColumn(items);
2825}
2826
2827/*!
2828 \since 4.2
2829 \fn QStandardItemModel::appendRow(QStandardItem *item)
2830 \overload
2831
2832 When building a list or a tree that has only one column, this function
2833 provides a convenient way to append a single new \a item.
2834*/
2835
2836/*!
2837 \since 4.2
2838
2839 Inserts a row at \a row containing \a items. If necessary, the column
2840 count is increased to the size of \a items.
2841
2842 \sa takeRow(), appendRow(), insertColumn()
2843*/
2844void QStandardItemModel::insertRow(int row, const QList<QStandardItem*> &items)
2845{
2846 invisibleRootItem()->insertRow(row, items);
2847}
2848
2849/*!
2850 \since 4.2
2851
2852 \fn void QStandardItemModel::insertRow(int row, QStandardItem *item)
2853 \overload
2854
2855 Inserts a row at \a row containing \a item.
2856
2857 When building a list or a tree that has only one column, this function
2858 provides a convenient way to append a single new item.
2859*/
2860
2861/*!
2862 \since 4.2
2863
2864 Inserts a column at \a column containing \a items. If necessary, the row
2865 count is increased to the size of \a items.
2866
2867 \sa takeColumn(), appendColumn(), insertRow()
2868*/
2869void QStandardItemModel::insertColumn(int column, const QList<QStandardItem*> &items)
2870{
2871 invisibleRootItem()->insertColumn(column, items);
2872}
2873
2874/*!
2875 \since 4.2
2876
2877 Removes the item at (\a row, \a column) without deleting it. The model
2878 releases ownership of the item.
2879
2880 \sa item(), takeRow(), takeColumn()
2881*/
2882QStandardItem *QStandardItemModel::takeItem(int row, int column)
2883{
2884 Q_D(QStandardItemModel);
2885 return d->root->takeChild(row, column);
2886}
2887
2888/*!
2889 \since 4.2
2890
2891 Removes the given \a row without deleting the row items, and returns a
2892 list of pointers to the removed items. The model releases ownership of the
2893 items. For items in the row that have not been set, the corresponding
2894 pointers in the list will be \nullptr.
2895
2896 \sa takeColumn()
2897*/
2898QList<QStandardItem*> QStandardItemModel::takeRow(int row)
2899{
2900 Q_D(QStandardItemModel);
2901 return d->root->takeRow(row);
2902}
2903
2904/*!
2905 \since 4.2
2906
2907 Removes the given \a column without deleting the column items, and returns
2908 a list of pointers to the removed items. The model releases ownership of
2909 the items. For items in the column that have not been set, the
2910 corresponding pointers in the list will be \nullptr.
2911
2912 \sa takeRow()
2913*/
2914QList<QStandardItem*> QStandardItemModel::takeColumn(int column)
2915{
2916 Q_D(QStandardItemModel);
2917 return d->root->takeColumn(column);
2918}
2919
2920/*!
2921 \since 4.2
2922
2923 Removes the horizontal header item at \a column from the header without
2924 deleting it, and returns a pointer to the item. The model releases
2925 ownership of the item.
2926
2927 \sa horizontalHeaderItem(), takeVerticalHeaderItem()
2928*/
2929QStandardItem *QStandardItemModel::takeHorizontalHeaderItem(int column)
2930{
2931 Q_D(QStandardItemModel);
2932 if ((column < 0) || (column >= columnCount()))
2933 return nullptr;
2934 QStandardItem *headerItem = d->columnHeaderItems.at(column);
2935 if (headerItem) {
2936 headerItem->d_func()->setParentAndModel(nullptr, nullptr);
2937 d->columnHeaderItems.replace(column, nullptr);
2938 }
2939 return headerItem;
2940}
2941
2942/*!
2943 \since 4.2
2944
2945 Removes the vertical header item at \a row from the header without
2946 deleting it, and returns a pointer to the item. The model releases
2947 ownership of the item.
2948
2949 \sa verticalHeaderItem(), takeHorizontalHeaderItem()
2950*/
2951QStandardItem *QStandardItemModel::takeVerticalHeaderItem(int row)
2952{
2953 Q_D(QStandardItemModel);
2954 if ((row < 0) || (row >= rowCount()))
2955 return nullptr;
2956 QStandardItem *headerItem = d->rowHeaderItems.at(row);
2957 if (headerItem) {
2958 headerItem->d_func()->setParentAndModel(nullptr, nullptr);
2959 d->rowHeaderItems.replace(row, nullptr);
2960 }
2961 return headerItem;
2962}
2963
2964/*!
2965 \since 4.2
2966 \property QStandardItemModel::sortRole
2967 \brief the item role that is used to query the model's data when sorting items
2968
2969 The default value is Qt::DisplayRole.
2970
2971 \sa sort(), QStandardItem::sortChildren()
2972*/
2973int QStandardItemModel::sortRole() const
2974{
2975 Q_D(const QStandardItemModel);
2976 return d->sortRole;
2977}
2978
2979void QStandardItemModel::setSortRole(int role)
2980{
2981 Q_D(QStandardItemModel);
2982 d->sortRole = role;
2983}
2984
2985QBindable<int> QStandardItemModel::bindableSortRole()
2986{
2987 Q_D(QStandardItemModel);
2988 return &d->sortRole;
2989}
2990
2991/*!
2992 \reimp
2993*/
2994int QStandardItemModel::columnCount(const QModelIndex &parent) const
2995{
2996 Q_D(const QStandardItemModel);
2997 QStandardItem *item = d->itemFromIndex(parent);
2998 return item ? item->columnCount() : 0;
2999}
3000
3001/*!
3002 \reimp
3003*/
3004QVariant QStandardItemModel::data(const QModelIndex &index, int role) const
3005{
3006 Q_D(const QStandardItemModel);
3007 QStandardItem *item = d->itemFromIndex(index);
3008 return item ? item->data(role) : QVariant();
3009}
3010
3011/*!
3012 \reimp
3013*/
3014void QStandardItemModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
3015{
3016 // Cannot offer a better implementation; users may be overriding
3017 // data(), and thus multiData() may fall out of sync for them.
3018 // The base class' implementation will simply call data() in a loop,
3019 // so it's fine.
3020 QAbstractItemModel::multiData(index, roleDataSpan);
3021}
3022
3023/*!
3024 \reimp
3025*/
3026Qt::ItemFlags QStandardItemModel::flags(const QModelIndex &index) const
3027{
3028 Q_D(const QStandardItemModel);
3029 if (!d->indexValid(index))
3030 return d->root->flags();
3031 QStandardItem *item = d->itemFromIndex(index);
3032 if (item)
3033 return item->flags();
3034 return Qt::ItemIsSelectable
3035 |Qt::ItemIsEnabled
3036 |Qt::ItemIsEditable
3037 |Qt::ItemIsDragEnabled
3038 |Qt::ItemIsDropEnabled;
3039}
3040
3041/*!
3042 \reimp
3043*/
3044bool QStandardItemModel::hasChildren(const QModelIndex &parent) const
3045{
3046 Q_D(const QStandardItemModel);
3047 QStandardItem *item = d->itemFromIndex(parent);
3048 return item ? item->hasChildren() : false;
3049}
3050
3051/*!
3052 \reimp
3053*/
3054QVariant QStandardItemModel::headerData(int section, Qt::Orientation orientation, int role) const
3055{
3056 Q_D(const QStandardItemModel);
3057 if ((section < 0)
3058 || ((orientation == Qt::Horizontal) && (section >= columnCount()))
3059 || ((orientation == Qt::Vertical) && (section >= rowCount()))) {
3060 return QVariant();
3061 }
3062 QStandardItem *headerItem = nullptr;
3063 if (orientation == Qt::Horizontal)
3064 headerItem = d->columnHeaderItems.at(section);
3065 else if (orientation == Qt::Vertical)
3066 headerItem = d->rowHeaderItems.at(section);
3067 return headerItem ? headerItem->data(role)
3068 : QAbstractItemModel::headerData(section, orientation, role);
3069}
3070
3071/*!
3072 \reimp
3073
3074 QStandardItemModel supports both copy and move.
3075*/
3076Qt::DropActions QStandardItemModel::supportedDropActions () const
3077{
3078 return Qt::CopyAction | Qt::MoveAction;
3079}
3080
3081/*!
3082 \reimp
3083*/
3084QModelIndex QStandardItemModel::index(int row, int column, const QModelIndex &parent) const
3085{
3086 Q_D(const QStandardItemModel);
3087 QStandardItem *parentItem = d->itemFromIndex(parent);
3088 if ((parentItem == nullptr)
3089 || (row < 0)
3090 || (column < 0)
3091 || (row >= parentItem->rowCount())
3092 || (column >= parentItem->columnCount())) {
3093 return QModelIndex();
3094 }
3095 return createIndex(row, column, parentItem);
3096}
3097
3098/*!
3099 \reimp
3100*/
3101bool QStandardItemModel::insertColumns(int column, int count, const QModelIndex &parent)
3102{
3103 Q_D(QStandardItemModel);
3104 QStandardItem *item = parent.isValid() ? itemFromIndex(parent) : d->root.data();
3105 if (item == nullptr)
3106 return false;
3107 return item->d_func()->insertColumns(column, count, QList<QStandardItem*>());
3108}
3109
3110/*!
3111 \reimp
3112*/
3113bool QStandardItemModel::insertRows(int row, int count, const QModelIndex &parent)
3114{
3115 Q_D(QStandardItemModel);
3116 QStandardItem *item = parent.isValid() ? itemFromIndex(parent) : d->root.data();
3117 if (item == nullptr)
3118 return false;
3119 return item->d_func()->insertRows(row, count, QList<QStandardItem*>());
3120}
3121
3122/*!
3123 \reimp
3124*/
3125QMap<int, QVariant> QStandardItemModel::itemData(const QModelIndex &index) const
3126{
3127 Q_D(const QStandardItemModel);
3128 const QStandardItem *const item = d->itemFromIndex(index);
3129 if (!item || item == d->root.data())
3130 return QMap<int, QVariant>();
3131 return item->d_func()->itemData();
3132}
3133
3134/*!
3135 \reimp
3136*/
3137QModelIndex QStandardItemModel::parent(const QModelIndex &child) const
3138{
3139 Q_D(const QStandardItemModel);
3140 if (!d->indexValid(child))
3141 return QModelIndex();
3142 QStandardItem *parentItem = static_cast<QStandardItem*>(child.internalPointer());
3143 return indexFromItem(parentItem);
3144}
3145
3146/*!
3147 \reimp
3148*/
3149bool QStandardItemModel::removeColumns(int column, int count, const QModelIndex &parent)
3150{
3151 Q_D(QStandardItemModel);
3152 QStandardItem *item = d->itemFromIndex(parent);
3153 if ((item == nullptr) || (count < 1) || (column < 0) || ((column + count) > item->columnCount()))
3154 return false;
3155 item->removeColumns(column, count);
3156 return true;
3157}
3158
3159/*!
3160 \reimp
3161*/
3162bool QStandardItemModel::removeRows(int row, int count, const QModelIndex &parent)
3163{
3164 Q_D(QStandardItemModel);
3165 QStandardItem *item = d->itemFromIndex(parent);
3166 if ((item == nullptr) || (count < 1) || (row < 0) || ((row + count) > item->rowCount()))
3167 return false;
3168 item->removeRows(row, count);
3169 return true;
3170}
3171
3172/*!
3173 \reimp
3174*/
3175int QStandardItemModel::rowCount(const QModelIndex &parent) const
3176{
3177 Q_D(const QStandardItemModel);
3178 QStandardItem *item = d->itemFromIndex(parent);
3179 return item ? item->rowCount() : 0;
3180}
3181
3182/*!
3183 \reimp
3184*/
3185bool QStandardItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
3186{
3187 if (!index.isValid())
3188 return false;
3189 QStandardItem *item = itemFromIndex(index);
3190 if (item == nullptr)
3191 return false;
3192 item->setData(value, role);
3193 return true;
3194}
3195
3196/*!
3197 \reimp
3198 */
3199bool QStandardItemModel::clearItemData(const QModelIndex &index)
3200{
3201 if (!checkIndex(index, CheckIndexOption::IndexIsValid))
3202 return false;
3203 Q_D(QStandardItemModel);
3204 QStandardItem *item = d->itemFromIndex(index);
3205 if (!item)
3206 return false;
3207 item->clearData();
3208 return true;
3209}
3210
3211/*!
3212 \reimp
3213*/
3214bool QStandardItemModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
3215{
3216 Q_D(QStandardItemModel);
3217 if ((section < 0)
3218 || ((orientation == Qt::Horizontal) && (section >= columnCount()))
3219 || ((orientation == Qt::Vertical) && (section >= rowCount()))) {
3220 return false;
3221 }
3222 QStandardItem *headerItem = nullptr;
3223 if (orientation == Qt::Horizontal) {
3224 headerItem = d->columnHeaderItems.at(section);
3225 if (headerItem == nullptr) {
3226 headerItem = d->createItem();
3227 headerItem->d_func()->setModel(this);
3228 d->columnHeaderItems.replace(section, headerItem);
3229 }
3230 } else if (orientation == Qt::Vertical) {
3231 headerItem = d->rowHeaderItems.at(section);
3232 if (headerItem == nullptr) {
3233 headerItem = d->createItem();
3234 headerItem->d_func()->setModel(this);
3235 d->rowHeaderItems.replace(section, headerItem);
3236 }
3237 }
3238 if (headerItem) {
3239 headerItem->setData(value, role);
3240 return true;
3241 }
3242 return false;
3243}
3244
3245/*!
3246 \reimp
3247*/
3248bool QStandardItemModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)
3249{
3250 QStandardItem *item = itemFromIndex(index);
3251 if (item == nullptr)
3252 return false;
3253 item->d_func()->setItemData(roles);
3254 return true;
3255}
3256
3257/*!
3258 \reimp
3259*/
3260void QStandardItemModel::sort(int column, Qt::SortOrder order)
3261{
3262 Q_D(QStandardItemModel);
3263 d->root->sortChildren(column, order);
3264}
3265
3266/*!
3267 \reimp
3268*/
3269QStringList QStandardItemModel::mimeTypes() const
3270{
3271 return QAbstractItemModel::mimeTypes() << qStandardItemModelDataListMimeType();
3272}
3273
3274/*!
3275 \reimp
3276*/
3277QMimeData *QStandardItemModel::mimeData(const QModelIndexList &indexes) const
3278{
3279 std::unique_ptr<QMimeData> data(QAbstractItemModel::mimeData(indexes));
3280 if (!data)
3281 return nullptr;
3282
3283 const QString format = qStandardItemModelDataListMimeType();
3284 if (!mimeTypes().contains(format))
3285 return data.release();
3286 QByteArray encoded;
3287 QDataStream stream(&encoded, QIODevice::WriteOnly);
3288
3289 QSet<QStandardItem*> itemsSet;
3290 QStack<QStandardItem*> stack;
3291 itemsSet.reserve(indexes.size());
3292 stack.reserve(indexes.size());
3293 for (int i = 0; i < indexes.size(); ++i) {
3294 if (QStandardItem *item = itemFromIndex(indexes.at(i))) {
3295 itemsSet << item;
3296 stack.push(item);
3297 } else {
3298 qWarning("QStandardItemModel::mimeData: No item associated with invalid index");
3299 return nullptr;
3300 }
3301 }
3302
3303 //remove duplicates children
3304 {
3305 QDuplicateTracker<QStandardItem *> seen;
3306 while (!stack.isEmpty()) {
3307 QStandardItem *itm = stack.pop();
3308 if (seen.hasSeen(itm))
3309 continue;
3310
3311 const QList<QStandardItem*> &childList = itm->d_func()->children;
3312 for (int i = 0; i < childList.size(); ++i) {
3313 QStandardItem *chi = childList.at(i);
3314 if (chi) {
3315 itemsSet.remove(chi);
3316 stack.push(chi);
3317 }
3318 }
3319 }
3320 }
3321
3322 stack.reserve(itemsSet.size());
3323 for (QStandardItem *item : std::as_const(itemsSet))
3324 stack.push(item);
3325
3326 //stream everything recursively
3327 while (!stack.isEmpty()) {
3328 QStandardItem *item = stack.pop();
3329 if (itemsSet.contains(item)) //if the item is selection 'top-level', stream its position
3330 stream << item->row() << item->column();
3331
3332 stream << *item << item->columnCount() << int(item->d_ptr->children.size());
3333 stack += item->d_ptr->children;
3334 }
3335
3336 data->setData(format, encoded);
3337 return data.release();
3338}
3339
3340
3341/* \internal
3342 Used by QStandardItemModel::dropMimeData
3343 stream out an item and his children
3344 */
3345void QStandardItemModelPrivate::decodeDataRecursive(QDataStream &stream, QStandardItem *item)
3346{
3347 int colCount, childCount;
3348 stream >> *item;
3349 stream >> colCount >> childCount;
3350 item->setColumnCount(colCount);
3351
3352 int childPos = childCount;
3353
3354 while(childPos > 0) {
3355 childPos--;
3356 QStandardItem *child = createItem();
3357 decodeDataRecursive(stream, child);
3358 item->setChild( childPos / colCount, childPos % colCount, child);
3359 }
3360}
3361
3362
3363/*!
3364 \reimp
3365*/
3366bool QStandardItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
3367 int row, int column, const QModelIndex &parent)
3368{
3369 Q_D(QStandardItemModel);
3370 // check if the action is supported
3371 if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
3372 return false;
3373 // check if the format is supported
3374 const QString format = qStandardItemModelDataListMimeType();
3375 if (!data->hasFormat(format))
3376 return QAbstractItemModel::dropMimeData(data, action, row, column, parent);
3377
3378 if (row > rowCount(parent))
3379 row = rowCount(parent);
3380 if (row == -1)
3381 row = rowCount(parent);
3382 if (column == -1)
3383 column = 0;
3384
3385 // decode and insert
3386 QByteArray encoded = data->data(format);
3387 QDataStream stream(&encoded, QIODevice::ReadOnly);
3388
3389
3390 //code based on QAbstractItemModel::decodeData
3391 // adapted to work with QStandardItem
3392 int top = INT_MAX;
3393 int left = INT_MAX;
3394 int bottom = 0;
3395 int right = 0;
3396 QList<int> rows, columns;
3397 QList<QStandardItem *> items;
3398
3399 while (!stream.atEnd()) {
3400 int r, c;
3401 QStandardItem *item = d->createItem();
3402 stream >> r >> c;
3403 d->decodeDataRecursive(stream, item);
3404
3405 rows.append(r);
3406 columns.append(c);
3407 items.append(item);
3408 top = qMin(r, top);
3409 left = qMin(c, left);
3410 bottom = qMax(r, bottom);
3411 right = qMax(c, right);
3412 }
3413
3414 // insert the dragged items into the table, use a bit array to avoid overwriting items,
3415 // since items from different tables can have the same row and column
3416 int dragRowCount = 0;
3417 int dragColumnCount = right - left + 1;
3418
3419 // Compute the number of continuous rows upon insertion and modify the rows to match
3420 QList<int> rowsToInsert(bottom + 1);
3421 for (int i = 0; i < rows.size(); ++i)
3422 rowsToInsert[rows.at(i)] = 1;
3423 for (int i = 0; i < rowsToInsert.size(); ++i) {
3424 if (rowsToInsert.at(i) == 1){
3425 rowsToInsert[i] = dragRowCount;
3426 ++dragRowCount;
3427 }
3428 }
3429 for (int i = 0; i < rows.size(); ++i)
3430 rows[i] = top + rowsToInsert.at(rows.at(i));
3431
3432 QBitArray isWrittenTo(dragRowCount * dragColumnCount);
3433
3434 // make space in the table for the dropped data
3435 int colCount = columnCount(parent);
3436 if (colCount < dragColumnCount + column) {
3437 insertColumns(colCount, dragColumnCount + column - colCount, parent);
3438 colCount = columnCount(parent);
3439 }
3440 insertRows(row, dragRowCount, parent);
3441
3442 row = qMax(0, row);
3443 column = qMax(0, column);
3444
3445 QStandardItem *parentItem = itemFromIndex (parent);
3446 if (!parentItem)
3447 parentItem = invisibleRootItem();
3448
3449 QList<QPersistentModelIndex> newIndexes(items.size());
3450 // set the data in the table
3451 for (int j = 0; j < items.size(); ++j) {
3452 int relativeRow = rows.at(j) - top;
3453 int relativeColumn = columns.at(j) - left;
3454 int destinationRow = relativeRow + row;
3455 int destinationColumn = relativeColumn + column;
3456 int flat = (relativeRow * dragColumnCount) + relativeColumn;
3457 // if the item was already written to, or we just can't fit it in the table, create a new row
3458 if (destinationColumn >= colCount || isWrittenTo.testBit(flat)) {
3459 destinationColumn = qBound(column, destinationColumn, colCount - 1);
3460 destinationRow = row + dragRowCount;
3461 insertRows(row + dragRowCount, 1, parent);
3462 flat = (dragRowCount * dragColumnCount) + relativeColumn;
3463 isWrittenTo.resize(++dragRowCount * dragColumnCount);
3464 }
3465 if (!isWrittenTo.testBit(flat)) {
3466 newIndexes[j] = index(destinationRow, destinationColumn, parentItem->index());
3467 isWrittenTo.setBit(flat);
3468 }
3469 }
3470
3471 for(int k = 0; k < newIndexes.size(); k++) {
3472 if (newIndexes.at(k).isValid()) {
3473 parentItem->setChild(newIndexes.at(k).row(), newIndexes.at(k).column(), items.at(k));
3474 } else {
3475 delete items.at(k);
3476 }
3477 }
3478
3479 return true;
3480}
3481
3482QT_END_NAMESPACE
3483
3484#include "moc_qstandarditemmodel.cpp"
bool operator()(const std::pair< QStandardItem *, int > &l, const std::pair< QStandardItem *, int > &r) const
bool operator()(const std::pair< QStandardItem *, int > &l, const std::pair< QStandardItem *, int > &r) const
static QVariant childrenCheckState(const QStandardItem *item)
QDataStream & operator<<(QDataStream &stream, const QImage &image)
[0]
Definition qimage.cpp:4064
QDataStream & operator>>(QDataStream &stream, QImage &image)
Definition qimage.cpp:4090