2 * Copyright (C) 2013 Canonical, Ltd.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * Some documentation on how this thing works:
20 * A flickable has two very important concepts that define the top and
21 * height of the flickable area.
22 * The top is returned in minYExtent()
23 * The height is set using setContentHeight()
24 * By changing those two values we can make the list grow up or down
25 * as needed. e.g. if we are in the middle of the list
26 * and something that is above the viewport grows, since we do not
27 * want to change the viewport because of that we just adjust the
28 * minYExtent so that the list grows up.
30 * The implementation on the list relies on the delegateModel doing
31 * most of the instantiation work. You call createItem() when you
32 * need to create an item asking for it async or not. If returns null
33 * it means the item will be created async and the model will call the
34 * itemCreated slot with the item.
36 * updatePolish is the central point of dispatch for the work of the
37 * class. It is called by the scene graph just before drawing the class.
39 * * Make sure all items are positioned correctly
40 * * Add/Remove items if needed
41 * * Update the content height if it was dirty
43 * m_visibleItems contains all the items we have created at the moment.
44 * Actually not all of them are visible since it includes the ones
45 * in the cache area we create asynchronously to help performance.
46 * The first item in m_visibleItems has the m_firstVisibleIndex in
47 * the model. If you actually want to know what is the first
48 * item in the viewport you have to find the first non culled element
51 * All the items (except the header) are childs of m_clipItem which
52 * is a child of the contentItem() of the flickable (The contentItem()
53 * is what actually 'moves' in a a flickable). This way
54 * we can implement the clipping needed so we can have the header
55 * shown in the middle of the list over the items without the items
56 * leaking under the header in case it is transparent.
58 * The first item of m_visibleItems is the one that defines the
59 * positions of all the rest of items (see updatePolish()) and
60 * this is why sometimes we move it even if it's not the item
61 * that has triggered the function (i.e. in itemGeometryChanged())
63 * m_visibleItems is a list of ListItem. Each ListItem
64 * will contain a item and potentially a sectionItem. The sectionItem
65 * is only there when the list is using sectionDelegate+sectionProperty
66 * and this is the first item of the section. Each ListItem is vertically
67 * layouted with the sectionItem first and then the item.
69 * For sectioning we also have a section item alone (m_topSectionItem)
70 * that is used for the cases we need to show the sticky section item at
71 * the top of the view.
73 * Each delegate item has a context property called heightToClip that is
74 * used to communicate to the delegate implementation in case it has to
75 * clip itself because of overlapping with the top sticky section item.
76 * This is an implementation decision since it has been agreed it
77 * is easier to implement the clipping in QML with this info than to
78 * do it at the C++ level.
80 * Note that minYExtent and height are not always totally accurate, since
81 * we don't have the items created we can't guess their heights
82 * so we can only guarantee the values are correct when the first/last
83 * items of the list are visible, otherwise we just live with good enough
84 * values that make the list scrollable
86 * There are a few things that are not really implemented or tested properly
87 * which we don't use at the moment like changing the model, changing
88 * the section delegate, having a section delegate that changes its size, etc.
89 * The known missing features are marked with TODOs along the code.
92#include "listviewwithpageheader.h"
94#include <QCoreApplication>
97#include <qqmlengine.h>
98#pragma GCC diagnostic push
99#pragma GCC diagnostic ignored "-pedantic"
100#include <private/qqmlcontext_p.h>
101#include <private/qqmldelegatemodel_p.h>
102#include <private/qqmlglobal_p.h>
103#include <private/qquickitem_p.h>
104#include <private/qquickanimation_p.h>
105#pragma GCC diagnostic pop
106// #include <private/qquickrectangle_p.h>
108qreal ListViewWithPageHeader::ListItem::height() const
110 return m_item->height() + (m_sectionItem ? m_sectionItem->height() : 0);
113qreal ListViewWithPageHeader::ListItem::y() const
115 return m_item->y() - (m_sectionItem ? m_sectionItem->height() : 0);
118void ListViewWithPageHeader::ListItem::setY(qreal newY)
121 m_sectionItem->setY(newY);
122 m_item->setY(newY + m_sectionItem->height());
128bool ListViewWithPageHeader::ListItem::culled() const
130 return QQuickItemPrivate::get(m_item)->culled;
133void ListViewWithPageHeader::ListItem::setCulled(bool culled)
135 QQuickItemPrivate::get(m_item)->setCulled(culled);
137 QQuickItemPrivate::get(m_sectionItem)->setCulled(culled);
140void ListViewWithPageHeader::ListItem::setSectionItem(QQuickItem *sectionItem)
142 m_sectionItem = sectionItem;
145ListViewWithPageHeader::ListViewWithPageHeader()
146 : m_delegateModel(nullptr)
147 , m_asyncRequestedIndex(-1)
148 , m_delegateValidated(false)
149 , m_firstVisibleIndex(-1)
151 , m_contentHeightDirty(false)
152 , m_headerItem(nullptr)
153 , m_previousContentY(0)
154 , m_headerItemShownHeight(0)
155 , m_sectionDelegate(nullptr)
156 , m_topSectionItem(nullptr)
157 , m_forceNoClip(false)
159 , m_inContentHeightKeepHeaderShown(false)
162 m_clipItem = new QQuickItem(contentItem());
163// m_clipItem = new QQuickRectangle(contentItem());
164// ((QQuickRectangle*)m_clipItem)->setColor(Qt::gray);
166 m_contentYAnimation = new QQuickNumberAnimation(this);
167 m_contentYAnimation->setEasing(QEasingCurve::OutQuad);
168 m_contentYAnimation->setProperty(QStringLiteral("contentY"));
169 m_contentYAnimation->setDuration(200);
170 m_contentYAnimation->setTargetObject(this);
172 connect(contentItem(), &QQuickItem::widthChanged, this, &ListViewWithPageHeader::onContentWidthChanged);
173 connect(this, &ListViewWithPageHeader::contentHeightChanged, this, &ListViewWithPageHeader::onContentHeightChanged);
174 connect(this, &ListViewWithPageHeader::heightChanged, this, &ListViewWithPageHeader::onHeightChanged);
175 connect(m_contentYAnimation, &QQuickNumberAnimation::runningChanged, this, &ListViewWithPageHeader::contentYAnimationRunningChanged);
177 setFlickableDirection(VerticalFlick);
180ListViewWithPageHeader::~ListViewWithPageHeader()
184QAbstractItemModel *ListViewWithPageHeader::model() const
186 return m_delegateModel ? m_delegateModel->model().value<QAbstractItemModel *>() : nullptr;
189void ListViewWithPageHeader::setModel(QAbstractItemModel *model)
191 if (model != this->model()) {
192 if (!m_delegateModel) {
193 createDelegateModel();
195 disconnect(m_delegateModel, &QQmlDelegateModel::modelUpdated, this, &ListViewWithPageHeader::onModelUpdated);
197 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
198 connect(m_delegateModel, &QQmlDelegateModel::modelUpdated, this, &ListViewWithPageHeader::onModelUpdated);
199 Q_EMIT modelChanged();
202// Q_EMIT contentHeightChanged();
203// Q_EMIT contentYChanged();
207QQmlComponent *ListViewWithPageHeader::delegate() const
209 return m_delegateModel ? m_delegateModel->delegate() : nullptr;
212void ListViewWithPageHeader::setDelegate(QQmlComponent *delegate)
214 if (delegate != this->delegate()) {
215 if (!m_delegateModel) {
216 createDelegateModel();
219 // Cleanup the existing items
220 Q_FOREACH(ListItem *item, m_visibleItems)
222 m_visibleItems.clear();
223 initializeValuesForEmptyList();
225 m_delegateModel->setDelegate(delegate);
227 Q_EMIT delegateChanged();
228 m_delegateValidated = false;
229 m_contentHeightDirty = true;
234void ListViewWithPageHeader::initializeValuesForEmptyList()
236 m_firstVisibleIndex = -1;
240 if (m_topSectionItem) {
241 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
245QQuickItem *ListViewWithPageHeader::header() const
250void ListViewWithPageHeader::setHeader(QQuickItem *headerItem)
252 if (m_headerItem != headerItem) {
253 qreal oldHeaderHeight = 0;
254 qreal oldHeaderY = 0;
256 oldHeaderHeight = m_headerItem->height();
257 oldHeaderY = m_headerItem->y();
258 m_headerItem->setParentItem(nullptr);
259 QQuickItemPrivate::get(m_headerItem)->removeItemChangeListener(this, QQuickItemPrivate::ImplicitHeight);
261 m_headerItem = headerItem;
263 m_headerItem->setParentItem(contentItem());
264 m_headerItem->setZ(1);
265 m_previousHeaderImplicitHeight = m_headerItem->implicitHeight();
266 QQuickItemPrivate::get(m_headerItem)->addItemChangeListener(this, QQuickItemPrivate::ImplicitHeight);
268 qreal newHeaderHeight = m_headerItem ? m_headerItem->height() : 0;
269 if (!m_visibleItems.isEmpty() && newHeaderHeight != oldHeaderHeight) {
270 headerHeightChanged(newHeaderHeight, oldHeaderHeight, oldHeaderY);
272 m_contentHeightDirty = true;
274 Q_EMIT headerChanged();
278QQmlComponent *ListViewWithPageHeader::sectionDelegate() const
280 return m_sectionDelegate;
283void ListViewWithPageHeader::setSectionDelegate(QQmlComponent *delegate)
285 if (delegate != m_sectionDelegate) {
286 // TODO clean existing sections
288 m_sectionDelegate = delegate;
290 m_topSectionItem = getSectionItem(QString(), false /*watchGeometry*/);
291 if (m_topSectionItem) {
292 m_topSectionItem->setZ(3);
293 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
294 connect(m_topSectionItem, &QQuickItem::heightChanged, this, &ListViewWithPageHeader::stickyHeaderHeightChanged);
297 // TODO create sections for existing items
299 Q_EMIT sectionDelegateChanged();
300 Q_EMIT stickyHeaderHeightChanged();
304QString ListViewWithPageHeader::sectionProperty() const
306 return m_sectionProperty;
309void ListViewWithPageHeader::setSectionProperty(const QString &property)
311 if (property != m_sectionProperty) {
312 m_sectionProperty = property;
314 updateWatchedRoles();
316 // TODO recreate sections
318 Q_EMIT sectionPropertyChanged();
322bool ListViewWithPageHeader::forceNoClip() const
324 return m_forceNoClip;
327void ListViewWithPageHeader::setForceNoClip(bool noClip)
329 if (noClip != m_forceNoClip) {
330 m_forceNoClip = noClip;
332 Q_EMIT forceNoClipChanged();
336int ListViewWithPageHeader::stickyHeaderHeight() const
338 return m_topSectionItem ? m_topSectionItem->height() : 0;
341qreal ListViewWithPageHeader::headerItemShownHeight() const
343 return m_headerItemShownHeight;
346int ListViewWithPageHeader::cacheBuffer() const
348 return m_cacheBuffer;
351void ListViewWithPageHeader::setCacheBuffer(int cacheBuffer)
353 if (cacheBuffer < 0) {
354 qmlInfo(this) << "Cannot set a negative cache buffer";
358 if (cacheBuffer != m_cacheBuffer) {
359 m_cacheBuffer = cacheBuffer;
360 Q_EMIT cacheBufferChanged();
365void ListViewWithPageHeader::positionAtBeginning()
367 if (m_delegateModel->count() <= 0)
370 qreal headerHeight = (m_headerItem ? m_headerItem->height() : 0);
371 if (m_firstVisibleIndex != 0) {
372 // TODO This could be optimized by trying to reuse the interesection
373 // of items that may end up intersecting between the existing
374 // m_visibleItems and the items we are creating in the next loop
375 Q_FOREACH(ListItem *item, m_visibleItems)
377 m_visibleItems.clear();
378 m_firstVisibleIndex = -1;
380 // Create the item 0, it will be already correctly positioned at createItem()
382 ListItem *item = createItem(0, false);
383 // Create the subsequent items
385 qreal pos = item->y() + item->height();
386 const qreal bufferTo = height() + m_cacheBuffer;
387 while (modelIndex < m_delegateModel->count() && pos <= bufferTo) {
388 if (!(item = createItem(modelIndex, false)))
390 pos += item->height();
394 m_previousContentY = m_visibleItems.first()->y() - headerHeight;
396 setContentY(m_visibleItems.first()->y() + m_clipItem->y() - headerHeight);
398 // TODO This should not be needed and the code that adjust the m_headerItem position
399 // in viewportMoved() should be enough but in some cases we have not found a way to reproduce
400 // yet the code of viewportMoved() fails so here we make sure that at least if we are calling
401 // positionAtBeginning the header item will be correctly positioned
402 m_headerItem->setY(-m_minYExtent);
406static inline bool uFuzzyCompare(qreal r1, qreal r2)
408 return qFuzzyCompare(r1, r2) || (qFuzzyIsNull(r1) && qFuzzyIsNull(r2));
411void ListViewWithPageHeader::showHeader()
416 const auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
417 if (!uFuzzyCompare(to, contentY())) {
418 const bool headerShownByItsOwn = contentY() < m_headerItem->y() + m_headerItem->height();
419 if (headerShownByItsOwn && m_headerItemShownHeight == 0) {
420 // We are not clipping since we are just at the top of the viewport
421 // but because of the showHeader animation we will need to, so
422 // enable the clipping without logically moving the items
423 m_headerItemShownHeight = m_headerItem->y() + m_headerItem->height() - contentY();
424 if (!m_visibleItems.isEmpty()) {
426 ListItem *firstItem = m_visibleItems.first();
427 firstItem->setY(firstItem->y() - m_headerItemShownHeight);
430 Q_EMIT headerItemShownHeightChanged();
432 m_contentYAnimation->setTo(to);
433 contentYAnimationType = ContentYAnimationShowHeader;
434 m_contentYAnimation->start();
438int ListViewWithPageHeader::firstCreatedIndex() const
440 return m_firstVisibleIndex;
443int ListViewWithPageHeader::createdItemCount() const
445 return m_visibleItems.count();
448QQuickItem *ListViewWithPageHeader::item(int modelIndex) const
450 ListItem *item = itemAtIndex(modelIndex);
457bool ListViewWithPageHeader::maximizeVisibleArea(int modelIndex)
459 ListItem *listItem = itemAtIndex(modelIndex);
461 return maximizeVisibleArea(listItem, listItem->height());
467bool ListViewWithPageHeader::maximizeVisibleArea(int modelIndex, int itemHeight)
472 ListItem *listItem = itemAtIndex(modelIndex);
474 return maximizeVisibleArea(listItem, itemHeight + (listItem->sectionItem() ? listItem->sectionItem()->height() : 0));
480bool ListViewWithPageHeader::maximizeVisibleArea(ListItem *listItem, int listItemHeight)
484 const auto listItemY = m_clipItem->y() + listItem->y();
485 if (listItemY > contentY() && listItemY + listItemHeight > contentY() + height()) {
486 // we can scroll the list up to show more stuff
487 const auto to = qMin(listItemY, listItemY + listItemHeight - height());
488 m_contentYAnimation->setTo(to);
489 contentYAnimationType = ContentYAnimationMaximizeVisibleArea;
490 m_contentYAnimation->start();
491 } else if ((listItemY < contentY() && listItemY + listItemHeight < contentY() + height()) ||
492 (m_topSectionItem && !listItem->sectionItem() && listItemY - m_topSectionItem->height() < contentY() && listItemY + listItemHeight < contentY() + height()))
494 // we can scroll the list down to show more stuff
495 auto realVisibleListItemY = listItemY;
496 if (m_topSectionItem) {
497 // If we are showing the top section sticky item and this item doesn't have a section
498 // item we have to make sure to scroll it a bit more so that it is not underlapping
499 // the top section sticky item
500 bool topSectionShown = !QQuickItemPrivate::get(m_topSectionItem)->culled;
501 if (topSectionShown && !listItem->sectionItem()) {
502 realVisibleListItemY -= m_topSectionItem->height();
505 const auto to = qMax(realVisibleListItemY, listItemY + listItemHeight - height());
506 m_contentYAnimation->setTo(to);
507 contentYAnimationType = ContentYAnimationMaximizeVisibleArea;
508 m_contentYAnimation->start();
515qreal ListViewWithPageHeader::minYExtent() const
517// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
521qreal ListViewWithPageHeader::maxYExtent() const
523 return height() - contentHeight();
526void ListViewWithPageHeader::componentComplete()
529 m_delegateModel->componentComplete();
531 QQuickFlickable::componentComplete();
536void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
538 // Check we are not being taken down and don't paint anything
539 // TODO Check if we still need this in 5.2
540 // For reproduction just inifnite loop testDash or testDashContent
541 if (!QQmlEngine::contextForObject(this)->parentContext())
544 QQuickFlickable::viewportMoved(orient);
545// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
546 const qreal diff = m_previousContentY - contentY();
548 m_previousContentY = contentY();
553void ListViewWithPageHeader::adjustHeader(qreal diff)
555 const bool showHeaderAnimationRunning = m_contentYAnimation->isRunning() && contentYAnimationType == ContentYAnimationShowHeader;
557 const auto oldHeaderItemShownHeight = m_headerItemShownHeight;
558 if (uFuzzyCompare(contentY(), -m_minYExtent) || contentY() > -m_minYExtent) {
559 m_headerItem->setHeight(m_headerItem->implicitHeight());
560 // We are going down (but it's not because of the rebound at the end)
561 // (but the header was not shown by it's own position)
562 // or the header is partially shown and we are not doing a maximizeVisibleArea either
563 const bool scrolledUp = m_previousContentY > contentY();
564 const bool notRebounding = qRound(contentY() + height()) < qRound(contentHeight());
565 const bool notShownByItsOwn = contentY() + diff >= m_headerItem->y() + m_headerItem->height();
566 const bool maximizeVisibleAreaRunning = m_contentYAnimation->isRunning() && contentYAnimationType == ContentYAnimationMaximizeVisibleArea;
568 if (!scrolledUp && (contentY() == -m_minYExtent || (m_headerItemShownHeight == 0 && m_previousContentY == m_headerItem->y()))) {
569 m_headerItemShownHeight = 0;
570 m_headerItem->setY(-m_minYExtent);
571 } else if ((scrolledUp && notRebounding && notShownByItsOwn && !maximizeVisibleAreaRunning) || (m_headerItemShownHeight > 0) || m_inContentHeightKeepHeaderShown) {
572 if (maximizeVisibleAreaRunning && diff > 0) {
573 // If we are maximizing and the header was shown, make sure we hide it
574 m_headerItemShownHeight -= diff;
576 m_headerItemShownHeight += diff;
578 if (uFuzzyCompare(contentY(), -m_minYExtent)) {
579 m_headerItemShownHeight = 0;
581 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
583 if (m_headerItemShownHeight > 0) {
584 if (uFuzzyCompare(m_headerItem->height(), m_headerItemShownHeight)) {
585 m_headerItem->setY(contentY());
586 m_headerItemShownHeight = m_headerItem->height();
588 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
591 m_headerItem->setY(-m_minYExtent);
594 Q_EMIT headerItemShownHeightChanged();
596 // Stick the header item to the top when dragging down
597 m_headerItem->setY(contentY());
598 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
600 // We will be changing the clip item, need to accomadate for it
601 // otherwise we move the firstItem down/up twice (unless the
602 // show header animation is running, where we want to keep the viewport stable)
603 if (!showHeaderAnimationRunning) {
604 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
609 if (!m_visibleItems.isEmpty()) {
611 ListItem *firstItem = m_visibleItems.first();
612 firstItem->setY(firstItem->y() + diff);
613 if (showHeaderAnimationRunning) {
619void ListViewWithPageHeader::createDelegateModel()
621 m_delegateModel = new QQmlDelegateModel(qmlContext(this), this);
622 connect(m_delegateModel, &QQmlDelegateModel::createdItem, this, &ListViewWithPageHeader::itemCreated);
623 if (isComponentComplete())
624 m_delegateModel->componentComplete();
625 updateWatchedRoles();
628void ListViewWithPageHeader::refill()
633 if (!isComponentComplete()) {
637 const qreal from = contentY();
638 const qreal to = from + height();
639 const qreal bufferFrom = from - m_cacheBuffer;
640 const qreal bufferTo = to + m_cacheBuffer;
642 bool added = addVisibleItems(from, to, false);
643 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
644 added |= addVisibleItems(bufferFrom, bufferTo, true);
646 if (added || removed) {
647 m_contentHeightDirty = true;
651bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
656 if (m_delegateModel->count() == 0)
660// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
664 if (!m_visibleItems.isEmpty()) {
665 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
666 item = m_visibleItems.last();
667 pos = item->y() + item->height() + m_clipItem->y();
669 bool changed = false;
670// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
671 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
672// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
673 if (!(item = createItem(modelIndex, asynchronous)))
675 pos += item->height();
682 if (!m_visibleItems.isEmpty()) {
683 modelIndex = m_firstVisibleIndex - 1;
684 item = m_visibleItems.first();
685 pos = item->y() + m_clipItem->y();
687 while (modelIndex >= 0 && pos > fillFrom) {
688// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
689 if (!(item = createItem(modelIndex, asynchronous)))
691 pos -= item->height();
699void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
701 QQuickItem *item = listItem->m_item;
702 QQmlDelegateModel::ReleaseFlags flags = m_delegateModel->release(item);
703 if (flags & QQmlDelegateModel::Destroyed) {
704 item->setParentItem(nullptr);
706 listItem->sectionItem()->deleteLater();
710void ListViewWithPageHeader::releaseItem(ListItem *listItem)
712 QQuickItemPrivate::get(listItem->m_item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
713 if (listItem->sectionItem()) {
714 QQuickItemPrivate::get(listItem->sectionItem())->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
716 m_itemsToRelease << listItem;
719void ListViewWithPageHeader::updateWatchedRoles()
721 if (m_delegateModel) {
722 QList<QByteArray> roles;
723 if (!m_sectionProperty.isEmpty())
724 roles << m_sectionProperty.toUtf8();
725 m_delegateModel->setWatchedRoles(roles);
729QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
731 if (!m_sectionDelegate)
734 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
736 if (modelIndex > 0) {
737 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
738 if (section == prevSection)
741 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
742 // Already inserted items can't steal next section header
743 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
744 if (section == nextSection) {
745 // Steal the section header
746 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
748 QQuickItem *sectionItem = nextItem->sectionItem();
749 nextItem->setSectionItem(nullptr);
755 return getSectionItem(section);
758QQuickItem *ListViewWithPageHeader::getSectionItem(const QString §ionText, bool watchGeometry)
760 QQuickItem *sectionItem = nullptr;
762 QQmlContext *creationContext = m_sectionDelegate->creationContext();
763 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
764 QObject *nobj = m_sectionDelegate->beginCreate(context);
766 QQml_setParent_noEvent(context, nobj);
767 sectionItem = qobject_cast<QQuickItem *>(nobj);
771 sectionItem->setProperty("text", sectionText);
772 sectionItem->setProperty("delegateIndex", -1);
773 sectionItem->setZ(2);
774 QQml_setParent_noEvent(sectionItem, m_clipItem);
775 sectionItem->setParentItem(m_clipItem);
780 m_sectionDelegate->completeCreate();
782 if (watchGeometry && sectionItem) {
783 QQuickItemPrivate::get(sectionItem)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
789void ListViewWithPageHeader::updateSectionItem(int modelIndex)
791 ListItem *item = itemAtIndex(modelIndex);
793 const QString sectionText = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
795 bool needSectionHeader = true;
796 // if it is the same section as the previous item need to drop the section
797 if (modelIndex > 0) {
798 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
799 if (sectionText == prevSection) {
800 needSectionHeader = false;
804 if (needSectionHeader) {
805 if (!item->sectionItem()) {
806 item->setSectionItem(getSectionItem(sectionText));
808 item->sectionItem()->setProperty("text", sectionText);
811 if (item->sectionItem()) {
812 item->sectionItem()->deleteLater();
813 item->setSectionItem(nullptr);
819bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
821// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
822 // Do not remove items if we are overshooting up or down, since we'll come back
823 // to the "stable" position and delete/create items without any reason
824 if (contentY() < -m_minYExtent) {
826 } else if (contentY() + height() > contentHeight()) {
829 bool changed = false;
831 bool foundVisible = false;
833 int removedItems = 0;
834 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
835 while (i < m_visibleItems.count()) {
836 ListItem *item = m_visibleItems[i];
837 const qreal pos = item->y() + m_clipItem->y();
838// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
839 if (pos + item->height() < bufferFrom || pos > bufferTo) {
840// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
842 m_visibleItems.removeAt(i);
848 const int itemIndex = m_firstVisibleIndex + removedItems + i;
849 m_firstVisibleIndex = itemIndex;
855 initializeValuesForEmptyList();
857 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
864ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
866// qDebug() << "CREATE ITEM" << modelIndex;
867 if (asynchronous && m_asyncRequestedIndex != -1)
870 m_asyncRequestedIndex = -1;
871 QObject* object = m_delegateModel->object(modelIndex, asynchronous);
872 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
875 m_delegateModel->release(object);
876 if (!m_delegateValidated) {
877 m_delegateValidated = true;
878 QObject* delegateObj = delegate();
879 qmlInfo(delegateObj ? delegateObj : this) << "Delegate must be of Item type";
882 m_asyncRequestedIndex = modelIndex;
886// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
887 ListItem *listItem = new ListItem;
888 listItem->m_item = item;
889 listItem->setSectionItem(getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/));
890 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
891 ListItem *prevItem = itemAtIndex(modelIndex - 1);
892 bool lostItem = false; // Is an item that we requested async but because of model changes
893 // it is no longer attached to any of the existing items (has no prev nor next item)
894 // nor is the first item
896 listItem->setY(prevItem->y() + prevItem->height());
898 ListItem *currItem = itemAtIndex(modelIndex);
900 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
901 listItem->setY(currItem->y() - listItem->height());
903 ListItem *nextItem = itemAtIndex(modelIndex + 1);
905 listItem->setY(nextItem->y() - listItem->height());
906 } else if (modelIndex == 0) {
907 listItem->setY(-m_clipItem->y() + (m_headerItem ? m_headerItem->height() : 0));
908 } else if (!m_visibleItems.isEmpty()) {
914 listItem->setCulled(true);
915 releaseItem(listItem);
918 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() <= contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
919 if (m_visibleItems.isEmpty()) {
920 m_visibleItems << listItem;
922 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
924 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
925 m_firstVisibleIndex = modelIndex;
928 if (listItem->sectionItem()) {
929 listItem->sectionItem()->setProperty("delegateIndex", modelIndex);
932 m_contentHeightDirty = true;
938void ListViewWithPageHeader::itemCreated(int modelIndex, QObject *object)
940 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
942 qWarning() << "ListViewWithPageHeader::itemCreated got a non item for index" << modelIndex;
945// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
946 // Check we are not being taken down and don't paint anything
947 // TODO Check if we still need this in 5.2
948 // For reproduction just inifnite loop testDash or testDashContent
949 if (!QQmlEngine::contextForObject(this)->parentContext())
952 item->setParentItem(m_clipItem);
953 // FIXME Why do we need the refreshExpressions call?
954 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
955 QQmlContextPrivate::get(context)->data->refreshExpressions();
956 item->setProperty("heightToClip", QVariant::fromValue<int>(0));
957 if (modelIndex == m_asyncRequestedIndex) {
958 createItem(modelIndex, false);
963void ListViewWithPageHeader::updateClipItem()
965 m_clipItem->setHeight(height() - m_headerItemShownHeight);
966 m_clipItem->setY(contentY() + m_headerItemShownHeight);
967 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
970void ListViewWithPageHeader::onContentHeightChanged()
975void ListViewWithPageHeader::onContentWidthChanged()
977 m_clipItem->setWidth(contentItem()->width());
980void ListViewWithPageHeader::onHeightChanged()
986void ListViewWithPageHeader::onModelUpdated(const QQmlChangeSet &changeSet, bool /*reset*/)
988 // TODO Do something with reset
989// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
990 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
992 Q_FOREACH(const QQmlChangeSet::Change remove, changeSet.removes()) {
993// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
994 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
995 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
996 // If all the items we are removing are either not created or culled
997 // we have to grow down to avoid viewport changing
998 bool growDown = true;
999 for (int i = 0; growDown && i < remove.count; ++i) {
1000 const int modelIndex = remove.index + i;
1001 ListItem *item = itemAtIndex(modelIndex);
1002 if (item && !item->culled()) {
1006 for (int i = remove.count - 1; i >= 0; --i) {
1007 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
1008 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
1009 ListItem *item = m_visibleItems[visibleIndex];
1010 // Pass the section item down if needed
1011 if (item->sectionItem() && visibleIndex + 1 < m_visibleItems.count()) {
1012 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
1013 if (!nextItem->sectionItem()) {
1014 nextItem->setSectionItem(item->sectionItem());
1015 item->setSectionItem(nullptr);
1019 m_visibleItems.removeAt(visibleIndex);
1024 } else if (remove.index <= m_firstVisibleIndex && !m_visibleItems.isEmpty()) {
1025 m_visibleItems.first()->setY(oldFirstValidIndexPos);
1027 if (m_visibleItems.isEmpty()) {
1028 m_firstVisibleIndex = -1;
1030 m_firstVisibleIndex -= qMax(0, m_firstVisibleIndex - remove.index);
1032 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
1033 m_firstVisibleIndex -= remove.count;
1035 for (int i = remove.count - 1; i >= 0; --i) {
1036 const int modelIndex = remove.index + i;
1037 if (modelIndex == m_asyncRequestedIndex) {
1038 m_asyncRequestedIndex = -1;
1039 } else if (modelIndex < m_asyncRequestedIndex) {
1040 m_asyncRequestedIndex--;
1045 Q_FOREACH(const QQmlChangeSet::Change insert, changeSet.inserts()) {
1046// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
1047 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
1048 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
1049 if (insertingInValidIndexes || firstItemWithViewOnTop)
1051 // If the items we are adding won't be really visible
1052 // we grow up instead of down to not change the viewport
1053 bool growUp = false;
1054 if (!firstItemWithViewOnTop) {
1055 for (int i = 0; i < m_visibleItems.count(); ++i) {
1056 if (!m_visibleItems[i]->culled()) {
1057 if (insert.index <= m_firstVisibleIndex + i) {
1065 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
1066 for (int i = insert.count - 1; i >= 0; --i) {
1067 const int modelIndex = insert.index + i;
1068 ListItem *item = createItem(modelIndex, false);
1070 ListItem *firstItem = m_visibleItems.first();
1071 firstItem->setY(firstItem->y() - item->height());
1073 // Adding an item may break a "same section" chain, so check
1074 // if we need adding a new section item
1075 if (m_sectionDelegate) {
1076 ListItem *nextItem = itemAtIndex(modelIndex + 1);
1077 if (nextItem && !nextItem->sectionItem()) {
1078 nextItem->setSectionItem(getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/));
1079 if (growUp && nextItem->sectionItem()) {
1080 ListItem *firstItem = m_visibleItems.first();
1081 firstItem->setY(firstItem->y() - nextItem->sectionItem()->height());
1086 if (firstItemWithViewOnTop) {
1087 ListItem *firstItem = m_visibleItems.first();
1088 firstItem->setY(oldFirstValidIndexPos);
1091 } else if (insert.index <= m_firstVisibleIndex) {
1092 m_firstVisibleIndex += insert.count;
1095 for (int i = insert.count - 1; i >= 0; --i) {
1096 const int modelIndex = insert.index + i;
1097 if (modelIndex <= m_asyncRequestedIndex) {
1098 m_asyncRequestedIndex++;
1103 Q_FOREACH(const QQmlChangeSet::Change change, changeSet.changes()) {
1104 for (int i = change.start(); i < change.end(); ++i) {
1105 updateSectionItem(i);
1107 // Also update the section header for the next item after the change since it may be influenced
1108 updateSectionItem(change.end());
1111 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
1112 if (m_visibleItems.isEmpty()) {
1113 initializeValuesForEmptyList();
1119 for (int i = 0; i < m_visibleItems.count(); ++i) {
1120 ListItem *item = m_visibleItems[i];
1121 if (item->sectionItem()) {
1122 item->sectionItem()->setProperty("delegateIndex", m_firstVisibleIndex + i);
1128 m_contentHeightDirty = true;
1131void ListViewWithPageHeader::contentYAnimationRunningChanged(bool running)
1133 setInteractive(!running);
1135 m_contentHeightDirty = true;
1140void ListViewWithPageHeader::itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry)
1142 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
1143 if (heightDiff != 0) {
1144 if (!m_visibleItems.isEmpty()) {
1145 ListItem *firstItem = m_visibleItems.first();
1146 const auto prevFirstItemY = firstItem->y();
1147 if (!m_inContentHeightKeepHeaderShown && oldGeometry.y() + oldGeometry.height() + m_clipItem->y() <= contentY()) {
1148 firstItem->setY(firstItem->y() - heightDiff);
1149 } else if (item == firstItem->sectionItem()) {
1150 firstItem->setY(firstItem->y() + heightDiff);
1153 if (firstItem->y() != prevFirstItemY) {
1161 m_contentHeightDirty = true;
1165void ListViewWithPageHeader::itemImplicitHeightChanged(QQuickItem *item)
1167 if (item == m_headerItem) {
1168 const qreal diff = m_headerItem->implicitHeight() - m_previousHeaderImplicitHeight;
1171 m_previousHeaderImplicitHeight = m_headerItem->implicitHeight();
1174 m_contentHeightDirty = true;
1179void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
1181 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
1182 if (m_headerItemShownHeight > 0) {
1183 // If the header is shown because of the clip
1185 m_headerItemShownHeight += heightDiff;
1186 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
1189 Q_EMIT headerItemShownHeightChanged();
1191 if (oldHeaderY + oldHeaderHeight > contentY()) {
1192 // If the header is shown because its position
1194 ListItem *firstItem = m_visibleItems.first();
1195 firstItem->setY(firstItem->y() + heightDiff);
1198 // If the header is not on screen, just change the start of the list
1199 // so the viewport is not changed
1206void ListViewWithPageHeader::adjustMinYExtent()
1208 if (m_visibleItems.isEmpty() || (contentHeight() + m_minYExtent < height())) {
1211 qreal nonCreatedHeight = 0;
1212 if (m_firstVisibleIndex != 0) {
1213 // Calculate the average height of items to estimate the position of the list start
1214 const int visibleItems = m_visibleItems.count();
1215 qreal visibleItemsHeight = 0;
1216 Q_FOREACH(ListItem *item, m_visibleItems) {
1217 visibleItemsHeight += item->height();
1219 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
1220// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
1222 const qreal headerHeight = (m_headerItem ? m_headerItem->implicitHeight() : 0);
1223 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + headerHeight;
1224 if (m_minYExtent != 0 && qFuzzyIsNull(m_minYExtent)) {
1226 m_visibleItems.first()->setY(nonCreatedHeight - m_clipItem->y() + headerHeight);
1231ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
1233 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
1234 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
1235 return m_visibleItems[visibleIndexedModelIndex];
1240void ListViewWithPageHeader::layout()
1246 if (!m_visibleItems.isEmpty()) {
1247 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
1248 const qreal visibleTo = contentY() + height() - m_clipItem->y();
1250 qreal pos = m_visibleItems.first()->y();
1252// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
1253 int firstReallyVisibleItem = -1;
1254 int modelIndex = m_firstVisibleIndex;
1255 Q_FOREACH(ListItem *item, m_visibleItems) {
1256 const bool cull = pos + item->height() <= visibleFrom || pos >= visibleTo;
1257 item->setCulled(cull);
1259 if (!cull && firstReallyVisibleItem == -1) {
1260 firstReallyVisibleItem = modelIndex;
1261 if (m_topSectionItem) {
1262 // Positing the top section sticky item is a two step process
1263 // First we set it either we cull it (because it doesn't need to be sticked to the top)
1264 // or stick it to the top
1265 // Then after the loop we'll make sure that if there's another section just below it
1266 // pushed the sticky section up to make it disappear
1267 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
1268 bool showStickySectionItem;
1269 // We need to show the "top section sticky item" when the position at the "top" of the
1270 // viewport is bigger than the start of the position of the first visible item
1271 // i.e. the first visible item starts before the viewport, or when the first
1272 // visible item starts just at the viewport start and it does not have its own section item
1273 if (topSectionStickPos > pos) {
1274 showStickySectionItem = true;
1275 } else if (topSectionStickPos == pos) {
1276 showStickySectionItem = !item->sectionItem();
1278 showStickySectionItem = false;
1280 if (!showStickySectionItem) {
1281 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
1282 if (item->sectionItem()) {
1283 // This seems it should happen since why would we cull the top section
1284 // if the first visible item has no section header? This only happens briefly
1285 // when increasing the height of a list that is at the bottom, the m_topSectionItem
1286 // gets shown shortly in the next polish call
1287 QQuickItemPrivate::get(item->sectionItem())->setCulled(false);
1290 // Update the top sticky section header
1291 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
1292 m_topSectionItem->setProperty("text", section);
1294 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
1295 m_topSectionItem->setY(topSectionStickPos);
1296 int delegateIndex = modelIndex;
1297 // Look for the first index with this section text
1298 while (delegateIndex > 0) {
1299 const QString prevSection = m_delegateModel->stringValue(delegateIndex - 1, m_sectionProperty);
1300 if (prevSection != section)
1304 m_topSectionItem->setProperty("delegateIndex", delegateIndex);
1305 if (item->sectionItem()) {
1306 QQuickItemPrivate::get(item->sectionItem())->setCulled(true);
1311 const qreal clipFrom = visibleFrom + (!item->sectionItem() && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
1312 if (!cull && pos < clipFrom) {
1313 item->m_item->setProperty("heightToClip", clipFrom - pos);
1315 item->m_item->setProperty("heightToClip", QVariant::fromValue<int>(0));
1317// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
1318 pos += item->height();
1322 // Second step of section sticky item positioning
1323 // Look at the next section header, check if it's pushing up the sticky one
1324 if (m_topSectionItem) {
1325 if (firstReallyVisibleItem >= 0) {
1326 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1327 ListItem *item = m_visibleItems[i];
1328 if (item->sectionItem()) {
1329 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1330 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1339 const bool cullHeader = m_headerItem->y() + m_headerItem->height() < contentY();
1340 QQuickItemPrivate::get(m_headerItem)->setCulled(cullHeader);
1345void ListViewWithPageHeader::updatePolish()
1347 // Check we are not being taken down and don't paint anything
1348 // TODO Check if we still need this in 5.2
1349 // For reproduction just inifnite loop testDash or testDashContent
1350 if (!QQmlEngine::contextForObject(this)->parentContext())
1353 Q_FOREACH(ListItem *item, m_itemsToRelease)
1354 reallyReleaseItem(item);
1355 m_itemsToRelease.clear();
1364 if (m_contentHeightDirty) {
1365 qreal contentHeight;
1366 if (m_visibleItems.isEmpty()) {
1367 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1369 const int modelCount = model()->rowCount();
1370 const int visibleItems = m_visibleItems.count();
1371 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1372 qreal nonCreatedHeight = 0;
1373 if (lastValidIndex != modelCount - 1) {
1374 const int visibleItems = m_visibleItems.count();
1375 qreal visibleItemsHeight = 0;
1376 Q_FOREACH(ListItem *item, m_visibleItems) {
1377 visibleItemsHeight += item->height();
1379 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1380 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1382 ListItem *item = m_visibleItems.last();
1383 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1384 if (m_firstVisibleIndex != 0) {
1385 // Make sure that if we are shrinking we tell the view we still fit
1386 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1390 m_contentHeightDirty = false;
1392 if (contentHeight + m_minYExtent < height()) {
1393 // need this since in the previous call to adjustMinYExtent contentHeight is not set yet
1396 m_inContentHeightKeepHeaderShown = m_headerItem && m_headerItem->y() == contentY();
1397 setContentHeight(contentHeight);
1398 m_inContentHeightKeepHeaderShown = false;
1402#include "moc_listviewwithpageheader.cpp"
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list