1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "kitemlistcontroller.h"
26 #include "kitemlistheader_p.h"
27 #include "kitemlistrubberband_p.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistsizehintresolver_p.h"
30 #include "kitemlistviewlayouter_p.h"
31 #include "kitemlistviewanimation_p.h"
32 #include "kitemlistwidget.h"
37 #include <QGraphicsSceneMouseEvent>
39 #include <QPropertyAnimation>
41 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
54 QGraphicsWidget(parent
),
55 m_enabledSelectionToggles(false),
57 m_supportsItemExpanding(false),
58 m_activeTransactions(0),
59 m_endTransactionAnimationHint(Animation
),
64 m_visibleRolesSizes(),
65 m_stretchedVisibleRolesSizes(),
67 m_groupHeaderCreator(0),
72 m_sizeHintResolver(0),
77 m_oldMaximumScrollOffset(0),
79 m_oldMaximumItemOffset(0),
80 m_skipAutoScrollForRubberBand(false),
83 m_autoScrollIncrement(0),
86 m_useHeaderWidths(false)
88 setAcceptHoverEvents(true);
90 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
92 m_layouter
= new KItemListViewLayouter(this);
93 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
95 m_animation
= new KItemListViewAnimation(this);
96 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
97 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
99 m_layoutTimer
= new QTimer(this);
100 m_layoutTimer
->setInterval(300);
101 m_layoutTimer
->setSingleShot(true);
102 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
104 m_rubberBand
= new KItemListRubberBand(this);
105 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
108 KItemListView::~KItemListView()
110 delete m_sizeHintResolver
;
111 m_sizeHintResolver
= 0;
114 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
116 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
117 if (orientation
== previousOrientation
) {
121 m_layouter
->setScrollOrientation(orientation
);
122 m_animation
->setScrollOrientation(orientation
);
123 m_sizeHintResolver
->clearCache();
126 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
127 while (it
.hasNext()) {
129 it
.value()->setScrollOrientation(orientation
);
131 updateGroupHeaderHeight();
135 doLayout(NoAnimation
);
137 onScrollOrientationChanged(orientation
, previousOrientation
);
138 emit
scrollOrientationChanged(orientation
, previousOrientation
);
141 Qt::Orientation
KItemListView::scrollOrientation() const
143 return m_layouter
->scrollOrientation();
146 void KItemListView::setItemSize(const QSizeF
& itemSize
)
148 const QSizeF previousSize
= m_itemSize
;
149 if (itemSize
== previousSize
) {
153 // Skip animations when the number of rows or columns
154 // are changed in the grid layout. Although the animation
155 // engine can handle this usecase, it looks obtrusive.
156 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
158 m_layouter
->itemMargin());
160 const bool updateAlternateBackgrounds
= (m_visibleRoles
.count() > 1) &&
161 (( m_itemSize
.isEmpty() && !itemSize
.isEmpty()) ||
162 (!m_itemSize
.isEmpty() && itemSize
.isEmpty()));
164 m_itemSize
= itemSize
;
166 if (updateAlternateBackgrounds
) {
167 // For an empty item size alternate backgrounds are drawn if more than
168 // one role is shown. Assure that the backgrounds for visible items are
169 // updated when changing the size in this context.
170 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
171 while (it
.hasNext()) {
173 updateAlternateBackgroundForWidget(it
.value());
177 if (itemSize
.isEmpty()) {
178 updateVisibleRolesSizes();
180 m_layouter
->setItemSize(itemSize
);
183 m_sizeHintResolver
->clearCache();
184 doLayout(animate
? Animation
: NoAnimation
);
185 onItemSizeChanged(itemSize
, previousSize
);
188 QSizeF
KItemListView::itemSize() const
193 void KItemListView::setScrollOffset(qreal offset
)
199 const qreal previousOffset
= m_layouter
->scrollOffset();
200 if (offset
== previousOffset
) {
204 m_layouter
->setScrollOffset(offset
);
205 m_animation
->setScrollOffset(offset
);
207 // Don't check whether the m_layoutTimer is active: Changing the
208 // scroll offset must always trigger a synchronous layout, otherwise
209 // the smooth-scrolling might get jerky.
210 doLayout(NoAnimation
);
211 onScrollOffsetChanged(offset
, previousOffset
);
214 qreal
KItemListView::scrollOffset() const
216 return m_layouter
->scrollOffset();
219 qreal
KItemListView::maximumScrollOffset() const
221 return m_layouter
->maximumScrollOffset();
224 void KItemListView::setItemOffset(qreal offset
)
226 if (m_layouter
->itemOffset() == offset
) {
230 m_layouter
->setItemOffset(offset
);
232 m_header
->setPos(-offset
, 0);
235 // Don't check whether the m_layoutTimer is active: Changing the
236 // item offset must always trigger a synchronous layout, otherwise
237 // the smooth-scrolling might get jerky.
238 doLayout(NoAnimation
);
241 qreal
KItemListView::itemOffset() const
243 return m_layouter
->itemOffset();
246 qreal
KItemListView::maximumItemOffset() const
248 return m_layouter
->maximumItemOffset();
251 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
253 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
254 m_visibleRoles
= roles
;
256 const bool updateAlternateBackgrounds
= m_itemSize
.isEmpty() &&
257 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
258 (roles
.count() <= 1 && previousRoles
.count() > 1));
260 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
261 while (it
.hasNext()) {
263 KItemListWidget
* widget
= it
.value();
264 widget
->setVisibleRoles(roles
);
265 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
266 if (updateAlternateBackgrounds
) {
267 updateAlternateBackgroundForWidget(widget
);
271 m_sizeHintResolver
->clearCache();
272 m_layouter
->markAsDirty();
275 m_header
->setVisibleRoles(roles
);
276 m_header
->setVisibleRolesWidths(headerRolesWidths());
277 m_useHeaderWidths
= false;
280 updateVisibleRolesSizes();
281 doLayout(NoAnimation
);
283 onVisibleRolesChanged(roles
, previousRoles
);
286 QList
<QByteArray
> KItemListView::visibleRoles() const
288 return m_visibleRoles
;
291 void KItemListView::setAutoScroll(bool enabled
)
293 if (enabled
&& !m_autoScrollTimer
) {
294 m_autoScrollTimer
= new QTimer(this);
295 m_autoScrollTimer
->setSingleShot(true);
296 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
297 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
298 } else if (!enabled
&& m_autoScrollTimer
) {
299 delete m_autoScrollTimer
;
300 m_autoScrollTimer
= 0;
305 bool KItemListView::autoScroll() const
307 return m_autoScrollTimer
!= 0;
310 void KItemListView::setEnabledSelectionToggles(bool enabled
)
312 if (m_enabledSelectionToggles
!= enabled
) {
313 m_enabledSelectionToggles
= enabled
;
315 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
316 while (it
.hasNext()) {
318 it
.value()->setEnabledSelectionToggle(enabled
);
323 bool KItemListView::enabledSelectionToggles() const
325 return m_enabledSelectionToggles
;
328 KItemListController
* KItemListView::controller() const
333 KItemModelBase
* KItemListView::model() const
338 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
340 m_widgetCreator
= widgetCreator
;
343 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
345 return m_widgetCreator
;
348 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
350 m_groupHeaderCreator
= groupHeaderCreator
;
353 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
355 return m_groupHeaderCreator
;
358 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
360 const KItemListStyleOption previousOption
= m_styleOption
;
361 m_styleOption
= option
;
364 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
365 if (margin
!= m_layouter
->itemMargin()) {
366 // Skip animations when the number of rows or columns
367 // are changed in the grid layout. Although the animation
368 // engine can handle this usecase, it looks obtrusive.
369 animate
= !changesItemGridLayout(m_layouter
->size(),
370 m_layouter
->itemSize(),
372 m_layouter
->setItemMargin(margin
);
376 updateGroupHeaderHeight();
379 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
380 while (it
.hasNext()) {
382 it
.value()->setStyleOption(option
);
385 m_sizeHintResolver
->clearCache();
386 doLayout(animate
? Animation
: NoAnimation
);
388 onStyleOptionChanged(option
, previousOption
);
391 const KItemListStyleOption
& KItemListView::styleOption() const
393 return m_styleOption
;
396 void KItemListView::setGeometry(const QRectF
& rect
)
398 QGraphicsWidget::setGeometry(rect
);
404 const QSizeF newSize
= rect
.size();
405 if (m_itemSize
.isEmpty()) {
406 // The item size is dynamic:
407 // Changing the geometry does not require to do an expensive
408 // update of the visible-roles sizes, only the stretched sizes
409 // need to be adjusted to the new size.
410 updateStretchedVisibleRolesSizes();
412 if (m_useHeaderWidths
) {
413 QSizeF dynamicItemSize
= m_layouter
->itemSize();
415 if (m_itemSize
.width() < 0) {
416 const qreal requiredWidth
= visibleRolesSizesWidthSum();
417 if (newSize
.width() > requiredWidth
) {
418 dynamicItemSize
.setWidth(newSize
.width());
420 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
421 m_header
->resize(headerWidth
, m_header
->size().height());
424 if (m_itemSize
.height() < 0) {
425 const qreal requiredHeight
= visibleRolesSizesHeightSum();
426 if (newSize
.height() > requiredHeight
) {
427 dynamicItemSize
.setHeight(newSize
.height());
429 // TODO: KItemListHeader is not prepared for vertical alignment
432 m_layouter
->setItemSize(dynamicItemSize
);
435 // Triggering a synchronous layout is fine from a performance point of view,
436 // as with dynamic item sizes no moving animation must be done.
437 m_layouter
->setSize(newSize
);
440 const bool animate
= !changesItemGridLayout(newSize
,
441 m_layouter
->itemSize(),
442 m_layouter
->itemMargin());
443 m_layouter
->setSize(newSize
);
446 // Trigger an asynchronous relayout with m_layoutTimer to prevent
447 // performance bottlenecks. If the timer is exceeded, an animated layout
448 // will be triggered.
449 if (!m_layoutTimer
->isActive()) {
450 m_layoutTimer
->start();
453 m_layoutTimer
->stop();
454 doLayout(NoAnimation
);
459 int KItemListView::itemAt(const QPointF
& pos
) const
461 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
462 while (it
.hasNext()) {
465 const KItemListWidget
* widget
= it
.value();
466 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
467 if (widget
->contains(mappedPos
)) {
475 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
477 if (!m_enabledSelectionToggles
) {
481 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
483 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
484 if (!selectionToggleRect
.isEmpty()) {
485 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
486 return selectionToggleRect
.contains(mappedPos
);
492 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
494 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
496 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
497 if (!expansionToggleRect
.isEmpty()) {
498 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
499 return expansionToggleRect
.contains(mappedPos
);
505 int KItemListView::firstVisibleIndex() const
507 return m_layouter
->firstVisibleIndex();
510 int KItemListView::lastVisibleIndex() const
512 return m_layouter
->lastVisibleIndex();
515 QSizeF
KItemListView::itemSizeHint(int index
) const
521 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
523 Q_UNUSED(itemRanges
);
524 return QHash
<QByteArray
, QSizeF
>();
527 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
529 if (m_supportsItemExpanding
!= supportsExpanding
) {
530 m_supportsItemExpanding
= supportsExpanding
;
531 updateSiblingsInformation();
532 onSupportsItemExpandingChanged(supportsExpanding
);
536 bool KItemListView::supportsItemExpanding() const
538 return m_supportsItemExpanding
;
541 QRectF
KItemListView::itemRect(int index
) const
543 return m_layouter
->itemRect(index
);
546 QRectF
KItemListView::itemContextRect(int index
) const
550 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
552 contextRect
= widget
->iconRect() | widget
->textRect();
553 contextRect
.translate(itemRect(index
).topLeft());
559 void KItemListView::scrollToItem(int index
)
561 QRectF viewGeometry
= geometry();
563 const qreal headerHeight
= m_header
->size().height();
564 viewGeometry
.adjust(0, headerHeight
, 0, 0);
566 const QRectF currentRect
= itemRect(index
);
568 if (!viewGeometry
.contains(currentRect
)) {
569 qreal newOffset
= scrollOffset();
570 if (scrollOrientation() == Qt::Vertical
) {
571 if (currentRect
.top() < viewGeometry
.top()) {
572 newOffset
+= currentRect
.top() - viewGeometry
.top();
573 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
574 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
577 if (currentRect
.left() < viewGeometry
.left()) {
578 newOffset
+= currentRect
.left() - viewGeometry
.left();
579 } else if (currentRect
.right() > viewGeometry
.right()) {
580 newOffset
+= currentRect
.right() - viewGeometry
.right();
584 if (newOffset
!= scrollOffset()) {
585 emit
scrollTo(newOffset
);
590 void KItemListView::beginTransaction()
592 ++m_activeTransactions
;
593 if (m_activeTransactions
== 1) {
594 onTransactionBegin();
598 void KItemListView::endTransaction()
600 --m_activeTransactions
;
601 if (m_activeTransactions
< 0) {
602 m_activeTransactions
= 0;
603 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
606 if (m_activeTransactions
== 0) {
608 doLayout(m_endTransactionAnimationHint
);
609 m_endTransactionAnimationHint
= Animation
;
613 bool KItemListView::isTransactionActive() const
615 return m_activeTransactions
> 0;
618 void KItemListView::setHeaderShown(bool show
)
621 if (show
&& !m_header
) {
622 m_header
= new KItemListHeader(this);
623 m_header
->setPos(0, 0);
624 m_header
->setModel(m_model
);
625 m_header
->setVisibleRoles(m_visibleRoles
);
626 m_header
->setVisibleRolesWidths(headerRolesWidths());
627 m_header
->setZValue(1);
629 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
630 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
631 connect(m_header
, SIGNAL(visibleRoleMoved(QByteArray
,int,int)),
632 this, SLOT(slotVisibleRoleMoved(QByteArray
,int,int)));
633 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
634 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
635 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
636 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
638 m_useHeaderWidths
= false;
640 m_layouter
->setHeaderHeight(m_header
->size().height());
641 } else if (!show
&& m_header
) {
644 m_useHeaderWidths
= false;
645 m_layouter
->setHeaderHeight(0);
649 bool KItemListView::isHeaderShown() const
651 return m_header
!= 0;
654 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
660 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
662 QGraphicsWidget::paint(painter
, option
, widget
);
664 if (m_rubberBand
->isActive()) {
665 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
666 m_rubberBand
->endPosition()).normalized();
668 const QPointF topLeft
= rubberBandRect
.topLeft();
669 if (scrollOrientation() == Qt::Vertical
) {
670 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
672 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
675 QStyleOptionRubberBand opt
;
676 opt
.initFrom(widget
);
677 opt
.shape
= QRubberBand::Rectangle
;
679 opt
.rect
= rubberBandRect
.toRect();
680 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
684 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
689 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
691 Q_UNUSED(changedRoles
);
695 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
701 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
707 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
713 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
719 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
725 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
731 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
737 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
739 Q_UNUSED(supportsExpanding
);
742 void KItemListView::onTransactionBegin()
746 void KItemListView::onTransactionEnd()
750 bool KItemListView::event(QEvent
* event
)
752 // Forward all events to the controller and handle them there
753 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
757 return QGraphicsWidget::event(event
);
760 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
762 m_mousePos
= transform().map(event
->pos());
766 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
768 QGraphicsWidget::mouseMoveEvent(event
);
770 m_mousePos
= transform().map(event
->pos());
771 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
772 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
776 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
778 event
->setAccepted(true);
782 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
784 QGraphicsWidget::dragMoveEvent(event
);
786 m_mousePos
= transform().map(event
->pos());
787 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
788 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
792 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
794 QGraphicsWidget::dragLeaveEvent(event
);
795 setAutoScroll(false);
798 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
800 QGraphicsWidget::dropEvent(event
);
801 setAutoScroll(false);
804 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
806 return m_visibleItems
.values();
809 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
811 updateVisibleRolesSizes(itemRanges
);
813 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
814 if (hasMultipleRanges
) {
818 m_layouter
->markAsDirty();
820 int previouslyInsertedCount
= 0;
821 foreach (const KItemRange
& range
, itemRanges
) {
822 // range.index is related to the model before anything has been inserted.
823 // As in each loop the current item-range gets inserted the index must
824 // be increased by the already previously inserted items.
825 const int index
= range
.index
+ previouslyInsertedCount
;
826 const int count
= range
.count
;
827 if (index
< 0 || count
<= 0) {
828 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
831 previouslyInsertedCount
+= count
;
833 m_sizeHintResolver
->itemsInserted(index
, count
);
835 // Determine which visible items must be moved
836 QList
<int> itemsToMove
;
837 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
838 while (it
.hasNext()) {
840 const int visibleItemIndex
= it
.key();
841 if (visibleItemIndex
>= index
) {
842 itemsToMove
.append(visibleItemIndex
);
846 // Update the indexes of all KItemListWidget instances that are located
847 // after the inserted items. It is important to adjust the indexes in the order
848 // from the highest index to the lowest index to prevent overlaps when setting the new index.
850 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
851 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
853 const int newIndex
= widget
->index() + count
;
854 if (hasMultipleRanges
) {
855 setWidgetIndex(widget
, newIndex
);
857 // Try to animate the moving of the item
858 moveWidgetToIndex(widget
, newIndex
);
862 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
863 // Check whether a scrollbar is required to show the inserted items. In this case
864 // the size of the layouter will be decreased before calling doLayout(): This prevents
865 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
866 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
867 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
868 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
869 if (decreaseLayouterSize
) {
870 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
871 QSizeF layouterSize
= m_layouter
->size();
872 if (verticalScrollOrientation
) {
873 layouterSize
.rwidth() -= scrollBarExtent
;
875 layouterSize
.rheight() -= scrollBarExtent
;
877 m_layouter
->setSize(layouterSize
);
881 if (!hasMultipleRanges
) {
882 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
883 updateSiblingsInformation();
888 m_controller
->selectionManager()->itemsInserted(itemRanges
);
891 if (hasMultipleRanges
) {
893 // Important: Don't read any m_layouter-property inside the for-loop in case if
894 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
895 // updated in each loop-cycle and has only a consistent state after the loop.
896 Q_ASSERT(m_layouter
->isDirty());
898 m_endTransactionAnimationHint
= NoAnimation
;
900 updateSiblingsInformation();
904 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
906 updateVisibleRolesSizes();
908 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
909 if (hasMultipleRanges
) {
913 m_layouter
->markAsDirty();
915 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
916 const KItemRange
& range
= itemRanges
.at(i
);
917 const int index
= range
.index
;
918 const int count
= range
.count
;
919 if (index
< 0 || count
<= 0) {
920 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
924 m_sizeHintResolver
->itemsRemoved(index
, count
);
926 const int firstRemovedIndex
= index
;
927 const int lastRemovedIndex
= index
+ count
- 1;
928 const int lastIndex
= m_model
->count() + count
- 1;
930 // Remove all KItemListWidget instances that got deleted
931 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
932 KItemListWidget
* widget
= m_visibleItems
.value(i
);
937 m_animation
->stop(widget
);
938 // Stopping the animation might lead to recycling the widget if
939 // it is invisible (see slotAnimationFinished()).
940 // Check again whether it is still visible:
941 if (!m_visibleItems
.contains(i
)) {
945 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
946 // Remove the widget without animation
947 recycleWidget(widget
);
949 // Animate the removing of the items. Special case: When removing an item there
950 // is no valid model index available anymore. For the
951 // remove-animation the item gets removed from m_visibleItems but the widget
952 // will stay alive until the animation has been finished and will
953 // be recycled (deleted) in KItemListView::slotAnimationFinished().
954 m_visibleItems
.remove(i
);
955 widget
->setIndex(-1);
956 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
960 // Update the indexes of all KItemListWidget instances that are located
961 // after the deleted items
962 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
963 KItemListWidget
* widget
= m_visibleItems
.value(i
);
965 const int newIndex
= i
- count
;
966 if (hasMultipleRanges
) {
967 setWidgetIndex(widget
, newIndex
);
969 // Try to animate the moving of the item
970 moveWidgetToIndex(widget
, newIndex
);
975 if (!hasMultipleRanges
) {
976 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
977 // assumes an updated geometry. If items are removed during an active transaction,
978 // the transaction will be temporary deactivated so that doLayout() triggers a
979 // geometry update if necessary.
980 const int activeTransactions
= m_activeTransactions
;
981 m_activeTransactions
= 0;
982 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
983 m_activeTransactions
= activeTransactions
;
984 updateSiblingsInformation();
989 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
992 if (hasMultipleRanges
) {
994 // Important: Don't read any m_layouter-property inside the for-loop in case if
995 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
996 // updated in each loop-cycle and has only a consistent state after the loop.
997 Q_ASSERT(m_layouter
->isDirty());
999 m_endTransactionAnimationHint
= NoAnimation
;
1001 updateSiblingsInformation();
1005 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1007 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1008 m_layouter
->markAsDirty();
1011 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1014 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1015 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1017 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1018 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1020 updateWidgetProperties(widget
, index
);
1021 initializeItemListWidget(widget
);
1025 doLayout(NoAnimation
);
1026 updateSiblingsInformation();
1029 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1030 const QSet
<QByteArray
>& roles
)
1032 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1033 if (updateSizeHints
) {
1034 updateVisibleRolesSizes(itemRanges
);
1037 foreach (const KItemRange
& itemRange
, itemRanges
) {
1038 const int index
= itemRange
.index
;
1039 const int count
= itemRange
.count
;
1041 if (updateSizeHints
) {
1042 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1043 m_layouter
->markAsDirty();
1045 if (!m_layoutTimer
->isActive()) {
1046 m_layoutTimer
->start();
1050 // Apply the changed roles to the visible item-widgets
1051 const int lastIndex
= index
+ count
- 1;
1052 for (int i
= index
; i
<= lastIndex
; ++i
) {
1053 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1055 widget
->setData(m_model
->data(i
), roles
);
1059 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1060 // The sort-role has been changed which might result
1061 // in modified group headers
1062 updateVisibleGroupHeaders();
1063 doLayout(NoAnimation
);
1068 void KItemListView::slotGroupedSortingChanged(bool current
)
1070 m_grouped
= current
;
1071 m_layouter
->markAsDirty();
1074 updateGroupHeaderHeight();
1076 // Clear all visible headers
1077 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1078 while (it
.hasNext()) {
1080 recycleGroupHeaderForWidget(it
.key());
1082 Q_ASSERT(m_visibleGroups
.isEmpty());
1085 if (useAlternateBackgrounds()) {
1086 // Changing the group mode requires to update the alternate backgrounds
1087 // as with the enabled group mode the altering is done on base of the first
1089 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1090 while (it
.hasNext()) {
1092 updateAlternateBackgroundForWidget(it
.value());
1096 updateSiblingsInformation();
1097 doLayout(NoAnimation
);
1100 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1105 updateVisibleGroupHeaders();
1106 doLayout(NoAnimation
);
1110 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1115 updateVisibleGroupHeaders();
1116 doLayout(NoAnimation
);
1120 void KItemListView::slotCurrentChanged(int current
, int previous
)
1124 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1125 if (previousWidget
) {
1126 previousWidget
->setCurrent(false);
1129 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1130 if (currentWidget
) {
1131 currentWidget
->setCurrent(true);
1135 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1139 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1140 while (it
.hasNext()) {
1142 const int index
= it
.key();
1143 KItemListWidget
* widget
= it
.value();
1144 widget
->setSelected(current
.contains(index
));
1148 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1149 KItemListViewAnimation::AnimationType type
)
1151 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1152 Q_ASSERT(itemListWidget
);
1155 case KItemListViewAnimation::DeleteAnimation
: {
1156 // As we recycle the widget in this case it is important to assure that no
1157 // other animation has been started. This is a convention in KItemListView and
1158 // not a requirement defined by KItemListViewAnimation.
1159 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1161 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1162 // by m_visibleWidgets and must be deleted manually after the animation has
1164 recycleGroupHeaderForWidget(itemListWidget
);
1165 m_widgetCreator
->recycle(itemListWidget
);
1169 case KItemListViewAnimation::CreateAnimation
:
1170 case KItemListViewAnimation::MovingAnimation
:
1171 case KItemListViewAnimation::ResizeAnimation
: {
1172 const int index
= itemListWidget
->index();
1173 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1174 (index
> m_layouter
->lastVisibleIndex());
1175 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1176 recycleWidget(itemListWidget
);
1185 void KItemListView::slotLayoutTimerFinished()
1187 m_layouter
->setSize(geometry().size());
1188 doLayout(Animation
);
1191 void KItemListView::slotRubberBandPosChanged()
1196 void KItemListView::slotRubberBandActivationChanged(bool active
)
1199 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1200 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1201 m_skipAutoScrollForRubberBand
= true;
1203 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1204 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1205 m_skipAutoScrollForRubberBand
= false;
1211 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1213 qreal previousWidth
)
1215 Q_UNUSED(previousWidth
);
1217 m_useHeaderWidths
= true;
1219 if (m_visibleRolesSizes
.contains(role
)) {
1220 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1221 roleSize
.setWidth(currentWidth
);
1222 m_visibleRolesSizes
.insert(role
, roleSize
);
1223 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1225 // Apply the new size to the layouter
1226 QSizeF dynamicItemSize
= m_itemSize
;
1227 if (dynamicItemSize
.width() < 0) {
1228 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1229 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1231 if (dynamicItemSize
.height() < 0) {
1232 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1233 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1236 m_layouter
->setItemSize(dynamicItemSize
);
1238 // Update the role sizes for all visible widgets
1239 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1240 while (it
.hasNext()) {
1242 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1244 doLayout(NoAnimation
);
1248 void KItemListView::slotVisibleRoleMoved(const QByteArray
& role
,
1252 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1254 const QList
<QByteArray
> previous
= m_visibleRoles
;
1256 QList
<QByteArray
> current
= m_visibleRoles
;
1257 current
.removeAt(previousIndex
);
1258 current
.insert(currentIndex
, role
);
1260 setVisibleRoles(current
);
1262 emit
visibleRolesChanged(current
, previous
);
1265 void KItemListView::triggerAutoScrolling()
1267 if (!m_autoScrollTimer
) {
1272 int visibleSize
= 0;
1273 if (scrollOrientation() == Qt::Vertical
) {
1274 pos
= m_mousePos
.y();
1275 visibleSize
= size().height();
1277 pos
= m_mousePos
.x();
1278 visibleSize
= size().width();
1281 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1282 m_autoScrollIncrement
= 0;
1285 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1286 if (m_autoScrollIncrement
== 0) {
1287 // The mouse position is not above an autoscroll margin (the autoscroll timer
1288 // will be restarted in mouseMoveEvent())
1289 m_autoScrollTimer
->stop();
1293 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1294 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1295 // if the direction of the rubberband is similar to the autoscroll direction. This
1296 // prevents that starting to create a rubberband within the autoscroll margins starts
1297 // an autoscrolling.
1299 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1300 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1301 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1302 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1303 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1304 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1305 // been moved up although the autoscroll direction might be down)
1306 m_autoScrollTimer
->stop();
1311 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1312 // the autoscrolling may not get skipped anymore until a new rubberband is created
1313 m_skipAutoScrollForRubberBand
= false;
1315 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1316 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1317 setScrollOffset(newScrollOffset
);
1319 // Trigger the autoscroll timer which will periodically call
1320 // triggerAutoScrolling()
1321 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1324 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1326 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1328 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1329 Q_ASSERT(groupHeader
);
1330 updateGroupHeaderLayout(widget
);
1333 void KItemListView::setController(KItemListController
* controller
)
1335 if (m_controller
!= controller
) {
1336 KItemListController
* previous
= m_controller
;
1338 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1339 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1340 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1343 m_controller
= controller
;
1346 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1347 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1348 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1351 onControllerChanged(controller
, previous
);
1355 void KItemListView::setModel(KItemModelBase
* model
)
1357 if (m_model
== model
) {
1361 KItemModelBase
* previous
= m_model
;
1364 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1365 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1366 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1367 this, SLOT(slotItemsInserted(KItemRangeList
)));
1368 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1369 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1370 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1371 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1372 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1373 this, SLOT(slotGroupedSortingChanged(bool)));
1374 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1375 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1376 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1377 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1381 m_layouter
->setModel(model
);
1382 m_grouped
= model
->groupedSorting();
1385 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1386 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1387 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1388 this, SLOT(slotItemsInserted(KItemRangeList
)));
1389 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1390 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1391 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1392 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1393 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1394 this, SLOT(slotGroupedSortingChanged(bool)));
1395 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1396 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1397 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1398 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1401 onModelChanged(model
, previous
);
1404 KItemListRubberBand
* KItemListView::rubberBand() const
1406 return m_rubberBand
;
1409 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1411 if (m_layoutTimer
->isActive()) {
1412 m_layoutTimer
->stop();
1415 if (m_activeTransactions
> 0) {
1416 if (hint
== NoAnimation
) {
1417 // As soon as at least one property change should be done without animation,
1418 // the whole transaction will be marked as not animated.
1419 m_endTransactionAnimationHint
= NoAnimation
;
1424 if (!m_model
|| m_model
->count() < 0) {
1428 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1429 if (firstVisibleIndex
< 0) {
1430 emitOffsetChanges();
1434 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1435 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1436 // is still shown if the maximum offset got decreased.
1437 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1438 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1439 if (scrollOffset() > maxOffsetToShowFullRange
) {
1440 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1441 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1444 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1446 int firstSibblingIndex
= -1;
1447 int lastSibblingIndex
= -1;
1448 const bool supportsExpanding
= supportsItemExpanding();
1450 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1452 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1453 // instances from invisible items are reused. If no reusable items are
1454 // found then new KItemListWidget instances get created.
1455 const bool animate
= (hint
== Animation
);
1456 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1457 bool applyNewPos
= true;
1458 bool wasHidden
= false;
1460 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1461 const QPointF newPos
= itemBounds
.topLeft();
1462 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1465 if (!reusableItems
.isEmpty()) {
1466 // Reuse a KItemListWidget instance from an invisible item
1467 const int oldIndex
= reusableItems
.takeLast();
1468 widget
= m_visibleItems
.value(oldIndex
);
1469 setWidgetIndex(widget
, i
);
1470 updateWidgetProperties(widget
, i
);
1471 initializeItemListWidget(widget
);
1473 // No reusable KItemListWidget instance is available, create a new one
1474 widget
= createWidget(i
);
1476 widget
->resize(itemBounds
.size());
1478 if (animate
&& changedCount
< 0) {
1479 // Items have been deleted, move the created item to the
1480 // imaginary old position. They will get animated to the new position
1482 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1483 if (itemRect
.isEmpty()) {
1484 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1485 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1486 widget
->setPos(invisibleOldPos
);
1488 widget
->setPos(itemRect
.topLeft());
1490 applyNewPos
= false;
1493 if (supportsExpanding
&& changedCount
== 0) {
1494 if (firstSibblingIndex
< 0) {
1495 firstSibblingIndex
= i
;
1497 lastSibblingIndex
= i
;
1502 const bool itemsRemoved
= (changedCount
< 0);
1503 const bool itemsInserted
= (changedCount
> 0);
1504 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1505 // The item is located after the removed items. Animate the moving of the position.
1506 applyNewPos
= !moveWidget(widget
, newPos
);
1507 } else if (itemsInserted
&& i
>= changedIndex
) {
1508 // The item is located after the first inserted item
1509 if (i
<= changedIndex
+ changedCount
- 1) {
1510 // The item is an inserted item. Animate the appearing of the item.
1511 // For performance reasons no animation is done when changedCount is equal
1512 // to all available items.
1513 if (changedCount
< m_model
->count()) {
1514 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1516 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1517 // The item was already there before, so animate the moving of the position.
1518 // No moving animation is done if the item is animated by a create animation: This
1519 // prevents a "move animation mess" when inserting several ranges in parallel.
1520 applyNewPos
= !moveWidget(widget
, newPos
);
1522 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1523 // The size of the view might have been changed. Animate the moving of the position.
1524 applyNewPos
= !moveWidget(widget
, newPos
);
1527 m_animation
->stop(widget
);
1531 widget
->setPos(newPos
);
1534 Q_ASSERT(widget
->index() == i
);
1535 widget
->setVisible(true);
1537 if (widget
->size() != itemBounds
.size()) {
1538 // Resize the widget for the item to the changed size.
1540 // If a dynamic item size is used then no animation is done in the direction
1541 // of the dynamic size.
1542 if (m_itemSize
.width() <= 0) {
1543 // The width is dynamic, apply the new width without animation.
1544 widget
->resize(itemBounds
.width(), widget
->size().height());
1545 } else if (m_itemSize
.height() <= 0) {
1546 // The height is dynamic, apply the new height without animation.
1547 widget
->resize(widget
->size().width(), itemBounds
.height());
1549 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1551 widget
->resize(itemBounds
.size());
1555 // Updating the cell-information must be done as last step: The decision whether the
1556 // moving-animation should be started at all is based on the previous cell-information.
1557 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1558 m_visibleCells
.insert(i
, cell
);
1561 // Delete invisible KItemListWidget instances that have not been reused
1562 foreach (int index
, reusableItems
) {
1563 recycleWidget(m_visibleItems
.value(index
));
1566 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1567 Q_ASSERT(lastSibblingIndex
>= 0);
1568 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1572 // Update the layout of all visible group headers
1573 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1574 while (it
.hasNext()) {
1576 updateGroupHeaderLayout(it
.key());
1580 emitOffsetChanges();
1583 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1584 int lastVisibleIndex
,
1585 LayoutAnimationHint hint
)
1587 // Determine all items that are completely invisible and might be
1588 // reused for items that just got (at least partly) visible. If the
1589 // animation hint is set to 'Animation' items that do e.g. an animated
1590 // moving of their position are not marked as invisible: This assures
1591 // that a scrolling inside the view can be done without breaking an animation.
1595 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1596 while (it
.hasNext()) {
1599 KItemListWidget
* widget
= it
.value();
1600 const int index
= widget
->index();
1601 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1604 if (m_animation
->isStarted(widget
)) {
1605 if (hint
== NoAnimation
) {
1606 // Stopping the animation will call KItemListView::slotAnimationFinished()
1607 // and the widget will be recycled if necessary there.
1608 m_animation
->stop(widget
);
1611 widget
->setVisible(false);
1612 items
.append(index
);
1615 recycleGroupHeaderForWidget(widget
);
1624 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1626 if (widget
->pos() == newPos
) {
1630 bool startMovingAnim
= false;
1632 // When having a grid the moving-animation should only be started, if it is done within
1633 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1634 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1635 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1636 const int index
= widget
->index();
1637 const Cell cell
= m_visibleCells
.value(index
);
1638 if (cell
.column
>= 0 && cell
.row
>= 0) {
1639 if (scrollOrientation() == Qt::Vertical
) {
1640 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1642 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1646 if (startMovingAnim
) {
1647 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1651 m_animation
->stop(widget
);
1652 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1656 void KItemListView::emitOffsetChanges()
1658 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1659 if (m_oldScrollOffset
!= newScrollOffset
) {
1660 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1661 m_oldScrollOffset
= newScrollOffset
;
1664 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1665 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1666 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1667 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1670 const qreal newItemOffset
= m_layouter
->itemOffset();
1671 if (m_oldItemOffset
!= newItemOffset
) {
1672 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1673 m_oldItemOffset
= newItemOffset
;
1676 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1677 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1678 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1679 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1683 KItemListWidget
* KItemListView::createWidget(int index
)
1685 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1686 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1688 m_visibleItems
.insert(index
, widget
);
1689 m_visibleCells
.insert(index
, Cell());
1690 updateWidgetProperties(widget
, index
);
1691 initializeItemListWidget(widget
);
1695 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1698 recycleGroupHeaderForWidget(widget
);
1701 const int index
= widget
->index();
1702 m_visibleItems
.remove(index
);
1703 m_visibleCells
.remove(index
);
1705 m_widgetCreator
->recycle(widget
);
1708 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1710 const int oldIndex
= widget
->index();
1711 m_visibleItems
.remove(oldIndex
);
1712 m_visibleCells
.remove(oldIndex
);
1714 m_visibleItems
.insert(index
, widget
);
1715 m_visibleCells
.insert(index
, Cell());
1717 widget
->setIndex(index
);
1720 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1722 const int oldIndex
= widget
->index();
1723 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1725 setWidgetIndex(widget
, index
);
1727 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1728 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1729 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1730 (!vertical
&& oldCell
.column
== newCell
.column
);
1732 m_visibleCells
.insert(index
, newCell
);
1736 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1739 case LayouterSize
: m_layouter
->setSize(size
); break;
1740 case ItemSize
: m_layouter
->setItemSize(size
); break;
1745 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1747 widget
->setVisibleRoles(m_visibleRoles
);
1748 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1749 widget
->setStyleOption(m_styleOption
);
1751 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1752 widget
->setCurrent(index
== selectionManager
->currentItem());
1753 widget
->setSelected(selectionManager
->isSelected(index
));
1754 widget
->setHovered(false);
1755 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1756 widget
->setIndex(index
);
1757 widget
->setData(m_model
->data(index
));
1758 widget
->setSiblingsInformation(QBitArray());
1759 updateAlternateBackgroundForWidget(widget
);
1762 updateGroupHeaderForWidget(widget
);
1766 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1768 Q_ASSERT(m_grouped
);
1770 const int index
= widget
->index();
1771 if (!m_layouter
->isFirstGroupItem(index
)) {
1772 // The widget does not represent the first item of a group
1773 // and hence requires no header
1774 recycleGroupHeaderForWidget(widget
);
1778 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1779 if (groups
.isEmpty()) {
1783 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1785 groupHeader
= m_groupHeaderCreator
->create(this);
1786 groupHeader
->setParentItem(widget
);
1787 m_visibleGroups
.insert(widget
, groupHeader
);
1788 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1790 Q_ASSERT(groupHeader
->parentItem() == widget
);
1792 const int groupIndex
= groupIndexForItem(index
);
1793 Q_ASSERT(groupIndex
>= 0);
1794 groupHeader
->setData(groups
.at(groupIndex
).second
);
1795 groupHeader
->setRole(model()->sortRole());
1796 groupHeader
->setStyleOption(m_styleOption
);
1797 groupHeader
->setScrollOrientation(scrollOrientation());
1798 groupHeader
->setItemIndex(index
);
1800 groupHeader
->show();
1803 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1805 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1806 Q_ASSERT(groupHeader
);
1808 const int index
= widget
->index();
1809 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1810 const QRectF itemRect
= m_layouter
->itemRect(index
);
1812 // The group-header is a child of the itemlist widget. Translate the
1813 // group header position to the relative position.
1814 if (scrollOrientation() == Qt::Vertical
) {
1815 // In the vertical scroll orientation the group header should always span
1816 // the whole width no matter which temporary position the parent widget
1817 // has. In this case the x-position and width will be adjusted manually.
1818 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1819 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1821 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1822 groupHeader
->resize(groupHeaderRect
.size());
1826 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1828 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1830 header
->setParentItem(0);
1831 m_groupHeaderCreator
->recycle(header
);
1832 m_visibleGroups
.remove(widget
);
1833 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1837 void KItemListView::updateVisibleGroupHeaders()
1839 Q_ASSERT(m_grouped
);
1840 m_layouter
->markAsDirty();
1842 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1843 while (it
.hasNext()) {
1845 updateGroupHeaderForWidget(it
.value());
1849 int KItemListView::groupIndexForItem(int index
) const
1851 Q_ASSERT(m_grouped
);
1853 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1854 if (groups
.isEmpty()) {
1859 int max
= groups
.count() - 1;
1862 mid
= (min
+ max
) / 2;
1863 if (index
> groups
[mid
].first
) {
1868 } while (groups
[mid
].first
!= index
&& min
<= max
);
1871 while (groups
[mid
].first
> index
&& mid
> 0) {
1879 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1881 bool enabled
= useAlternateBackgrounds();
1883 const int index
= widget
->index();
1884 enabled
= (index
& 0x1) > 0;
1886 const int groupIndex
= groupIndexForItem(index
);
1887 if (groupIndex
>= 0) {
1888 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1889 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1890 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1891 enabled
= (relativeIndex
& 0x1) > 0;
1895 widget
->setAlternateBackground(enabled
);
1898 bool KItemListView::useAlternateBackgrounds() const
1900 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1903 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1905 QHash
<QByteArray
, qreal
> rolesWidths
;
1907 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1908 while (it
.hasNext()) {
1910 rolesWidths
.insert(it
.key(), it
.value().width());
1916 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1918 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1922 const int itemCount
= m_model
->count();
1923 int rangesItemCount
= 0;
1924 foreach (const KItemRange
& range
, itemRanges
) {
1925 rangesItemCount
+= range
.count
;
1928 if (itemCount
== rangesItemCount
) {
1929 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1931 // Assure the the sizes are not smaller than the minimum defined by the header
1932 // TODO: Currently only implemented for a top-aligned header
1933 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1934 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1935 while (it
.hasNext()) {
1937 const QSizeF
& size
= it
.value();
1938 if (size
.width() < minHeaderRoleWidth
) {
1939 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1940 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1945 // Only a sub range of the roles need to be determined.
1946 // The chances are good that the sizes of the sub ranges
1947 // already fit into the available sizes and hence no
1948 // expensive update might be required.
1949 bool updateRequired
= false;
1951 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1952 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1953 while (it
.hasNext()) {
1955 const QByteArray
& role
= it
.key();
1956 const QSizeF
& updatedSize
= it
.value();
1957 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1958 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1959 m_visibleRolesSizes
.insert(role
, updatedSize
);
1960 updateRequired
= true;
1964 if (!updateRequired
) {
1965 // All the updated sizes are smaller than the current sizes and no change
1966 // of the stretched roles-widths is required
1971 updateStretchedVisibleRolesSizes();
1974 void KItemListView::updateVisibleRolesSizes()
1980 const int itemCount
= m_model
->count();
1981 if (itemCount
> 0) {
1982 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1986 void KItemListView::updateStretchedVisibleRolesSizes()
1988 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1992 // Calculate the maximum size of an item by considering the
1993 // visible role sizes and apply them to the layouter. If the
1994 // size does not use the available view-size it the size of the
1995 // first role will get stretched.
1996 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1997 const QByteArray role
= m_visibleRoles
.first();
1998 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
2000 QSizeF dynamicItemSize
= m_itemSize
;
2002 if (dynamicItemSize
.width() <= 0) {
2003 const qreal requiredWidth
= visibleRolesSizesWidthSum();
2004 const qreal availableWidth
= size().width();
2005 if (requiredWidth
< availableWidth
) {
2006 // Stretch the first role to use the whole width for the item
2007 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
2008 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
2010 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
2013 if (dynamicItemSize
.height() <= 0) {
2014 const qreal requiredHeight
= visibleRolesSizesHeightSum();
2015 const qreal availableHeight
= size().height();
2016 if (requiredHeight
< availableHeight
) {
2017 // Stretch the first role to use the whole height for the item
2018 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
2019 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
2021 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
2024 m_layouter
->setItemSize(dynamicItemSize
);
2027 m_header
->setVisibleRolesWidths(headerRolesWidths());
2028 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
2031 // Update the role sizes for all visible widgets
2032 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2033 while (it
.hasNext()) {
2035 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
2039 qreal
KItemListView::visibleRolesSizesWidthSum() const
2042 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2043 while (it
.hasNext()) {
2045 widthSum
+= it
.value().width();
2050 qreal
KItemListView::visibleRolesSizesHeightSum() const
2052 qreal heightSum
= 0;
2053 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2054 while (it
.hasNext()) {
2056 heightSum
+= it
.value().height();
2061 QRectF
KItemListView::headerBoundaries() const
2063 return m_header
? m_header
->geometry() : QRectF();
2066 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2067 const QSizeF
& newItemSize
,
2068 const QSizeF
& newItemMargin
) const
2070 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2074 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2075 const qreal itemWidth
= m_layouter
->itemSize().width();
2076 if (itemWidth
> 0) {
2077 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2078 newItemSize
.width(),
2079 newItemMargin
.width());
2080 if (m_model
->count() > newColumnCount
) {
2081 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2083 m_layouter
->itemMargin().width());
2084 return oldColumnCount
!= newColumnCount
;
2088 const qreal itemHeight
= m_layouter
->itemSize().height();
2089 if (itemHeight
> 0) {
2090 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2091 newItemSize
.height(),
2092 newItemMargin
.height());
2093 if (m_model
->count() > newRowCount
) {
2094 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2096 m_layouter
->itemMargin().height());
2097 return oldRowCount
!= newRowCount
;
2105 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2107 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2111 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2112 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2113 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2114 // Only animate if up to 2/3 of a row or column are inserted or removed
2115 return changedItemCount
<= maximum
* 2 / 3;
2119 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2121 const QSizeF oldSize
= m_layouter
->size();
2123 m_layouter
->setSize(size
);
2124 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2125 m_layouter
->setSize(oldSize
);
2127 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2128 : maxOffset
> size
.width();
2131 void KItemListView::updateGroupHeaderHeight()
2133 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2134 qreal groupHeaderMargin
= 0;
2136 if (scrollOrientation() == Qt::Horizontal
) {
2137 // The vertical margin above and below the header should be
2138 // equal to the horizontal margin, not the vertical margin
2139 // from m_styleOption.
2140 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2141 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2142 } else if (m_itemSize
.isEmpty()){
2143 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2144 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2146 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2147 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2149 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2150 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2152 updateVisibleGroupHeaders();
2155 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2157 if (!supportsItemExpanding() || !m_model
) {
2161 if (firstIndex
< 0 || lastIndex
< 0) {
2162 firstIndex
= m_layouter
->firstVisibleIndex();
2163 lastIndex
= m_layouter
->lastVisibleIndex();
2165 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2166 lastIndex
>= m_layouter
->firstVisibleIndex());
2167 if (!isRangeVisible
) {
2172 int previousParents
= 0;
2173 QBitArray previousSiblings
;
2175 // The rootIndex describes the first index where the siblings get
2176 // calculated from. For the calculation the upper most parent item
2177 // is required. For performance reasons it is checked first whether
2178 // the visible items before or after the current range already
2179 // contain a siblings information which can be used as base.
2180 int rootIndex
= firstIndex
;
2182 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2184 // There is no visible widget before the range, check whether there
2185 // is one after the range:
2186 widget
= m_visibleItems
.value(lastIndex
+ 1);
2188 // The sibling information of the widget may only be used if
2189 // all items of the range have the same number of parents.
2190 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2191 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2192 if (m_model
->expandedParentsCount(i
) != parents
) {
2201 // Performance optimization: Use the sibling information of the visible
2202 // widget beside the given range.
2203 previousSiblings
= widget
->siblingsInformation();
2204 if (previousSiblings
.isEmpty()) {
2207 previousParents
= previousSiblings
.count() - 1;
2208 previousSiblings
.truncate(previousParents
);
2210 // Potentially slow path: Go back to the upper most parent of firstIndex
2211 // to be able to calculate the initial value for the siblings.
2212 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2217 Q_ASSERT(previousParents
>= 0);
2218 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2219 // Update the parent-siblings in case if the current item represents
2220 // a child or an upper parent.
2221 const int currentParents
= m_model
->expandedParentsCount(i
);
2222 Q_ASSERT(currentParents
>= 0);
2223 if (previousParents
< currentParents
) {
2224 previousParents
= currentParents
;
2225 previousSiblings
.resize(currentParents
);
2226 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2227 } else if (previousParents
> currentParents
) {
2228 previousParents
= currentParents
;
2229 previousSiblings
.truncate(currentParents
);
2232 if (i
>= firstIndex
) {
2233 // The index represents a visible item. Apply the parent-siblings
2234 // and update the sibling of the current item.
2235 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2240 QBitArray siblings
= previousSiblings
;
2241 siblings
.resize(siblings
.count() + 1);
2242 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2244 widget
->setSiblingsInformation(siblings
);
2249 bool KItemListView::hasSiblingSuccessor(int index
) const
2251 bool hasSuccessor
= false;
2252 const int parentsCount
= m_model
->expandedParentsCount(index
);
2253 int successorIndex
= index
+ 1;
2255 // Search the next sibling
2256 const int itemCount
= m_model
->count();
2257 while (successorIndex
< itemCount
) {
2258 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2259 if (currentParentsCount
== parentsCount
) {
2260 hasSuccessor
= true;
2262 } else if (currentParentsCount
< parentsCount
) {
2268 if (m_grouped
&& hasSuccessor
) {
2269 // If the sibling is part of another group, don't mark it as
2270 // successor as the group header is between the sibling connections.
2271 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2272 if (m_layouter
->isFirstGroupItem(i
)) {
2273 hasSuccessor
= false;
2279 return hasSuccessor
;
2282 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2286 const int minSpeed
= 4;
2287 const int maxSpeed
= 128;
2288 const int speedLimiter
= 96;
2289 const int autoScrollBorder
= 64;
2291 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2292 // This assures that the autoscrolling speed grows gradually.
2293 const int incLimiter
= 1;
2295 if (pos
< autoScrollBorder
) {
2296 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2297 inc
= qMax(inc
, -maxSpeed
);
2298 inc
= qMax(inc
, oldInc
- incLimiter
);
2299 } else if (pos
> range
- autoScrollBorder
) {
2300 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2301 inc
= qMin(inc
, maxSpeed
);
2302 inc
= qMin(inc
, oldInc
+ incLimiter
);
2308 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2310 const qreal availableSize
= size
- itemMargin
;
2311 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2317 KItemListCreatorBase::~KItemListCreatorBase()
2319 qDeleteAll(m_recycleableWidgets
);
2320 qDeleteAll(m_createdWidgets
);
2323 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2325 m_createdWidgets
.insert(widget
);
2328 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2330 Q_ASSERT(m_createdWidgets
.contains(widget
));
2331 m_createdWidgets
.remove(widget
);
2333 if (m_recycleableWidgets
.count() < 100) {
2334 m_recycleableWidgets
.append(widget
);
2335 widget
->setVisible(false);
2341 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2343 if (m_recycleableWidgets
.isEmpty()) {
2347 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2348 m_createdWidgets
.insert(widget
);
2352 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2356 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2358 widget
->setParentItem(0);
2359 widget
->setOpacity(1.0);
2360 pushRecycleableWidget(widget
);
2363 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2367 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2369 header
->setOpacity(1.0);
2370 pushRecycleableWidget(header
);
2373 #include "kitemlistview.moc"