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
qquickstacklayout.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 <limits>
8
9#include <QtQml/qqmlinfo.h>
10
11/*!
12 \qmltype StackLayout
13 //! \nativetype QQuickStackLayout
14 \inherits Item
15 \inqmlmodule QtQuick.Layouts
16 \ingroup layouts
17 \brief The StackLayout class provides a stack of items where
18 only one item is visible at a time.
19
20 To be able to use this type more efficiently, it is recommended that you
21 understand the general mechanism of the Qt Quick Layouts module. Refer to
22 \l{Qt Quick Layouts Overview} for more information.
23
24 The current visible item can be modified by setting the \l currentIndex property.
25 The index corresponds to the order of the StackLayout's children.
26
27 In contrast to most other layouts, child Items' \l{Layout::fillWidth}{Layout.fillWidth} and \l{Layout::fillHeight}{Layout.fillHeight} properties
28 default to \c true. As a consequence, child items are by default filled to match the size of the StackLayout as long as their
29 \l{Layout::maximumWidth}{Layout.maximumWidth} or \l{Layout::maximumHeight}{Layout.maximumHeight} does not prevent it.
30
31 Items are added to the layout by reparenting the item to the layout. Similarly, removal is done by reparenting the item from the layout.
32 Both of these operations will affect the layout's \l count property.
33
34 The following code will create a StackLayout where only the 'plum' rectangle is visible.
35 \code
36 StackLayout {
37 id: layout
38 anchors.fill: parent
39 currentIndex: 1
40 Rectangle {
41 color: 'teal'
42 implicitWidth: 200
43 implicitHeight: 200
44 }
45 Rectangle {
46 color: 'plum'
47 implicitWidth: 300
48 implicitHeight: 200
49 }
50 }
51 \endcode
52
53 Items in a StackLayout support these attached properties:
54 \list
55 \li \l{Layout.minimumWidth}
56 \li \l{Layout.minimumHeight}
57 \li \l{Layout.preferredWidth}
58 \li \l{Layout.preferredHeight}
59 \li \l{Layout.maximumWidth}
60 \li \l{Layout.maximumHeight}
61 \li \l{Layout.fillWidth}
62 \li \l{Layout.fillHeight}
63 \li \l{Layout.ignored}
64 \endlist
65
66 Read more about attached properties \l{QML Object Attributes}{here}.
67 \sa ColumnLayout
68 \sa GridLayout
69 \sa RowLayout
70 \sa {QtQuick.Controls::StackView}{StackView}
71 \sa {Qt Quick Layouts Overview}
72*/
73
74QT_BEGIN_NAMESPACE
75
76static QQuickStackLayoutAttached *attachedStackLayoutObject(QQuickItem *item, bool create = false)
77{
78 return static_cast<QQuickStackLayoutAttached*>(
79 qmlAttachedPropertiesObject<QQuickStackLayout>(item, create));
80}
81
82QQuickStackLayout::QQuickStackLayout(QQuickItem *parent) :
83 QQuickLayout(*new QQuickStackLayoutPrivate, parent)
84{
85}
86
87/*!
88 \qmlproperty int StackLayout::count
89 \readonly
90
91 This property holds the number of items that belong to the layout.
92
93 Only items that are children of the StackLayout will be candidates for layouting.
94*/
95int QQuickStackLayout::count() const
96{
97 Q_D(const QQuickStackLayout);
98 return d->count;
99}
100
101/*!
102 \qmlproperty int StackLayout::currentIndex
103
104 This property holds the index of the child item that is currently visible in the StackLayout.
105 By default it will be \c -1 for an empty layout, otherwise the default is \c 0 (referring to the first item).
106
107 Since 6.5, inserting/removing a new Item at an index less than or equal to the current index
108 will increment/decrement the current index, but keep the current Item.
109*/
110int QQuickStackLayout::currentIndex() const
111{
112 Q_D(const QQuickStackLayout);
113 return d->currentIndex;
114}
115
116void QQuickStackLayout::setCurrentIndex(int index)
117{
118 Q_D(QQuickStackLayout);
119 if (index == d->currentIndex)
120 return;
121
122 QQuickItem *prev = itemAt(d->currentIndex);
123 QQuickItem *next = itemAt(index);
124 d->currentIndex = index;
125 d->explicitCurrentIndex = true;
126 if (prev)
127 prev->setVisible(false);
128 if (next)
129 next->setVisible(true);
130
131 if (isComponentComplete()) {
132 rearrange(QSizeF(width(), height()));
133 emit currentIndexChanged();
134 }
135
136 // Update attached properties after emitting currentIndexChanged()
137 // to maintain a more sensible emission order.
138 if (prev) {
139 auto stackLayoutAttached = attachedStackLayoutObject(prev);
140 if (stackLayoutAttached)
141 stackLayoutAttached->setIsCurrentItem(false);
142 }
143 if (next) {
144 auto stackLayoutAttached = attachedStackLayoutObject(next);
145 if (stackLayoutAttached)
146 stackLayoutAttached->setIsCurrentItem(true);
147 }
148}
149
150void QQuickStackLayout::componentComplete()
151{
152 QQuickLayout::componentComplete(); // will call our geometryChange(), (where isComponentComplete() == true)
153
154 childItemsChanged();
155 invalidate();
156 ensureLayoutItemsUpdated(ApplySizeHints);
157
158 QQuickItem *par = parentItem();
159 if (qobject_cast<QQuickLayout*>(par))
160 return;
161
162 rearrange(QSizeF(width(), height()));
163}
164
165void QQuickStackLayout::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &value)
166{
167 QQuickLayout::itemChange(change, value);
168 if (!isReady())
169 return;
170
171 if (change == ItemChildRemovedChange) {
172 QQuickItem *item = value.item;
173 auto stackLayoutAttached = attachedStackLayoutObject(item);
174 if (stackLayoutAttached) {
175 stackLayoutAttached->setLayout(nullptr);
176 stackLayoutAttached->setIndex(-1);
177 stackLayoutAttached->setIsCurrentItem(false);
178 }
179 m_cachedItemSizeHints.remove(item);
180 childItemsChanged(AdjustCurrentIndex); // removal; might have to adjust currentIndex
181 invalidate();
182 } else if (change == ItemChildAddedChange) {
183 childItemsChanged();
184 invalidate();
185 }
186}
187
188QSizeF QQuickStackLayout::sizeHint(Qt::SizeHint whichSizeHint) const
189{
190 Q_D(const QQuickStackLayout);
191 QSizeF &askingFor = m_cachedSizeHints[whichSizeHint];
192 if (!askingFor.isValid()) {
193 QSizeF &minS = m_cachedSizeHints[Qt::MinimumSize];
194 QSizeF &prefS = m_cachedSizeHints[Qt::PreferredSize];
195 QSizeF &maxS = m_cachedSizeHints[Qt::MaximumSize];
196
197 minS = QSizeF(0,0);
198 prefS = QSizeF(0,0);
199 maxS = QSizeF(std::numeric_limits<qreal>::infinity(), std::numeric_limits<qreal>::infinity());
200
201 const int count = itemCount();
202 for (int i = 0; i < count; ++i) {
203 SizeHints &hints = cachedItemSizeHints(i);
204 minS = minS.expandedTo(hints.min());
205 prefS = prefS.expandedTo(hints.pref());
206 //maxS = maxS.boundedTo(hints.max()); // Can be resized to be larger than any of its items.
207 // This is the same as QStackLayout does it.
208 // Not sure how descent makes sense here...
209 }
210 }
211 d->m_dirty = false;
212 return askingFor;
213}
214
215int QQuickStackLayout::indexOf(QQuickItem *childItem) const
216{
217 if (childItem) {
218 int indexOfItem = 0;
219 const auto items = childItems();
220 for (QQuickItem *item : items) {
221 if (shouldIgnoreItem(item))
222 continue;
223 if (childItem == item)
224 return indexOfItem;
225 ++indexOfItem;
226 }
227 }
228 return -1;
229}
230
231QQuickStackLayoutAttached *QQuickStackLayout::qmlAttachedProperties(QObject *object)
232{
233 return new QQuickStackLayoutAttached(object);
234}
235
236QQuickItem *QQuickStackLayout::itemAt(int index) const
237{
238 const auto items = childItems();
239 for (QQuickItem *item : items) {
240 if (shouldIgnoreItem(item))
241 continue;
242 if (index == 0)
243 return item;
244 --index;
245 }
246 return nullptr;
247}
248
249int QQuickStackLayout::itemCount() const
250{
251 int count = 0;
252 const auto items = childItems();
253 for (QQuickItem *item : items) {
254 if (shouldIgnoreItem(item))
255 continue;
256 ++count;
257 }
258 return count;
259}
260
261void QQuickStackLayout::setAlignment(QQuickItem * /*item*/, Qt::Alignment /*align*/)
262{
263 // ### Do we have to respect alignment?
264}
265
266void QQuickStackLayout::invalidate(QQuickItem *childItem)
267{
268 if (childItem) {
269 SizeHints &hints = m_cachedItemSizeHints[childItem];
270 hints.min() = QSizeF();
271 hints.pref() = QSizeF();
272 hints.max() = QSizeF();
273 }
274
275 for (int i = 0; i < Qt::NSizeHints; ++i)
276 m_cachedSizeHints[i] = QSizeF();
277 QQuickLayout::invalidate(this);
278
279 if (QQuickLayout *parentLayout = qobject_cast<QQuickLayout *>(parentItem()))
280 parentLayout->invalidate(this);
281}
282
283void QQuickStackLayout::itemIgnoredChanged(QQuickItem *childItem)
284{
285 if (!isReady())
286 return;
287
288 // Note that this must happen before the cached size hints are discarded
289 // below, since invalidate() re-creates the entry for childItem.
290 invalidate(childItem);
291
292 if (isItemIgnored(childItem)) {
293 // The item is no longer one of ours, so clear the state we imposed on
294 // it. This mirrors what itemChange() does for ItemChildRemovedChange,
295 // except that the item is still a child, so it keeps its layout().
296 if (QQuickStackLayoutAttached *attached = attachedStackLayoutObject(childItem)) {
297 attached->setIndex(-1);
298 attached->setIsCurrentItem(false);
299 }
300 m_cachedItemSizeHints.remove(childItem);
301 }
302
303 childItemsChanged(AdjustCurrentIndex);
304}
305
306void QQuickStackLayout::childItemsChanged(AdjustCurrentIndexPolicy adjustCurrentIndexPolicy)
307{
308 Q_D(QQuickStackLayout);
309 const int count = itemCount();
310 const int oldIndex = d->currentIndex;
311 if (!d->explicitCurrentIndex)
312 d->currentIndex = (count > 0 ? 0 : -1);
313
314 if (adjustCurrentIndexPolicy == AdjustCurrentIndex) {
315 /*
316 * If an item is inserted or deleted at an index less than or equal to the current index it
317 * will affect the current index, but keep the current item. This is consistent with
318 * QStackedLayout, QStackedWidget and TabBar
319 *
320 * Unless the caller is componentComplete(), we can assume that only one of the children
321 * are visible, and we should keep that visible even if the stacking order has changed.
322 * This means that if the sibling order has changed (or an item stacked before the current
323 * item is added/removed), we must update the currentIndex so that it corresponds with the
324 * current visible item.
325 */
326 if (d->currentIndex < d->count) {
327 for (int i = 0; i < count; ++i) {
328 QQuickItem *child = itemAt(i);
329 if (child->isVisible()) {
330 d->currentIndex = i;
331 break;
332 }
333 }
334 }
335 }
336 if (d->currentIndex != oldIndex)
337 emit currentIndexChanged();
338
339 if (count != d->count) {
340 d->count = count;
341 emit countChanged();
342 }
343 for (int i = 0; i < count; ++i) {
344 QQuickItem *child = itemAt(i);
345 checkAnchors(child);
346 child->setVisible(d->currentIndex == i);
347
348 auto stackLayoutAttached = attachedStackLayoutObject(child);
349 if (stackLayoutAttached) {
350 stackLayoutAttached->setLayout(this);
351 stackLayoutAttached->setIndex(i);
352 stackLayoutAttached->setIsCurrentItem(d->currentIndex == i);
353 }
354 }
355}
356
357QQuickStackLayout::SizeHints &QQuickStackLayout::cachedItemSizeHints(int index) const
358{
359 QQuickItem *item = itemAt(index);
360 Q_ASSERT(item);
361 SizeHints &hints = m_cachedItemSizeHints[item]; // will create an entry if it doesn't exist
362 if (!hints.min().isValid())
363 QQuickStackLayout::collectItemSizeHints(item, hints.array);
364 return hints;
365}
366
367
368void QQuickStackLayout::rearrange(const QSizeF &newSize)
369{
370 Q_D(QQuickStackLayout);
371 if (newSize.isNull() || !newSize.isValid())
372 return;
373
374 qCDebug(lcQuickLayouts) << "QQuickStackLayout::rearrange";
375
376 if (d->currentIndex == -1 || d->currentIndex >= m_cachedItemSizeHints.size())
377 return;
378 QQuickStackLayout::SizeHints &hints = cachedItemSizeHints(d->currentIndex);
379 QQuickItem *item = itemAt(d->currentIndex);
380 Q_ASSERT(item);
381 item->setPosition(QPointF(0,0)); // ### respect alignment?
382 const QSizeF oldSize(item->width(), item->height());
383 const QSizeF effectiveNewSize = newSize.expandedTo(hints.min()).boundedTo(hints.max());
384 item->setSize(effectiveNewSize);
385 if (effectiveNewSize == oldSize)
386 item->polish();
387 QQuickLayout::rearrange(newSize);
388}
389
390void QQuickStackLayout::setStretchFactor(QQuickItem * /*item*/, int /*stretchFactor*/, Qt::Orientation /*orient*/)
391{
392}
393
394void QQuickStackLayout::collectItemSizeHints(QQuickItem *item, QSizeF *sizeHints)
395{
396 QQuickLayoutAttached *info = nullptr;
397 QQuickLayout::effectiveSizeHints_helper(item, sizeHints, &info, true);
398 if (!info)
399 return;
400 if (info->isFillWidthSet() && !info->fillWidth()) {
401 const qreal pref = sizeHints[Qt::PreferredSize].width();
402 sizeHints[Qt::MinimumSize].setWidth(pref);
403 sizeHints[Qt::MaximumSize].setWidth(pref);
404 }
405
406 if (info->isFillHeightSet() && !info->fillHeight()) {
407 const qreal pref = sizeHints[Qt::PreferredSize].height();
408 sizeHints[Qt::MinimumSize].setHeight(pref);
409 sizeHints[Qt::MaximumSize].setHeight(pref);
410 }
411}
412
413bool QQuickStackLayout::shouldIgnoreItem(QQuickItem *item) const
414{
415 // Unlike the other layouts, a StackLayout must not treat an explicitly
416 // invisible child as ignored: it hides the non-current children itself (see
417 // childItemsChanged())
418 return isItemIgnored(item) || QQuickItemPrivate::get(item)->isTransparentForPositioner();
419}
420
421void QQuickStackLayout::itemSiblingOrderChanged(QQuickItem *)
422{
423 if (!isReady())
424 return;
425 childItemsChanged(AdjustCurrentIndex);
426 invalidate();
427}
428
429QQuickStackLayoutAttached::QQuickStackLayoutAttached(QObject *object)
430{
431 auto item = qobject_cast<QQuickItem*>(object);
432 if (!item) {
433 qmlWarning(object) << "StackLayout attached property must be attached to an object deriving from Item";
434 return;
435 }
436
437 auto stackLayout = qobject_cast<QQuickStackLayout*>(item->parentItem());
438 if (!stackLayout) {
439 // It might not be a child of a StackLayout yet, and that's OK.
440 // The index will get set by updateLayoutItems() when it's reparented.
441 return;
442 }
443
444 if (!stackLayout->isComponentComplete()) {
445 // Don't try to get the index if the StackLayout itself hasn't loaded yet.
446 return;
447 }
448
449 // If we got this far, the item was added as a child to the StackLayout after it loaded.
450 // indexOf() returns -1 for an item that the layout does not manage, which
451 // must not be mistaken for the currentIndex of an empty StackLayout.
452 const int index = stackLayout->indexOf(item);
453 setLayout(stackLayout);
454 setIndex(index);
455 setIsCurrentItem(index >= 0 && stackLayout->currentIndex() == index);
456
457 // In case of lazy loading in loader, attachedProperties are created and updated for the
458 // object after adding the child object to the stack layout, which leads to entries with
459 // same index. Triggering childItemsChanged() resets to right index in the stack layout.
460 stackLayout->childItemsChanged();
461}
462
463/*!
464 \qmlattachedproperty int StackLayout::index
465 \readonly
466
467 This attached property holds the index of each child item in the
468 \l StackLayout.
469
470 \sa isCurrentItem, layout
471
472 \since QtQuick.Layouts 1.15
473*/
474int QQuickStackLayoutAttached::index() const
475{
476 return m_index;
477}
478
479void QQuickStackLayoutAttached::setIndex(int index)
480{
481 if (index == m_index)
482 return;
483
484 m_index = index;
485 emit indexChanged();
486}
487
488/*!
489 \qmlattachedproperty bool StackLayout::isCurrentItem
490 \readonly
491
492 This attached property is \c true if this child is the current item
493 in the \l StackLayout.
494
495 \sa index, layout
496
497 \since QtQuick.Layouts 1.15
498*/
499bool QQuickStackLayoutAttached::isCurrentItem() const
500{
501 return m_isCurrentItem;
502}
503
504void QQuickStackLayoutAttached::setIsCurrentItem(bool isCurrentItem)
505{
506 if (isCurrentItem == m_isCurrentItem)
507 return;
508
509 m_isCurrentItem = isCurrentItem;
510 emit isCurrentItemChanged();
511}
512
513/*!
514 \qmlattachedproperty StackLayout StackLayout::layout
515 \readonly
516
517 This attached property holds the \l StackLayout that manages this child
518 item.
519
520 \sa index, isCurrentItem
521
522 \since QtQuick.Layouts 1.15
523*/
524QQuickStackLayout *QQuickStackLayoutAttached::layout() const
525{
526 return m_layout;
527}
528
529void QQuickStackLayoutAttached::setLayout(QQuickStackLayout *layout)
530{
531 if (layout == m_layout)
532 return;
533
534 m_layout = layout;
535 emit layoutChanged();
536}
537
538QT_END_NAMESPACE
539
540#include "moc_qquickstacklayout_p.cpp"