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 alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
161 (( m_itemSize
.isEmpty() && !itemSize
.isEmpty()) ||
162 (!m_itemSize
.isEmpty() && itemSize
.isEmpty()));
164 m_itemSize
= itemSize
;
166 if (alternateBackgroundsChanged
) {
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 updateAlternateBackgrounds();
173 if (itemSize
.isEmpty()) {
174 updateVisibleRolesSizes();
176 m_layouter
->setItemSize(itemSize
);
179 m_sizeHintResolver
->clearCache();
180 doLayout(animate
? Animation
: NoAnimation
);
181 onItemSizeChanged(itemSize
, previousSize
);
184 QSizeF
KItemListView::itemSize() const
189 void KItemListView::setScrollOffset(qreal offset
)
195 const qreal previousOffset
= m_layouter
->scrollOffset();
196 if (offset
== previousOffset
) {
200 m_layouter
->setScrollOffset(offset
);
201 m_animation
->setScrollOffset(offset
);
203 // Don't check whether the m_layoutTimer is active: Changing the
204 // scroll offset must always trigger a synchronous layout, otherwise
205 // the smooth-scrolling might get jerky.
206 doLayout(NoAnimation
);
207 onScrollOffsetChanged(offset
, previousOffset
);
210 qreal
KItemListView::scrollOffset() const
212 return m_layouter
->scrollOffset();
215 qreal
KItemListView::maximumScrollOffset() const
217 return m_layouter
->maximumScrollOffset();
220 void KItemListView::setItemOffset(qreal offset
)
222 if (m_layouter
->itemOffset() == offset
) {
226 m_layouter
->setItemOffset(offset
);
228 m_header
->setPos(-offset
, 0);
231 // Don't check whether the m_layoutTimer is active: Changing the
232 // item offset must always trigger a synchronous layout, otherwise
233 // the smooth-scrolling might get jerky.
234 doLayout(NoAnimation
);
237 qreal
KItemListView::itemOffset() const
239 return m_layouter
->itemOffset();
242 qreal
KItemListView::maximumItemOffset() const
244 return m_layouter
->maximumItemOffset();
247 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
249 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
250 m_visibleRoles
= roles
;
252 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
253 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
254 (roles
.count() <= 1 && previousRoles
.count() > 1));
256 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
257 while (it
.hasNext()) {
259 KItemListWidget
* widget
= it
.value();
260 widget
->setVisibleRoles(roles
);
261 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
262 if (alternateBackgroundsChanged
) {
263 updateAlternateBackgroundForWidget(widget
);
267 m_sizeHintResolver
->clearCache();
268 m_layouter
->markAsDirty();
271 m_header
->setVisibleRoles(roles
);
272 m_header
->setVisibleRolesWidths(headerRolesWidths());
273 m_useHeaderWidths
= false;
276 updateVisibleRolesSizes();
277 doLayout(NoAnimation
);
279 onVisibleRolesChanged(roles
, previousRoles
);
282 QList
<QByteArray
> KItemListView::visibleRoles() const
284 return m_visibleRoles
;
287 void KItemListView::setAutoScroll(bool enabled
)
289 if (enabled
&& !m_autoScrollTimer
) {
290 m_autoScrollTimer
= new QTimer(this);
291 m_autoScrollTimer
->setSingleShot(true);
292 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
293 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
294 } else if (!enabled
&& m_autoScrollTimer
) {
295 delete m_autoScrollTimer
;
296 m_autoScrollTimer
= 0;
300 bool KItemListView::autoScroll() const
302 return m_autoScrollTimer
!= 0;
305 void KItemListView::setEnabledSelectionToggles(bool enabled
)
307 if (m_enabledSelectionToggles
!= enabled
) {
308 m_enabledSelectionToggles
= enabled
;
310 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
311 while (it
.hasNext()) {
313 it
.value()->setEnabledSelectionToggle(enabled
);
318 bool KItemListView::enabledSelectionToggles() const
320 return m_enabledSelectionToggles
;
323 KItemListController
* KItemListView::controller() const
328 KItemModelBase
* KItemListView::model() const
333 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
335 m_widgetCreator
= widgetCreator
;
338 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
340 return m_widgetCreator
;
343 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
345 m_groupHeaderCreator
= groupHeaderCreator
;
348 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
350 return m_groupHeaderCreator
;
353 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
355 const KItemListStyleOption previousOption
= m_styleOption
;
356 m_styleOption
= option
;
359 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
360 if (margin
!= m_layouter
->itemMargin()) {
361 // Skip animations when the number of rows or columns
362 // are changed in the grid layout. Although the animation
363 // engine can handle this usecase, it looks obtrusive.
364 animate
= !changesItemGridLayout(m_layouter
->size(),
365 m_layouter
->itemSize(),
367 m_layouter
->setItemMargin(margin
);
371 updateGroupHeaderHeight();
374 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
375 while (it
.hasNext()) {
377 it
.value()->setStyleOption(option
);
380 m_sizeHintResolver
->clearCache();
381 doLayout(animate
? Animation
: NoAnimation
);
383 onStyleOptionChanged(option
, previousOption
);
386 const KItemListStyleOption
& KItemListView::styleOption() const
388 return m_styleOption
;
391 void KItemListView::setGeometry(const QRectF
& rect
)
393 QGraphicsWidget::setGeometry(rect
);
399 const QSizeF newSize
= rect
.size();
400 if (m_itemSize
.isEmpty()) {
401 // The item size is dynamic:
402 // Changing the geometry does not require to do an expensive
403 // update of the visible-roles sizes, only the stretched sizes
404 // need to be adjusted to the new size.
405 updateStretchedVisibleRolesSizes();
407 if (m_useHeaderWidths
) {
408 QSizeF dynamicItemSize
= m_layouter
->itemSize();
410 if (m_itemSize
.width() < 0) {
411 const qreal requiredWidth
= visibleRolesSizesWidthSum();
412 if (newSize
.width() > requiredWidth
) {
413 dynamicItemSize
.setWidth(newSize
.width());
415 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
416 m_header
->resize(headerWidth
, m_header
->size().height());
419 if (m_itemSize
.height() < 0) {
420 const qreal requiredHeight
= visibleRolesSizesHeightSum();
421 if (newSize
.height() > requiredHeight
) {
422 dynamicItemSize
.setHeight(newSize
.height());
424 // TODO: KItemListHeader is not prepared for vertical alignment
427 m_layouter
->setItemSize(dynamicItemSize
);
430 // Triggering a synchronous layout is fine from a performance point of view,
431 // as with dynamic item sizes no moving animation must be done.
432 m_layouter
->setSize(newSize
);
435 const bool animate
= !changesItemGridLayout(newSize
,
436 m_layouter
->itemSize(),
437 m_layouter
->itemMargin());
438 m_layouter
->setSize(newSize
);
441 // Trigger an asynchronous relayout with m_layoutTimer to prevent
442 // performance bottlenecks. If the timer is exceeded, an animated layout
443 // will be triggered.
444 if (!m_layoutTimer
->isActive()) {
445 m_layoutTimer
->start();
448 m_layoutTimer
->stop();
449 doLayout(NoAnimation
);
454 int KItemListView::itemAt(const QPointF
& pos
) const
456 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
457 while (it
.hasNext()) {
460 const KItemListWidget
* widget
= it
.value();
461 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
462 if (widget
->contains(mappedPos
)) {
470 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
472 if (!m_enabledSelectionToggles
) {
476 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
478 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
479 if (!selectionToggleRect
.isEmpty()) {
480 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
481 return selectionToggleRect
.contains(mappedPos
);
487 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
489 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
491 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
492 if (!expansionToggleRect
.isEmpty()) {
493 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
494 return expansionToggleRect
.contains(mappedPos
);
500 int KItemListView::firstVisibleIndex() const
502 return m_layouter
->firstVisibleIndex();
505 int KItemListView::lastVisibleIndex() const
507 return m_layouter
->lastVisibleIndex();
510 QSizeF
KItemListView::itemSizeHint(int index
) const
516 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
518 Q_UNUSED(itemRanges
);
519 return QHash
<QByteArray
, QSizeF
>();
522 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
524 if (m_supportsItemExpanding
!= supportsExpanding
) {
525 m_supportsItemExpanding
= supportsExpanding
;
526 updateSiblingsInformation();
527 onSupportsItemExpandingChanged(supportsExpanding
);
531 bool KItemListView::supportsItemExpanding() const
533 return m_supportsItemExpanding
;
536 QRectF
KItemListView::itemRect(int index
) const
538 return m_layouter
->itemRect(index
);
541 QRectF
KItemListView::itemContextRect(int index
) const
545 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
547 contextRect
= widget
->iconRect() | widget
->textRect();
548 contextRect
.translate(itemRect(index
).topLeft());
554 void KItemListView::scrollToItem(int index
)
556 QRectF viewGeometry
= geometry();
558 const qreal headerHeight
= m_header
->size().height();
559 viewGeometry
.adjust(0, headerHeight
, 0, 0);
561 const QRectF currentRect
= itemRect(index
);
563 if (!viewGeometry
.contains(currentRect
)) {
564 qreal newOffset
= scrollOffset();
565 if (scrollOrientation() == Qt::Vertical
) {
566 if (currentRect
.top() < viewGeometry
.top()) {
567 newOffset
+= currentRect
.top() - viewGeometry
.top();
568 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
569 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
572 if (currentRect
.left() < viewGeometry
.left()) {
573 newOffset
+= currentRect
.left() - viewGeometry
.left();
574 } else if (currentRect
.right() > viewGeometry
.right()) {
575 newOffset
+= currentRect
.right() - viewGeometry
.right();
579 if (newOffset
!= scrollOffset()) {
580 emit
scrollTo(newOffset
);
585 void KItemListView::beginTransaction()
587 ++m_activeTransactions
;
588 if (m_activeTransactions
== 1) {
589 onTransactionBegin();
593 void KItemListView::endTransaction()
595 --m_activeTransactions
;
596 if (m_activeTransactions
< 0) {
597 m_activeTransactions
= 0;
598 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
601 if (m_activeTransactions
== 0) {
603 doLayout(m_endTransactionAnimationHint
);
604 m_endTransactionAnimationHint
= Animation
;
608 bool KItemListView::isTransactionActive() const
610 return m_activeTransactions
> 0;
613 void KItemListView::setHeaderShown(bool show
)
616 if (show
&& !m_header
) {
617 m_header
= new KItemListHeader(this);
618 m_header
->setPos(0, 0);
619 m_header
->setModel(m_model
);
620 m_header
->setVisibleRoles(m_visibleRoles
);
621 m_header
->setVisibleRolesWidths(headerRolesWidths());
622 m_header
->setZValue(1);
624 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
625 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
626 connect(m_header
, SIGNAL(visibleRoleMoved(QByteArray
,int,int)),
627 this, SLOT(slotVisibleRoleMoved(QByteArray
,int,int)));
628 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
629 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
630 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
631 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
633 m_useHeaderWidths
= false;
635 m_layouter
->setHeaderHeight(m_header
->size().height());
636 } else if (!show
&& m_header
) {
639 m_useHeaderWidths
= false;
640 m_layouter
->setHeaderHeight(0);
644 bool KItemListView::isHeaderShown() const
646 return m_header
!= 0;
649 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
655 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
657 QGraphicsWidget::paint(painter
, option
, widget
);
659 if (m_rubberBand
->isActive()) {
660 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
661 m_rubberBand
->endPosition()).normalized();
663 const QPointF topLeft
= rubberBandRect
.topLeft();
664 if (scrollOrientation() == Qt::Vertical
) {
665 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
667 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
670 QStyleOptionRubberBand opt
;
671 opt
.initFrom(widget
);
672 opt
.shape
= QRubberBand::Rectangle
;
674 opt
.rect
= rubberBandRect
.toRect();
675 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
679 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
684 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
686 Q_UNUSED(changedRoles
);
690 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
696 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
702 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
708 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
714 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
720 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
726 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
732 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
734 Q_UNUSED(supportsExpanding
);
737 void KItemListView::onTransactionBegin()
741 void KItemListView::onTransactionEnd()
745 bool KItemListView::event(QEvent
* event
)
747 // Forward all events to the controller and handle them there
748 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
752 return QGraphicsWidget::event(event
);
755 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
757 m_mousePos
= transform().map(event
->pos());
761 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
763 QGraphicsWidget::mouseMoveEvent(event
);
765 m_mousePos
= transform().map(event
->pos());
766 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
767 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
771 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
773 event
->setAccepted(true);
777 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
779 QGraphicsWidget::dragMoveEvent(event
);
781 m_mousePos
= transform().map(event
->pos());
782 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
783 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
787 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
789 QGraphicsWidget::dragLeaveEvent(event
);
790 setAutoScroll(false);
793 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
795 QGraphicsWidget::dropEvent(event
);
796 setAutoScroll(false);
799 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
801 return m_visibleItems
.values();
804 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
806 updateVisibleRolesSizes(itemRanges
);
808 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
809 if (hasMultipleRanges
) {
813 m_layouter
->markAsDirty();
815 int previouslyInsertedCount
= 0;
816 foreach (const KItemRange
& range
, itemRanges
) {
817 // range.index is related to the model before anything has been inserted.
818 // As in each loop the current item-range gets inserted the index must
819 // be increased by the already previously inserted items.
820 const int index
= range
.index
+ previouslyInsertedCount
;
821 const int count
= range
.count
;
822 if (index
< 0 || count
<= 0) {
823 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
826 previouslyInsertedCount
+= count
;
828 m_sizeHintResolver
->itemsInserted(index
, count
);
830 // Determine which visible items must be moved
831 QList
<int> itemsToMove
;
832 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
833 while (it
.hasNext()) {
835 const int visibleItemIndex
= it
.key();
836 if (visibleItemIndex
>= index
) {
837 itemsToMove
.append(visibleItemIndex
);
841 // Update the indexes of all KItemListWidget instances that are located
842 // after the inserted items. It is important to adjust the indexes in the order
843 // from the highest index to the lowest index to prevent overlaps when setting the new index.
845 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
846 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
848 const int newIndex
= widget
->index() + count
;
849 if (hasMultipleRanges
) {
850 setWidgetIndex(widget
, newIndex
);
852 // Try to animate the moving of the item
853 moveWidgetToIndex(widget
, newIndex
);
857 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
858 // Check whether a scrollbar is required to show the inserted items. In this case
859 // the size of the layouter will be decreased before calling doLayout(): This prevents
860 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
861 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
862 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
863 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
864 if (decreaseLayouterSize
) {
865 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
866 QSizeF layouterSize
= m_layouter
->size();
867 if (verticalScrollOrientation
) {
868 layouterSize
.rwidth() -= scrollBarExtent
;
870 layouterSize
.rheight() -= scrollBarExtent
;
872 m_layouter
->setSize(layouterSize
);
876 if (!hasMultipleRanges
) {
877 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
878 updateSiblingsInformation();
883 m_controller
->selectionManager()->itemsInserted(itemRanges
);
886 if (hasMultipleRanges
) {
888 // Important: Don't read any m_layouter-property inside the for-loop in case if
889 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
890 // updated in each loop-cycle and has only a consistent state after the loop.
891 Q_ASSERT(m_layouter
->isDirty());
893 m_endTransactionAnimationHint
= NoAnimation
;
895 updateSiblingsInformation();
898 if (useAlternateBackgrounds()) {
899 updateAlternateBackgrounds();
903 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
905 updateVisibleRolesSizes();
907 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
908 if (hasMultipleRanges
) {
912 m_layouter
->markAsDirty();
914 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
915 const KItemRange
& range
= itemRanges
.at(i
);
916 const int index
= range
.index
;
917 const int count
= range
.count
;
918 if (index
< 0 || count
<= 0) {
919 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
923 m_sizeHintResolver
->itemsRemoved(index
, count
);
925 const int firstRemovedIndex
= index
;
926 const int lastRemovedIndex
= index
+ count
- 1;
927 const int lastIndex
= m_model
->count() + count
- 1;
929 // Remove all KItemListWidget instances that got deleted
930 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
931 KItemListWidget
* widget
= m_visibleItems
.value(i
);
936 m_animation
->stop(widget
);
937 // Stopping the animation might lead to recycling the widget if
938 // it is invisible (see slotAnimationFinished()).
939 // Check again whether it is still visible:
940 if (!m_visibleItems
.contains(i
)) {
944 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
945 // Remove the widget without animation
946 recycleWidget(widget
);
948 // Animate the removing of the items. Special case: When removing an item there
949 // is no valid model index available anymore. For the
950 // remove-animation the item gets removed from m_visibleItems but the widget
951 // will stay alive until the animation has been finished and will
952 // be recycled (deleted) in KItemListView::slotAnimationFinished().
953 m_visibleItems
.remove(i
);
954 widget
->setIndex(-1);
955 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
959 // Update the indexes of all KItemListWidget instances that are located
960 // after the deleted items
961 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
962 KItemListWidget
* widget
= m_visibleItems
.value(i
);
964 const int newIndex
= i
- count
;
965 if (hasMultipleRanges
) {
966 setWidgetIndex(widget
, newIndex
);
968 // Try to animate the moving of the item
969 moveWidgetToIndex(widget
, newIndex
);
974 if (!hasMultipleRanges
) {
975 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
976 // assumes an updated geometry. If items are removed during an active transaction,
977 // the transaction will be temporary deactivated so that doLayout() triggers a
978 // geometry update if necessary.
979 const int activeTransactions
= m_activeTransactions
;
980 m_activeTransactions
= 0;
981 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
982 m_activeTransactions
= activeTransactions
;
983 updateSiblingsInformation();
988 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
991 if (hasMultipleRanges
) {
993 // Important: Don't read any m_layouter-property inside the for-loop in case if
994 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
995 // updated in each loop-cycle and has only a consistent state after the loop.
996 Q_ASSERT(m_layouter
->isDirty());
998 m_endTransactionAnimationHint
= NoAnimation
;
1000 updateSiblingsInformation();
1003 if (useAlternateBackgrounds()) {
1004 updateAlternateBackgrounds();
1008 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1010 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1011 m_layouter
->markAsDirty();
1014 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1017 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1018 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1020 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1021 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1023 updateWidgetProperties(widget
, index
);
1024 initializeItemListWidget(widget
);
1028 doLayout(NoAnimation
);
1029 updateSiblingsInformation();
1032 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1033 const QSet
<QByteArray
>& roles
)
1035 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1036 if (updateSizeHints
) {
1037 updateVisibleRolesSizes(itemRanges
);
1040 foreach (const KItemRange
& itemRange
, itemRanges
) {
1041 const int index
= itemRange
.index
;
1042 const int count
= itemRange
.count
;
1044 if (updateSizeHints
) {
1045 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1046 m_layouter
->markAsDirty();
1048 if (!m_layoutTimer
->isActive()) {
1049 m_layoutTimer
->start();
1053 // Apply the changed roles to the visible item-widgets
1054 const int lastIndex
= index
+ count
- 1;
1055 for (int i
= index
; i
<= lastIndex
; ++i
) {
1056 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1058 widget
->setData(m_model
->data(i
), roles
);
1062 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1063 // The sort-role has been changed which might result
1064 // in modified group headers
1065 updateVisibleGroupHeaders();
1066 doLayout(NoAnimation
);
1071 void KItemListView::slotGroupedSortingChanged(bool current
)
1073 m_grouped
= current
;
1074 m_layouter
->markAsDirty();
1077 updateGroupHeaderHeight();
1079 // Clear all visible headers
1080 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1081 while (it
.hasNext()) {
1083 recycleGroupHeaderForWidget(it
.key());
1085 Q_ASSERT(m_visibleGroups
.isEmpty());
1088 if (useAlternateBackgrounds()) {
1089 // Changing the group mode requires to update the alternate backgrounds
1090 // as with the enabled group mode the altering is done on base of the first
1092 updateAlternateBackgrounds();
1094 updateSiblingsInformation();
1095 doLayout(NoAnimation
);
1098 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1103 updateVisibleGroupHeaders();
1104 doLayout(NoAnimation
);
1108 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1113 updateVisibleGroupHeaders();
1114 doLayout(NoAnimation
);
1118 void KItemListView::slotCurrentChanged(int current
, int previous
)
1122 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1123 if (previousWidget
) {
1124 previousWidget
->setCurrent(false);
1127 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1128 if (currentWidget
) {
1129 currentWidget
->setCurrent(true);
1133 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1137 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1138 while (it
.hasNext()) {
1140 const int index
= it
.key();
1141 KItemListWidget
* widget
= it
.value();
1142 widget
->setSelected(current
.contains(index
));
1146 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1147 KItemListViewAnimation::AnimationType type
)
1149 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1150 Q_ASSERT(itemListWidget
);
1153 case KItemListViewAnimation::DeleteAnimation
: {
1154 // As we recycle the widget in this case it is important to assure that no
1155 // other animation has been started. This is a convention in KItemListView and
1156 // not a requirement defined by KItemListViewAnimation.
1157 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1159 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1160 // by m_visibleWidgets and must be deleted manually after the animation has
1162 recycleGroupHeaderForWidget(itemListWidget
);
1163 m_widgetCreator
->recycle(itemListWidget
);
1167 case KItemListViewAnimation::CreateAnimation
:
1168 case KItemListViewAnimation::MovingAnimation
:
1169 case KItemListViewAnimation::ResizeAnimation
: {
1170 const int index
= itemListWidget
->index();
1171 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1172 (index
> m_layouter
->lastVisibleIndex());
1173 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1174 recycleWidget(itemListWidget
);
1183 void KItemListView::slotLayoutTimerFinished()
1185 m_layouter
->setSize(geometry().size());
1186 doLayout(Animation
);
1189 void KItemListView::slotRubberBandPosChanged()
1194 void KItemListView::slotRubberBandActivationChanged(bool active
)
1197 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1198 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1199 m_skipAutoScrollForRubberBand
= true;
1201 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1202 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1203 m_skipAutoScrollForRubberBand
= false;
1209 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1211 qreal previousWidth
)
1213 Q_UNUSED(previousWidth
);
1215 m_useHeaderWidths
= true;
1217 if (m_visibleRolesSizes
.contains(role
)) {
1218 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1219 roleSize
.setWidth(currentWidth
);
1220 m_visibleRolesSizes
.insert(role
, roleSize
);
1221 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1223 // Apply the new size to the layouter
1224 QSizeF dynamicItemSize
= m_itemSize
;
1225 if (dynamicItemSize
.width() < 0) {
1226 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1227 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1229 if (dynamicItemSize
.height() < 0) {
1230 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1231 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1234 m_layouter
->setItemSize(dynamicItemSize
);
1236 // Update the role sizes for all visible widgets
1237 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1238 while (it
.hasNext()) {
1240 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1242 doLayout(NoAnimation
);
1246 void KItemListView::slotVisibleRoleMoved(const QByteArray
& role
,
1250 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1252 const QList
<QByteArray
> previous
= m_visibleRoles
;
1254 QList
<QByteArray
> current
= m_visibleRoles
;
1255 current
.removeAt(previousIndex
);
1256 current
.insert(currentIndex
, role
);
1258 setVisibleRoles(current
);
1260 emit
visibleRolesChanged(current
, previous
);
1263 void KItemListView::triggerAutoScrolling()
1265 if (!m_autoScrollTimer
) {
1270 int visibleSize
= 0;
1271 if (scrollOrientation() == Qt::Vertical
) {
1272 pos
= m_mousePos
.y();
1273 visibleSize
= size().height();
1275 pos
= m_mousePos
.x();
1276 visibleSize
= size().width();
1279 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1280 m_autoScrollIncrement
= 0;
1283 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1284 if (m_autoScrollIncrement
== 0) {
1285 // The mouse position is not above an autoscroll margin (the autoscroll timer
1286 // will be restarted in mouseMoveEvent())
1287 m_autoScrollTimer
->stop();
1291 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1292 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1293 // if the direction of the rubberband is similar to the autoscroll direction. This
1294 // prevents that starting to create a rubberband within the autoscroll margins starts
1295 // an autoscrolling.
1297 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1298 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1299 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1300 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1301 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1302 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1303 // been moved up although the autoscroll direction might be down)
1304 m_autoScrollTimer
->stop();
1309 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1310 // the autoscrolling may not get skipped anymore until a new rubberband is created
1311 m_skipAutoScrollForRubberBand
= false;
1313 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1314 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1315 setScrollOffset(newScrollOffset
);
1317 // Trigger the autoscroll timer which will periodically call
1318 // triggerAutoScrolling()
1319 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1322 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1324 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1326 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1327 Q_ASSERT(groupHeader
);
1328 updateGroupHeaderLayout(widget
);
1331 void KItemListView::setController(KItemListController
* controller
)
1333 if (m_controller
!= controller
) {
1334 KItemListController
* previous
= m_controller
;
1336 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1337 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1338 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1341 m_controller
= controller
;
1344 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1345 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1346 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1349 onControllerChanged(controller
, previous
);
1353 void KItemListView::setModel(KItemModelBase
* model
)
1355 if (m_model
== model
) {
1359 KItemModelBase
* previous
= m_model
;
1362 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1363 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1364 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1365 this, SLOT(slotItemsInserted(KItemRangeList
)));
1366 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1367 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1368 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1369 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1370 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1371 this, SLOT(slotGroupedSortingChanged(bool)));
1372 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1373 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1374 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1375 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1379 m_layouter
->setModel(model
);
1380 m_grouped
= model
->groupedSorting();
1383 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1384 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1385 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1386 this, SLOT(slotItemsInserted(KItemRangeList
)));
1387 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1388 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1389 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1390 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1391 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1392 this, SLOT(slotGroupedSortingChanged(bool)));
1393 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1394 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1395 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1396 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1399 onModelChanged(model
, previous
);
1402 KItemListRubberBand
* KItemListView::rubberBand() const
1404 return m_rubberBand
;
1407 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1409 if (m_layoutTimer
->isActive()) {
1410 m_layoutTimer
->stop();
1413 if (m_activeTransactions
> 0) {
1414 if (hint
== NoAnimation
) {
1415 // As soon as at least one property change should be done without animation,
1416 // the whole transaction will be marked as not animated.
1417 m_endTransactionAnimationHint
= NoAnimation
;
1422 if (!m_model
|| m_model
->count() < 0) {
1426 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1427 if (firstVisibleIndex
< 0) {
1428 emitOffsetChanges();
1432 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1433 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1434 // is still shown if the maximum offset got decreased.
1435 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1436 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1437 if (scrollOffset() > maxOffsetToShowFullRange
) {
1438 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1439 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1442 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1444 int firstSibblingIndex
= -1;
1445 int lastSibblingIndex
= -1;
1446 const bool supportsExpanding
= supportsItemExpanding();
1448 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1450 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1451 // instances from invisible items are reused. If no reusable items are
1452 // found then new KItemListWidget instances get created.
1453 const bool animate
= (hint
== Animation
);
1454 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1455 bool applyNewPos
= true;
1456 bool wasHidden
= false;
1458 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1459 const QPointF newPos
= itemBounds
.topLeft();
1460 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1463 if (!reusableItems
.isEmpty()) {
1464 // Reuse a KItemListWidget instance from an invisible item
1465 const int oldIndex
= reusableItems
.takeLast();
1466 widget
= m_visibleItems
.value(oldIndex
);
1467 setWidgetIndex(widget
, i
);
1468 updateWidgetProperties(widget
, i
);
1469 initializeItemListWidget(widget
);
1471 // No reusable KItemListWidget instance is available, create a new one
1472 widget
= createWidget(i
);
1474 widget
->resize(itemBounds
.size());
1476 if (animate
&& changedCount
< 0) {
1477 // Items have been deleted, move the created item to the
1478 // imaginary old position. They will get animated to the new position
1480 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1481 if (itemRect
.isEmpty()) {
1482 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1483 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1484 widget
->setPos(invisibleOldPos
);
1486 widget
->setPos(itemRect
.topLeft());
1488 applyNewPos
= false;
1491 if (supportsExpanding
&& changedCount
== 0) {
1492 if (firstSibblingIndex
< 0) {
1493 firstSibblingIndex
= i
;
1495 lastSibblingIndex
= i
;
1500 const bool itemsRemoved
= (changedCount
< 0);
1501 const bool itemsInserted
= (changedCount
> 0);
1502 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1503 // The item is located after the removed items. Animate the moving of the position.
1504 applyNewPos
= !moveWidget(widget
, newPos
);
1505 } else if (itemsInserted
&& i
>= changedIndex
) {
1506 // The item is located after the first inserted item
1507 if (i
<= changedIndex
+ changedCount
- 1) {
1508 // The item is an inserted item. Animate the appearing of the item.
1509 // For performance reasons no animation is done when changedCount is equal
1510 // to all available items.
1511 if (changedCount
< m_model
->count()) {
1512 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1514 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1515 // The item was already there before, so animate the moving of the position.
1516 // No moving animation is done if the item is animated by a create animation: This
1517 // prevents a "move animation mess" when inserting several ranges in parallel.
1518 applyNewPos
= !moveWidget(widget
, newPos
);
1520 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1521 // The size of the view might have been changed. Animate the moving of the position.
1522 applyNewPos
= !moveWidget(widget
, newPos
);
1525 m_animation
->stop(widget
);
1529 widget
->setPos(newPos
);
1532 Q_ASSERT(widget
->index() == i
);
1533 widget
->setVisible(true);
1535 if (widget
->size() != itemBounds
.size()) {
1536 // Resize the widget for the item to the changed size.
1538 // If a dynamic item size is used then no animation is done in the direction
1539 // of the dynamic size.
1540 if (m_itemSize
.width() <= 0) {
1541 // The width is dynamic, apply the new width without animation.
1542 widget
->resize(itemBounds
.width(), widget
->size().height());
1543 } else if (m_itemSize
.height() <= 0) {
1544 // The height is dynamic, apply the new height without animation.
1545 widget
->resize(widget
->size().width(), itemBounds
.height());
1547 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1549 widget
->resize(itemBounds
.size());
1553 // Updating the cell-information must be done as last step: The decision whether the
1554 // moving-animation should be started at all is based on the previous cell-information.
1555 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1556 m_visibleCells
.insert(i
, cell
);
1559 // Delete invisible KItemListWidget instances that have not been reused
1560 foreach (int index
, reusableItems
) {
1561 recycleWidget(m_visibleItems
.value(index
));
1564 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1565 Q_ASSERT(lastSibblingIndex
>= 0);
1566 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1570 // Update the layout of all visible group headers
1571 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1572 while (it
.hasNext()) {
1574 updateGroupHeaderLayout(it
.key());
1578 emitOffsetChanges();
1581 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1582 int lastVisibleIndex
,
1583 LayoutAnimationHint hint
)
1585 // Determine all items that are completely invisible and might be
1586 // reused for items that just got (at least partly) visible. If the
1587 // animation hint is set to 'Animation' items that do e.g. an animated
1588 // moving of their position are not marked as invisible: This assures
1589 // that a scrolling inside the view can be done without breaking an animation.
1593 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1594 while (it
.hasNext()) {
1597 KItemListWidget
* widget
= it
.value();
1598 const int index
= widget
->index();
1599 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1602 if (m_animation
->isStarted(widget
)) {
1603 if (hint
== NoAnimation
) {
1604 // Stopping the animation will call KItemListView::slotAnimationFinished()
1605 // and the widget will be recycled if necessary there.
1606 m_animation
->stop(widget
);
1609 widget
->setVisible(false);
1610 items
.append(index
);
1613 recycleGroupHeaderForWidget(widget
);
1622 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1624 if (widget
->pos() == newPos
) {
1628 bool startMovingAnim
= false;
1630 // When having a grid the moving-animation should only be started, if it is done within
1631 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1632 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1633 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1634 const int index
= widget
->index();
1635 const Cell cell
= m_visibleCells
.value(index
);
1636 if (cell
.column
>= 0 && cell
.row
>= 0) {
1637 if (scrollOrientation() == Qt::Vertical
) {
1638 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1640 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1644 if (startMovingAnim
) {
1645 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1649 m_animation
->stop(widget
);
1650 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1654 void KItemListView::emitOffsetChanges()
1656 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1657 if (m_oldScrollOffset
!= newScrollOffset
) {
1658 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1659 m_oldScrollOffset
= newScrollOffset
;
1662 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1663 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1664 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1665 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1668 const qreal newItemOffset
= m_layouter
->itemOffset();
1669 if (m_oldItemOffset
!= newItemOffset
) {
1670 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1671 m_oldItemOffset
= newItemOffset
;
1674 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1675 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1676 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1677 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1681 KItemListWidget
* KItemListView::createWidget(int index
)
1683 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1684 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1686 m_visibleItems
.insert(index
, widget
);
1687 m_visibleCells
.insert(index
, Cell());
1688 updateWidgetProperties(widget
, index
);
1689 initializeItemListWidget(widget
);
1693 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1696 recycleGroupHeaderForWidget(widget
);
1699 const int index
= widget
->index();
1700 m_visibleItems
.remove(index
);
1701 m_visibleCells
.remove(index
);
1703 m_widgetCreator
->recycle(widget
);
1706 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1708 const int oldIndex
= widget
->index();
1709 m_visibleItems
.remove(oldIndex
);
1710 m_visibleCells
.remove(oldIndex
);
1712 m_visibleItems
.insert(index
, widget
);
1713 m_visibleCells
.insert(index
, Cell());
1715 widget
->setIndex(index
);
1718 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1720 const int oldIndex
= widget
->index();
1721 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1723 setWidgetIndex(widget
, index
);
1725 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1726 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1727 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1728 (!vertical
&& oldCell
.column
== newCell
.column
);
1730 m_visibleCells
.insert(index
, newCell
);
1734 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1737 case LayouterSize
: m_layouter
->setSize(size
); break;
1738 case ItemSize
: m_layouter
->setItemSize(size
); break;
1743 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1745 widget
->setVisibleRoles(m_visibleRoles
);
1746 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1747 widget
->setStyleOption(m_styleOption
);
1749 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1750 widget
->setCurrent(index
== selectionManager
->currentItem());
1751 widget
->setSelected(selectionManager
->isSelected(index
));
1752 widget
->setHovered(false);
1753 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1754 widget
->setIndex(index
);
1755 widget
->setData(m_model
->data(index
));
1756 widget
->setSiblingsInformation(QBitArray());
1757 updateAlternateBackgroundForWidget(widget
);
1760 updateGroupHeaderForWidget(widget
);
1764 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1766 Q_ASSERT(m_grouped
);
1768 const int index
= widget
->index();
1769 if (!m_layouter
->isFirstGroupItem(index
)) {
1770 // The widget does not represent the first item of a group
1771 // and hence requires no header
1772 recycleGroupHeaderForWidget(widget
);
1776 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1777 if (groups
.isEmpty()) {
1781 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1783 groupHeader
= m_groupHeaderCreator
->create(this);
1784 groupHeader
->setParentItem(widget
);
1785 m_visibleGroups
.insert(widget
, groupHeader
);
1786 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1788 Q_ASSERT(groupHeader
->parentItem() == widget
);
1790 const int groupIndex
= groupIndexForItem(index
);
1791 Q_ASSERT(groupIndex
>= 0);
1792 groupHeader
->setData(groups
.at(groupIndex
).second
);
1793 groupHeader
->setRole(model()->sortRole());
1794 groupHeader
->setStyleOption(m_styleOption
);
1795 groupHeader
->setScrollOrientation(scrollOrientation());
1796 groupHeader
->setItemIndex(index
);
1798 groupHeader
->show();
1801 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1803 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1804 Q_ASSERT(groupHeader
);
1806 const int index
= widget
->index();
1807 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1808 const QRectF itemRect
= m_layouter
->itemRect(index
);
1810 // The group-header is a child of the itemlist widget. Translate the
1811 // group header position to the relative position.
1812 if (scrollOrientation() == Qt::Vertical
) {
1813 // In the vertical scroll orientation the group header should always span
1814 // the whole width no matter which temporary position the parent widget
1815 // has. In this case the x-position and width will be adjusted manually.
1816 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1817 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1819 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1820 groupHeader
->resize(groupHeaderRect
.size());
1824 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1826 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1828 header
->setParentItem(0);
1829 m_groupHeaderCreator
->recycle(header
);
1830 m_visibleGroups
.remove(widget
);
1831 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1835 void KItemListView::updateVisibleGroupHeaders()
1837 Q_ASSERT(m_grouped
);
1838 m_layouter
->markAsDirty();
1840 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1841 while (it
.hasNext()) {
1843 updateGroupHeaderForWidget(it
.value());
1847 int KItemListView::groupIndexForItem(int index
) const
1849 Q_ASSERT(m_grouped
);
1851 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1852 if (groups
.isEmpty()) {
1857 int max
= groups
.count() - 1;
1860 mid
= (min
+ max
) / 2;
1861 if (index
> groups
[mid
].first
) {
1866 } while (groups
[mid
].first
!= index
&& min
<= max
);
1869 while (groups
[mid
].first
> index
&& mid
> 0) {
1877 void KItemListView::updateAlternateBackgrounds()
1879 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1880 while (it
.hasNext()) {
1882 updateAlternateBackgroundForWidget(it
.value());
1886 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1888 bool enabled
= useAlternateBackgrounds();
1890 const int index
= widget
->index();
1891 enabled
= (index
& 0x1) > 0;
1893 const int groupIndex
= groupIndexForItem(index
);
1894 if (groupIndex
>= 0) {
1895 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1896 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1897 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1898 enabled
= (relativeIndex
& 0x1) > 0;
1902 widget
->setAlternateBackground(enabled
);
1905 bool KItemListView::useAlternateBackgrounds() const
1907 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1910 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1912 QHash
<QByteArray
, qreal
> rolesWidths
;
1914 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1915 while (it
.hasNext()) {
1917 rolesWidths
.insert(it
.key(), it
.value().width());
1923 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1925 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1929 const int itemCount
= m_model
->count();
1930 int rangesItemCount
= 0;
1931 foreach (const KItemRange
& range
, itemRanges
) {
1932 rangesItemCount
+= range
.count
;
1935 if (itemCount
== rangesItemCount
) {
1936 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1938 // Assure the the sizes are not smaller than the minimum defined by the header
1939 // TODO: Currently only implemented for a top-aligned header
1940 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1941 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1942 while (it
.hasNext()) {
1944 const QSizeF
& size
= it
.value();
1945 if (size
.width() < minHeaderRoleWidth
) {
1946 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1947 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1952 // Only a sub range of the roles need to be determined.
1953 // The chances are good that the sizes of the sub ranges
1954 // already fit into the available sizes and hence no
1955 // expensive update might be required.
1956 bool updateRequired
= false;
1958 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1959 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1960 while (it
.hasNext()) {
1962 const QByteArray
& role
= it
.key();
1963 const QSizeF
& updatedSize
= it
.value();
1964 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1965 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1966 m_visibleRolesSizes
.insert(role
, updatedSize
);
1967 updateRequired
= true;
1971 if (!updateRequired
) {
1972 // All the updated sizes are smaller than the current sizes and no change
1973 // of the stretched roles-widths is required
1978 updateStretchedVisibleRolesSizes();
1981 void KItemListView::updateVisibleRolesSizes()
1987 const int itemCount
= m_model
->count();
1988 if (itemCount
> 0) {
1989 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1993 void KItemListView::updateStretchedVisibleRolesSizes()
1995 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1999 // Calculate the maximum size of an item by considering the
2000 // visible role sizes and apply them to the layouter. If the
2001 // size does not use the available view-size the size of the
2002 // first role will get stretched.
2003 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
2004 const QByteArray role
= m_visibleRoles
.first();
2005 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
2007 QSizeF dynamicItemSize
= m_itemSize
;
2009 if (dynamicItemSize
.width() <= 0) {
2010 const qreal requiredWidth
= visibleRolesSizesWidthSum();
2011 const qreal availableWidth
= size().width();
2012 if (requiredWidth
!= availableWidth
) {
2013 // Stretch the first role to use the whole remaining width
2014 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
2016 // TODO: A proper calculation of the minimum width depends on the implementation
2017 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2019 const qreal minWidth
= m_styleOption
.iconSize
* 2 + 200;
2020 if (firstRoleSize
.width() < minWidth
) {
2021 firstRoleSize
.rwidth() = minWidth
;
2023 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
2025 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2028 // TODO: A dynamic item height (dynamicItemSize.height() <= 0)
2029 // is not handled currently
2031 m_layouter
->setItemSize(dynamicItemSize
);
2034 m_header
->setVisibleRolesWidths(headerRolesWidths());
2035 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
2038 // Update the role sizes for all visible widgets
2039 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2040 while (it
.hasNext()) {
2042 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
2046 qreal
KItemListView::visibleRolesSizesWidthSum() const
2049 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2050 while (it
.hasNext()) {
2052 widthSum
+= it
.value().width();
2057 qreal
KItemListView::visibleRolesSizesHeightSum() const
2059 qreal heightSum
= 0;
2060 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2061 while (it
.hasNext()) {
2063 heightSum
+= it
.value().height();
2068 QRectF
KItemListView::headerBoundaries() const
2070 return m_header
? m_header
->geometry() : QRectF();
2073 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2074 const QSizeF
& newItemSize
,
2075 const QSizeF
& newItemMargin
) const
2077 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2081 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2082 const qreal itemWidth
= m_layouter
->itemSize().width();
2083 if (itemWidth
> 0) {
2084 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2085 newItemSize
.width(),
2086 newItemMargin
.width());
2087 if (m_model
->count() > newColumnCount
) {
2088 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2090 m_layouter
->itemMargin().width());
2091 return oldColumnCount
!= newColumnCount
;
2095 const qreal itemHeight
= m_layouter
->itemSize().height();
2096 if (itemHeight
> 0) {
2097 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2098 newItemSize
.height(),
2099 newItemMargin
.height());
2100 if (m_model
->count() > newRowCount
) {
2101 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2103 m_layouter
->itemMargin().height());
2104 return oldRowCount
!= newRowCount
;
2112 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2114 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2118 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2119 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2120 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2121 // Only animate if up to 2/3 of a row or column are inserted or removed
2122 return changedItemCount
<= maximum
* 2 / 3;
2126 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2128 const QSizeF oldSize
= m_layouter
->size();
2130 m_layouter
->setSize(size
);
2131 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2132 m_layouter
->setSize(oldSize
);
2134 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2135 : maxOffset
> size
.width();
2138 void KItemListView::updateGroupHeaderHeight()
2140 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2141 qreal groupHeaderMargin
= 0;
2143 if (scrollOrientation() == Qt::Horizontal
) {
2144 // The vertical margin above and below the header should be
2145 // equal to the horizontal margin, not the vertical margin
2146 // from m_styleOption.
2147 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2148 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2149 } else if (m_itemSize
.isEmpty()){
2150 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2151 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2153 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2154 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2156 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2157 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2159 updateVisibleGroupHeaders();
2162 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2164 if (!supportsItemExpanding() || !m_model
) {
2168 if (firstIndex
< 0 || lastIndex
< 0) {
2169 firstIndex
= m_layouter
->firstVisibleIndex();
2170 lastIndex
= m_layouter
->lastVisibleIndex();
2172 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2173 lastIndex
>= m_layouter
->firstVisibleIndex());
2174 if (!isRangeVisible
) {
2179 int previousParents
= 0;
2180 QBitArray previousSiblings
;
2182 // The rootIndex describes the first index where the siblings get
2183 // calculated from. For the calculation the upper most parent item
2184 // is required. For performance reasons it is checked first whether
2185 // the visible items before or after the current range already
2186 // contain a siblings information which can be used as base.
2187 int rootIndex
= firstIndex
;
2189 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2191 // There is no visible widget before the range, check whether there
2192 // is one after the range:
2193 widget
= m_visibleItems
.value(lastIndex
+ 1);
2195 // The sibling information of the widget may only be used if
2196 // all items of the range have the same number of parents.
2197 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2198 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2199 if (m_model
->expandedParentsCount(i
) != parents
) {
2208 // Performance optimization: Use the sibling information of the visible
2209 // widget beside the given range.
2210 previousSiblings
= widget
->siblingsInformation();
2211 if (previousSiblings
.isEmpty()) {
2214 previousParents
= previousSiblings
.count() - 1;
2215 previousSiblings
.truncate(previousParents
);
2217 // Potentially slow path: Go back to the upper most parent of firstIndex
2218 // to be able to calculate the initial value for the siblings.
2219 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2224 Q_ASSERT(previousParents
>= 0);
2225 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2226 // Update the parent-siblings in case if the current item represents
2227 // a child or an upper parent.
2228 const int currentParents
= m_model
->expandedParentsCount(i
);
2229 Q_ASSERT(currentParents
>= 0);
2230 if (previousParents
< currentParents
) {
2231 previousParents
= currentParents
;
2232 previousSiblings
.resize(currentParents
);
2233 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2234 } else if (previousParents
> currentParents
) {
2235 previousParents
= currentParents
;
2236 previousSiblings
.truncate(currentParents
);
2239 if (i
>= firstIndex
) {
2240 // The index represents a visible item. Apply the parent-siblings
2241 // and update the sibling of the current item.
2242 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2247 QBitArray siblings
= previousSiblings
;
2248 siblings
.resize(siblings
.count() + 1);
2249 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2251 widget
->setSiblingsInformation(siblings
);
2256 bool KItemListView::hasSiblingSuccessor(int index
) const
2258 bool hasSuccessor
= false;
2259 const int parentsCount
= m_model
->expandedParentsCount(index
);
2260 int successorIndex
= index
+ 1;
2262 // Search the next sibling
2263 const int itemCount
= m_model
->count();
2264 while (successorIndex
< itemCount
) {
2265 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2266 if (currentParentsCount
== parentsCount
) {
2267 hasSuccessor
= true;
2269 } else if (currentParentsCount
< parentsCount
) {
2275 if (m_grouped
&& hasSuccessor
) {
2276 // If the sibling is part of another group, don't mark it as
2277 // successor as the group header is between the sibling connections.
2278 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2279 if (m_layouter
->isFirstGroupItem(i
)) {
2280 hasSuccessor
= false;
2286 return hasSuccessor
;
2289 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2293 const int minSpeed
= 4;
2294 const int maxSpeed
= 128;
2295 const int speedLimiter
= 96;
2296 const int autoScrollBorder
= 64;
2298 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2299 // This assures that the autoscrolling speed grows gradually.
2300 const int incLimiter
= 1;
2302 if (pos
< autoScrollBorder
) {
2303 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2304 inc
= qMax(inc
, -maxSpeed
);
2305 inc
= qMax(inc
, oldInc
- incLimiter
);
2306 } else if (pos
> range
- autoScrollBorder
) {
2307 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2308 inc
= qMin(inc
, maxSpeed
);
2309 inc
= qMin(inc
, oldInc
+ incLimiter
);
2315 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2317 const qreal availableSize
= size
- itemMargin
;
2318 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2324 KItemListCreatorBase::~KItemListCreatorBase()
2326 qDeleteAll(m_recycleableWidgets
);
2327 qDeleteAll(m_createdWidgets
);
2330 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2332 m_createdWidgets
.insert(widget
);
2335 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2337 Q_ASSERT(m_createdWidgets
.contains(widget
));
2338 m_createdWidgets
.remove(widget
);
2340 if (m_recycleableWidgets
.count() < 100) {
2341 m_recycleableWidgets
.append(widget
);
2342 widget
->setVisible(false);
2348 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2350 if (m_recycleableWidgets
.isEmpty()) {
2354 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2355 m_createdWidgets
.insert(widget
);
2359 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2363 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2365 widget
->setParentItem(0);
2366 widget
->setOpacity(1.0);
2367 pushRecycleableWidget(widget
);
2370 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2374 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2376 header
->setOpacity(1.0);
2377 pushRecycleableWidget(header
);
2380 #include "kitemlistview.moc"