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;
304 bool KItemListView::autoScroll() const
306 return m_autoScrollTimer
!= 0;
309 void KItemListView::setEnabledSelectionToggles(bool enabled
)
311 if (m_enabledSelectionToggles
!= enabled
) {
312 m_enabledSelectionToggles
= enabled
;
314 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
315 while (it
.hasNext()) {
317 it
.value()->setEnabledSelectionToggle(enabled
);
322 bool KItemListView::enabledSelectionToggles() const
324 return m_enabledSelectionToggles
;
327 KItemListController
* KItemListView::controller() const
332 KItemModelBase
* KItemListView::model() const
337 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
339 m_widgetCreator
= widgetCreator
;
342 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
344 return m_widgetCreator
;
347 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
349 m_groupHeaderCreator
= groupHeaderCreator
;
352 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
354 return m_groupHeaderCreator
;
357 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
359 const KItemListStyleOption previousOption
= m_styleOption
;
360 m_styleOption
= option
;
363 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
364 if (margin
!= m_layouter
->itemMargin()) {
365 // Skip animations when the number of rows or columns
366 // are changed in the grid layout. Although the animation
367 // engine can handle this usecase, it looks obtrusive.
368 animate
= !changesItemGridLayout(m_layouter
->size(),
369 m_layouter
->itemSize(),
371 m_layouter
->setItemMargin(margin
);
375 updateGroupHeaderHeight();
378 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
379 while (it
.hasNext()) {
381 it
.value()->setStyleOption(option
);
384 m_sizeHintResolver
->clearCache();
385 doLayout(animate
? Animation
: NoAnimation
);
387 onStyleOptionChanged(option
, previousOption
);
390 const KItemListStyleOption
& KItemListView::styleOption() const
392 return m_styleOption
;
395 void KItemListView::setGeometry(const QRectF
& rect
)
397 QGraphicsWidget::setGeometry(rect
);
403 const QSizeF newSize
= rect
.size();
404 if (m_itemSize
.isEmpty()) {
405 // The item size is dynamic:
406 // Changing the geometry does not require to do an expensive
407 // update of the visible-roles sizes, only the stretched sizes
408 // need to be adjusted to the new size.
409 updateStretchedVisibleRolesSizes();
411 if (m_useHeaderWidths
) {
412 QSizeF dynamicItemSize
= m_layouter
->itemSize();
414 if (m_itemSize
.width() < 0) {
415 const qreal requiredWidth
= visibleRolesSizesWidthSum();
416 if (newSize
.width() > requiredWidth
) {
417 dynamicItemSize
.setWidth(newSize
.width());
419 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
420 m_header
->resize(headerWidth
, m_header
->size().height());
423 if (m_itemSize
.height() < 0) {
424 const qreal requiredHeight
= visibleRolesSizesHeightSum();
425 if (newSize
.height() > requiredHeight
) {
426 dynamicItemSize
.setHeight(newSize
.height());
428 // TODO: KItemListHeader is not prepared for vertical alignment
431 m_layouter
->setItemSize(dynamicItemSize
);
434 // Triggering a synchronous layout is fine from a performance point of view,
435 // as with dynamic item sizes no moving animation must be done.
436 m_layouter
->setSize(newSize
);
439 const bool animate
= !changesItemGridLayout(newSize
,
440 m_layouter
->itemSize(),
441 m_layouter
->itemMargin());
442 m_layouter
->setSize(newSize
);
445 // Trigger an asynchronous relayout with m_layoutTimer to prevent
446 // performance bottlenecks. If the timer is exceeded, an animated layout
447 // will be triggered.
448 if (!m_layoutTimer
->isActive()) {
449 m_layoutTimer
->start();
452 m_layoutTimer
->stop();
453 doLayout(NoAnimation
);
458 int KItemListView::itemAt(const QPointF
& pos
) const
460 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
461 while (it
.hasNext()) {
464 const KItemListWidget
* widget
= it
.value();
465 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
466 if (widget
->contains(mappedPos
)) {
474 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
476 if (!m_enabledSelectionToggles
) {
480 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
482 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
483 if (!selectionToggleRect
.isEmpty()) {
484 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
485 return selectionToggleRect
.contains(mappedPos
);
491 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
493 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
495 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
496 if (!expansionToggleRect
.isEmpty()) {
497 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
498 return expansionToggleRect
.contains(mappedPos
);
504 int KItemListView::firstVisibleIndex() const
506 return m_layouter
->firstVisibleIndex();
509 int KItemListView::lastVisibleIndex() const
511 return m_layouter
->lastVisibleIndex();
514 QSizeF
KItemListView::itemSizeHint(int index
) const
520 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
522 Q_UNUSED(itemRanges
);
523 return QHash
<QByteArray
, QSizeF
>();
526 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
528 if (m_supportsItemExpanding
!= supportsExpanding
) {
529 m_supportsItemExpanding
= supportsExpanding
;
530 updateSiblingsInformation();
531 onSupportsItemExpandingChanged(supportsExpanding
);
535 bool KItemListView::supportsItemExpanding() const
537 return m_supportsItemExpanding
;
540 QRectF
KItemListView::itemRect(int index
) const
542 return m_layouter
->itemRect(index
);
545 QRectF
KItemListView::itemContextRect(int index
) const
549 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
551 contextRect
= widget
->iconRect() | widget
->textRect();
552 contextRect
.translate(itemRect(index
).topLeft());
558 void KItemListView::scrollToItem(int index
)
560 QRectF viewGeometry
= geometry();
562 const qreal headerHeight
= m_header
->size().height();
563 viewGeometry
.adjust(0, headerHeight
, 0, 0);
565 const QRectF currentRect
= itemRect(index
);
567 if (!viewGeometry
.contains(currentRect
)) {
568 qreal newOffset
= scrollOffset();
569 if (scrollOrientation() == Qt::Vertical
) {
570 if (currentRect
.top() < viewGeometry
.top()) {
571 newOffset
+= currentRect
.top() - viewGeometry
.top();
572 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
573 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
576 if (currentRect
.left() < viewGeometry
.left()) {
577 newOffset
+= currentRect
.left() - viewGeometry
.left();
578 } else if (currentRect
.right() > viewGeometry
.right()) {
579 newOffset
+= currentRect
.right() - viewGeometry
.right();
583 if (newOffset
!= scrollOffset()) {
584 emit
scrollTo(newOffset
);
589 void KItemListView::beginTransaction()
591 ++m_activeTransactions
;
592 if (m_activeTransactions
== 1) {
593 onTransactionBegin();
597 void KItemListView::endTransaction()
599 --m_activeTransactions
;
600 if (m_activeTransactions
< 0) {
601 m_activeTransactions
= 0;
602 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
605 if (m_activeTransactions
== 0) {
607 doLayout(m_endTransactionAnimationHint
);
608 m_endTransactionAnimationHint
= Animation
;
612 bool KItemListView::isTransactionActive() const
614 return m_activeTransactions
> 0;
617 void KItemListView::setHeaderShown(bool show
)
620 if (show
&& !m_header
) {
621 m_header
= new KItemListHeader(this);
622 m_header
->setPos(0, 0);
623 m_header
->setModel(m_model
);
624 m_header
->setVisibleRoles(m_visibleRoles
);
625 m_header
->setVisibleRolesWidths(headerRolesWidths());
626 m_header
->setZValue(1);
628 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
629 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
630 connect(m_header
, SIGNAL(visibleRoleMoved(QByteArray
,int,int)),
631 this, SLOT(slotVisibleRoleMoved(QByteArray
,int,int)));
632 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
633 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
634 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
635 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
637 m_useHeaderWidths
= false;
639 m_layouter
->setHeaderHeight(m_header
->size().height());
640 } else if (!show
&& m_header
) {
643 m_useHeaderWidths
= false;
644 m_layouter
->setHeaderHeight(0);
648 bool KItemListView::isHeaderShown() const
650 return m_header
!= 0;
653 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
659 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
661 QGraphicsWidget::paint(painter
, option
, widget
);
663 if (m_rubberBand
->isActive()) {
664 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
665 m_rubberBand
->endPosition()).normalized();
667 const QPointF topLeft
= rubberBandRect
.topLeft();
668 if (scrollOrientation() == Qt::Vertical
) {
669 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
671 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
674 QStyleOptionRubberBand opt
;
675 opt
.initFrom(widget
);
676 opt
.shape
= QRubberBand::Rectangle
;
678 opt
.rect
= rubberBandRect
.toRect();
679 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
683 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
688 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
690 Q_UNUSED(changedRoles
);
694 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
700 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
706 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
712 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
718 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
724 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
730 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
736 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
738 Q_UNUSED(supportsExpanding
);
741 void KItemListView::onTransactionBegin()
745 void KItemListView::onTransactionEnd()
749 bool KItemListView::event(QEvent
* event
)
751 // Forward all events to the controller and handle them there
752 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
756 return QGraphicsWidget::event(event
);
759 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
761 m_mousePos
= transform().map(event
->pos());
765 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
767 QGraphicsWidget::mouseMoveEvent(event
);
769 m_mousePos
= transform().map(event
->pos());
770 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
771 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
775 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
777 event
->setAccepted(true);
781 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
783 QGraphicsWidget::dragMoveEvent(event
);
785 m_mousePos
= transform().map(event
->pos());
786 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
787 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
791 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
793 QGraphicsWidget::dragLeaveEvent(event
);
794 setAutoScroll(false);
797 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
799 QGraphicsWidget::dropEvent(event
);
800 setAutoScroll(false);
803 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
805 return m_visibleItems
.values();
808 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
810 updateVisibleRolesSizes(itemRanges
);
812 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
813 if (hasMultipleRanges
) {
817 m_layouter
->markAsDirty();
819 int previouslyInsertedCount
= 0;
820 foreach (const KItemRange
& range
, itemRanges
) {
821 // range.index is related to the model before anything has been inserted.
822 // As in each loop the current item-range gets inserted the index must
823 // be increased by the already previously inserted items.
824 const int index
= range
.index
+ previouslyInsertedCount
;
825 const int count
= range
.count
;
826 if (index
< 0 || count
<= 0) {
827 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
830 previouslyInsertedCount
+= count
;
832 m_sizeHintResolver
->itemsInserted(index
, count
);
834 // Determine which visible items must be moved
835 QList
<int> itemsToMove
;
836 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
837 while (it
.hasNext()) {
839 const int visibleItemIndex
= it
.key();
840 if (visibleItemIndex
>= index
) {
841 itemsToMove
.append(visibleItemIndex
);
845 // Update the indexes of all KItemListWidget instances that are located
846 // after the inserted items. It is important to adjust the indexes in the order
847 // from the highest index to the lowest index to prevent overlaps when setting the new index.
849 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
850 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
852 const int newIndex
= widget
->index() + count
;
853 if (hasMultipleRanges
) {
854 setWidgetIndex(widget
, newIndex
);
856 // Try to animate the moving of the item
857 moveWidgetToIndex(widget
, newIndex
);
861 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
862 // Check whether a scrollbar is required to show the inserted items. In this case
863 // the size of the layouter will be decreased before calling doLayout(): This prevents
864 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
865 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
866 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
867 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
868 if (decreaseLayouterSize
) {
869 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
870 QSizeF layouterSize
= m_layouter
->size();
871 if (verticalScrollOrientation
) {
872 layouterSize
.rwidth() -= scrollBarExtent
;
874 layouterSize
.rheight() -= scrollBarExtent
;
876 m_layouter
->setSize(layouterSize
);
880 if (!hasMultipleRanges
) {
881 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
882 updateSiblingsInformation();
887 m_controller
->selectionManager()->itemsInserted(itemRanges
);
890 if (hasMultipleRanges
) {
892 // Important: Don't read any m_layouter-property inside the for-loop in case if
893 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
894 // updated in each loop-cycle and has only a consistent state after the loop.
895 Q_ASSERT(m_layouter
->isDirty());
897 m_endTransactionAnimationHint
= NoAnimation
;
899 updateSiblingsInformation();
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();
1004 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1006 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1007 m_layouter
->markAsDirty();
1010 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1013 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1014 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1016 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1017 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1019 updateWidgetProperties(widget
, index
);
1020 initializeItemListWidget(widget
);
1024 doLayout(NoAnimation
);
1025 updateSiblingsInformation();
1028 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1029 const QSet
<QByteArray
>& roles
)
1031 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1032 if (updateSizeHints
) {
1033 updateVisibleRolesSizes(itemRanges
);
1036 foreach (const KItemRange
& itemRange
, itemRanges
) {
1037 const int index
= itemRange
.index
;
1038 const int count
= itemRange
.count
;
1040 if (updateSizeHints
) {
1041 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1042 m_layouter
->markAsDirty();
1044 if (!m_layoutTimer
->isActive()) {
1045 m_layoutTimer
->start();
1049 // Apply the changed roles to the visible item-widgets
1050 const int lastIndex
= index
+ count
- 1;
1051 for (int i
= index
; i
<= lastIndex
; ++i
) {
1052 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1054 widget
->setData(m_model
->data(i
), roles
);
1058 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1059 // The sort-role has been changed which might result
1060 // in modified group headers
1061 updateVisibleGroupHeaders();
1062 doLayout(NoAnimation
);
1067 void KItemListView::slotGroupedSortingChanged(bool current
)
1069 m_grouped
= current
;
1070 m_layouter
->markAsDirty();
1073 updateGroupHeaderHeight();
1075 // Clear all visible headers
1076 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1077 while (it
.hasNext()) {
1079 recycleGroupHeaderForWidget(it
.key());
1081 Q_ASSERT(m_visibleGroups
.isEmpty());
1084 if (useAlternateBackgrounds()) {
1085 // Changing the group mode requires to update the alternate backgrounds
1086 // as with the enabled group mode the altering is done on base of the first
1088 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1089 while (it
.hasNext()) {
1091 updateAlternateBackgroundForWidget(it
.value());
1095 updateSiblingsInformation();
1096 doLayout(NoAnimation
);
1099 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1104 updateVisibleGroupHeaders();
1105 doLayout(NoAnimation
);
1109 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1114 updateVisibleGroupHeaders();
1115 doLayout(NoAnimation
);
1119 void KItemListView::slotCurrentChanged(int current
, int previous
)
1123 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1124 if (previousWidget
) {
1125 previousWidget
->setCurrent(false);
1128 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1129 if (currentWidget
) {
1130 currentWidget
->setCurrent(true);
1134 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1138 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1139 while (it
.hasNext()) {
1141 const int index
= it
.key();
1142 KItemListWidget
* widget
= it
.value();
1143 widget
->setSelected(current
.contains(index
));
1147 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1148 KItemListViewAnimation::AnimationType type
)
1150 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1151 Q_ASSERT(itemListWidget
);
1154 case KItemListViewAnimation::DeleteAnimation
: {
1155 // As we recycle the widget in this case it is important to assure that no
1156 // other animation has been started. This is a convention in KItemListView and
1157 // not a requirement defined by KItemListViewAnimation.
1158 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1160 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1161 // by m_visibleWidgets and must be deleted manually after the animation has
1163 recycleGroupHeaderForWidget(itemListWidget
);
1164 m_widgetCreator
->recycle(itemListWidget
);
1168 case KItemListViewAnimation::CreateAnimation
:
1169 case KItemListViewAnimation::MovingAnimation
:
1170 case KItemListViewAnimation::ResizeAnimation
: {
1171 const int index
= itemListWidget
->index();
1172 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1173 (index
> m_layouter
->lastVisibleIndex());
1174 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1175 recycleWidget(itemListWidget
);
1184 void KItemListView::slotLayoutTimerFinished()
1186 m_layouter
->setSize(geometry().size());
1187 doLayout(Animation
);
1190 void KItemListView::slotRubberBandPosChanged()
1195 void KItemListView::slotRubberBandActivationChanged(bool active
)
1198 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1199 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1200 m_skipAutoScrollForRubberBand
= true;
1202 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1203 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1204 m_skipAutoScrollForRubberBand
= false;
1210 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1212 qreal previousWidth
)
1214 Q_UNUSED(previousWidth
);
1216 m_useHeaderWidths
= true;
1218 if (m_visibleRolesSizes
.contains(role
)) {
1219 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1220 roleSize
.setWidth(currentWidth
);
1221 m_visibleRolesSizes
.insert(role
, roleSize
);
1222 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1224 // Apply the new size to the layouter
1225 QSizeF dynamicItemSize
= m_itemSize
;
1226 if (dynamicItemSize
.width() < 0) {
1227 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1228 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1230 if (dynamicItemSize
.height() < 0) {
1231 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1232 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1235 m_layouter
->setItemSize(dynamicItemSize
);
1237 // Update the role sizes for all visible widgets
1238 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1239 while (it
.hasNext()) {
1241 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1243 doLayout(NoAnimation
);
1247 void KItemListView::slotVisibleRoleMoved(const QByteArray
& role
,
1251 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1253 const QList
<QByteArray
> previous
= m_visibleRoles
;
1255 QList
<QByteArray
> current
= m_visibleRoles
;
1256 current
.removeAt(previousIndex
);
1257 current
.insert(currentIndex
, role
);
1259 setVisibleRoles(current
);
1261 emit
visibleRolesChanged(current
, previous
);
1264 void KItemListView::triggerAutoScrolling()
1266 if (!m_autoScrollTimer
) {
1271 int visibleSize
= 0;
1272 if (scrollOrientation() == Qt::Vertical
) {
1273 pos
= m_mousePos
.y();
1274 visibleSize
= size().height();
1276 pos
= m_mousePos
.x();
1277 visibleSize
= size().width();
1280 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1281 m_autoScrollIncrement
= 0;
1284 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1285 if (m_autoScrollIncrement
== 0) {
1286 // The mouse position is not above an autoscroll margin (the autoscroll timer
1287 // will be restarted in mouseMoveEvent())
1288 m_autoScrollTimer
->stop();
1292 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1293 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1294 // if the direction of the rubberband is similar to the autoscroll direction. This
1295 // prevents that starting to create a rubberband within the autoscroll margins starts
1296 // an autoscrolling.
1298 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1299 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1300 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1301 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1302 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1303 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1304 // been moved up although the autoscroll direction might be down)
1305 m_autoScrollTimer
->stop();
1310 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1311 // the autoscrolling may not get skipped anymore until a new rubberband is created
1312 m_skipAutoScrollForRubberBand
= false;
1314 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1315 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1316 setScrollOffset(newScrollOffset
);
1318 // Trigger the autoscroll timer which will periodically call
1319 // triggerAutoScrolling()
1320 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1323 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1325 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1327 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1328 Q_ASSERT(groupHeader
);
1329 updateGroupHeaderLayout(widget
);
1332 void KItemListView::setController(KItemListController
* controller
)
1334 if (m_controller
!= controller
) {
1335 KItemListController
* previous
= m_controller
;
1337 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1338 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1339 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1342 m_controller
= controller
;
1345 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1346 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1347 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1350 onControllerChanged(controller
, previous
);
1354 void KItemListView::setModel(KItemModelBase
* model
)
1356 if (m_model
== model
) {
1360 KItemModelBase
* previous
= m_model
;
1363 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1364 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1365 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1366 this, SLOT(slotItemsInserted(KItemRangeList
)));
1367 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1368 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1369 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1370 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1371 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1372 this, SLOT(slotGroupedSortingChanged(bool)));
1373 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1374 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1375 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1376 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1380 m_layouter
->setModel(model
);
1381 m_grouped
= model
->groupedSorting();
1384 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1385 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1386 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1387 this, SLOT(slotItemsInserted(KItemRangeList
)));
1388 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1389 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1390 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1391 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1392 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1393 this, SLOT(slotGroupedSortingChanged(bool)));
1394 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1395 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1396 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1397 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1400 onModelChanged(model
, previous
);
1403 KItemListRubberBand
* KItemListView::rubberBand() const
1405 return m_rubberBand
;
1408 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1410 if (m_layoutTimer
->isActive()) {
1411 m_layoutTimer
->stop();
1414 if (m_activeTransactions
> 0) {
1415 if (hint
== NoAnimation
) {
1416 // As soon as at least one property change should be done without animation,
1417 // the whole transaction will be marked as not animated.
1418 m_endTransactionAnimationHint
= NoAnimation
;
1423 if (!m_model
|| m_model
->count() < 0) {
1427 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1428 if (firstVisibleIndex
< 0) {
1429 emitOffsetChanges();
1433 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1434 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1435 // is still shown if the maximum offset got decreased.
1436 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1437 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1438 if (scrollOffset() > maxOffsetToShowFullRange
) {
1439 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1440 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1443 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1445 int firstSibblingIndex
= -1;
1446 int lastSibblingIndex
= -1;
1447 const bool supportsExpanding
= supportsItemExpanding();
1449 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1451 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1452 // instances from invisible items are reused. If no reusable items are
1453 // found then new KItemListWidget instances get created.
1454 const bool animate
= (hint
== Animation
);
1455 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1456 bool applyNewPos
= true;
1457 bool wasHidden
= false;
1459 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1460 const QPointF newPos
= itemBounds
.topLeft();
1461 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1464 if (!reusableItems
.isEmpty()) {
1465 // Reuse a KItemListWidget instance from an invisible item
1466 const int oldIndex
= reusableItems
.takeLast();
1467 widget
= m_visibleItems
.value(oldIndex
);
1468 setWidgetIndex(widget
, i
);
1469 updateWidgetProperties(widget
, i
);
1470 initializeItemListWidget(widget
);
1472 // No reusable KItemListWidget instance is available, create a new one
1473 widget
= createWidget(i
);
1475 widget
->resize(itemBounds
.size());
1477 if (animate
&& changedCount
< 0) {
1478 // Items have been deleted, move the created item to the
1479 // imaginary old position. They will get animated to the new position
1481 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1482 if (itemRect
.isEmpty()) {
1483 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1484 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1485 widget
->setPos(invisibleOldPos
);
1487 widget
->setPos(itemRect
.topLeft());
1489 applyNewPos
= false;
1492 if (supportsExpanding
&& changedCount
== 0) {
1493 if (firstSibblingIndex
< 0) {
1494 firstSibblingIndex
= i
;
1496 lastSibblingIndex
= i
;
1501 const bool itemsRemoved
= (changedCount
< 0);
1502 const bool itemsInserted
= (changedCount
> 0);
1503 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1504 // The item is located after the removed items. Animate the moving of the position.
1505 applyNewPos
= !moveWidget(widget
, newPos
);
1506 } else if (itemsInserted
&& i
>= changedIndex
) {
1507 // The item is located after the first inserted item
1508 if (i
<= changedIndex
+ changedCount
- 1) {
1509 // The item is an inserted item. Animate the appearing of the item.
1510 // For performance reasons no animation is done when changedCount is equal
1511 // to all available items.
1512 if (changedCount
< m_model
->count()) {
1513 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1515 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1516 // The item was already there before, so animate the moving of the position.
1517 // No moving animation is done if the item is animated by a create animation: This
1518 // prevents a "move animation mess" when inserting several ranges in parallel.
1519 applyNewPos
= !moveWidget(widget
, newPos
);
1521 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1522 // The size of the view might have been changed. Animate the moving of the position.
1523 applyNewPos
= !moveWidget(widget
, newPos
);
1526 m_animation
->stop(widget
);
1530 widget
->setPos(newPos
);
1533 Q_ASSERT(widget
->index() == i
);
1534 widget
->setVisible(true);
1536 if (widget
->size() != itemBounds
.size()) {
1537 // Resize the widget for the item to the changed size.
1539 // If a dynamic item size is used then no animation is done in the direction
1540 // of the dynamic size.
1541 if (m_itemSize
.width() <= 0) {
1542 // The width is dynamic, apply the new width without animation.
1543 widget
->resize(itemBounds
.width(), widget
->size().height());
1544 } else if (m_itemSize
.height() <= 0) {
1545 // The height is dynamic, apply the new height without animation.
1546 widget
->resize(widget
->size().width(), itemBounds
.height());
1548 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1550 widget
->resize(itemBounds
.size());
1554 // Updating the cell-information must be done as last step: The decision whether the
1555 // moving-animation should be started at all is based on the previous cell-information.
1556 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1557 m_visibleCells
.insert(i
, cell
);
1560 // Delete invisible KItemListWidget instances that have not been reused
1561 foreach (int index
, reusableItems
) {
1562 recycleWidget(m_visibleItems
.value(index
));
1565 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1566 Q_ASSERT(lastSibblingIndex
>= 0);
1567 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1571 // Update the layout of all visible group headers
1572 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1573 while (it
.hasNext()) {
1575 updateGroupHeaderLayout(it
.key());
1579 emitOffsetChanges();
1582 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1583 int lastVisibleIndex
,
1584 LayoutAnimationHint hint
)
1586 // Determine all items that are completely invisible and might be
1587 // reused for items that just got (at least partly) visible. If the
1588 // animation hint is set to 'Animation' items that do e.g. an animated
1589 // moving of their position are not marked as invisible: This assures
1590 // that a scrolling inside the view can be done without breaking an animation.
1594 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1595 while (it
.hasNext()) {
1598 KItemListWidget
* widget
= it
.value();
1599 const int index
= widget
->index();
1600 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1603 if (m_animation
->isStarted(widget
)) {
1604 if (hint
== NoAnimation
) {
1605 // Stopping the animation will call KItemListView::slotAnimationFinished()
1606 // and the widget will be recycled if necessary there.
1607 m_animation
->stop(widget
);
1610 widget
->setVisible(false);
1611 items
.append(index
);
1614 recycleGroupHeaderForWidget(widget
);
1623 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1625 if (widget
->pos() == newPos
) {
1629 bool startMovingAnim
= false;
1631 // When having a grid the moving-animation should only be started, if it is done within
1632 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1633 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1634 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1635 const int index
= widget
->index();
1636 const Cell cell
= m_visibleCells
.value(index
);
1637 if (cell
.column
>= 0 && cell
.row
>= 0) {
1638 if (scrollOrientation() == Qt::Vertical
) {
1639 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1641 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1645 if (startMovingAnim
) {
1646 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1650 m_animation
->stop(widget
);
1651 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1655 void KItemListView::emitOffsetChanges()
1657 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1658 if (m_oldScrollOffset
!= newScrollOffset
) {
1659 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1660 m_oldScrollOffset
= newScrollOffset
;
1663 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1664 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1665 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1666 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1669 const qreal newItemOffset
= m_layouter
->itemOffset();
1670 if (m_oldItemOffset
!= newItemOffset
) {
1671 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1672 m_oldItemOffset
= newItemOffset
;
1675 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1676 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1677 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1678 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1682 KItemListWidget
* KItemListView::createWidget(int index
)
1684 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1685 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1687 m_visibleItems
.insert(index
, widget
);
1688 m_visibleCells
.insert(index
, Cell());
1689 updateWidgetProperties(widget
, index
);
1690 initializeItemListWidget(widget
);
1694 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1697 recycleGroupHeaderForWidget(widget
);
1700 const int index
= widget
->index();
1701 m_visibleItems
.remove(index
);
1702 m_visibleCells
.remove(index
);
1704 m_widgetCreator
->recycle(widget
);
1707 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1709 const int oldIndex
= widget
->index();
1710 m_visibleItems
.remove(oldIndex
);
1711 m_visibleCells
.remove(oldIndex
);
1713 m_visibleItems
.insert(index
, widget
);
1714 m_visibleCells
.insert(index
, Cell());
1716 widget
->setIndex(index
);
1719 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1721 const int oldIndex
= widget
->index();
1722 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1724 setWidgetIndex(widget
, index
);
1726 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1727 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1728 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1729 (!vertical
&& oldCell
.column
== newCell
.column
);
1731 m_visibleCells
.insert(index
, newCell
);
1735 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1738 case LayouterSize
: m_layouter
->setSize(size
); break;
1739 case ItemSize
: m_layouter
->setItemSize(size
); break;
1744 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1746 widget
->setVisibleRoles(m_visibleRoles
);
1747 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1748 widget
->setStyleOption(m_styleOption
);
1750 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1751 widget
->setCurrent(index
== selectionManager
->currentItem());
1752 widget
->setSelected(selectionManager
->isSelected(index
));
1753 widget
->setHovered(false);
1754 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1755 widget
->setIndex(index
);
1756 widget
->setData(m_model
->data(index
));
1757 widget
->setSiblingsInformation(QBitArray());
1758 updateAlternateBackgroundForWidget(widget
);
1761 updateGroupHeaderForWidget(widget
);
1765 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1767 Q_ASSERT(m_grouped
);
1769 const int index
= widget
->index();
1770 if (!m_layouter
->isFirstGroupItem(index
)) {
1771 // The widget does not represent the first item of a group
1772 // and hence requires no header
1773 recycleGroupHeaderForWidget(widget
);
1777 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1778 if (groups
.isEmpty()) {
1782 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1784 groupHeader
= m_groupHeaderCreator
->create(this);
1785 groupHeader
->setParentItem(widget
);
1786 m_visibleGroups
.insert(widget
, groupHeader
);
1787 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1789 Q_ASSERT(groupHeader
->parentItem() == widget
);
1791 const int groupIndex
= groupIndexForItem(index
);
1792 Q_ASSERT(groupIndex
>= 0);
1793 groupHeader
->setData(groups
.at(groupIndex
).second
);
1794 groupHeader
->setRole(model()->sortRole());
1795 groupHeader
->setStyleOption(m_styleOption
);
1796 groupHeader
->setScrollOrientation(scrollOrientation());
1797 groupHeader
->setItemIndex(index
);
1799 groupHeader
->show();
1802 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1804 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1805 Q_ASSERT(groupHeader
);
1807 const int index
= widget
->index();
1808 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1809 const QRectF itemRect
= m_layouter
->itemRect(index
);
1811 // The group-header is a child of the itemlist widget. Translate the
1812 // group header position to the relative position.
1813 if (scrollOrientation() == Qt::Vertical
) {
1814 // In the vertical scroll orientation the group header should always span
1815 // the whole width no matter which temporary position the parent widget
1816 // has. In this case the x-position and width will be adjusted manually.
1817 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1818 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1820 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1821 groupHeader
->resize(groupHeaderRect
.size());
1825 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1827 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1829 header
->setParentItem(0);
1830 m_groupHeaderCreator
->recycle(header
);
1831 m_visibleGroups
.remove(widget
);
1832 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1836 void KItemListView::updateVisibleGroupHeaders()
1838 Q_ASSERT(m_grouped
);
1839 m_layouter
->markAsDirty();
1841 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1842 while (it
.hasNext()) {
1844 updateGroupHeaderForWidget(it
.value());
1848 int KItemListView::groupIndexForItem(int index
) const
1850 Q_ASSERT(m_grouped
);
1852 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1853 if (groups
.isEmpty()) {
1858 int max
= groups
.count() - 1;
1861 mid
= (min
+ max
) / 2;
1862 if (index
> groups
[mid
].first
) {
1867 } while (groups
[mid
].first
!= index
&& min
<= max
);
1870 while (groups
[mid
].first
> index
&& mid
> 0) {
1878 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1880 bool enabled
= useAlternateBackgrounds();
1882 const int index
= widget
->index();
1883 enabled
= (index
& 0x1) > 0;
1885 const int groupIndex
= groupIndexForItem(index
);
1886 if (groupIndex
>= 0) {
1887 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1888 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1889 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1890 enabled
= (relativeIndex
& 0x1) > 0;
1894 widget
->setAlternateBackground(enabled
);
1897 bool KItemListView::useAlternateBackgrounds() const
1899 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1902 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1904 QHash
<QByteArray
, qreal
> rolesWidths
;
1906 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1907 while (it
.hasNext()) {
1909 rolesWidths
.insert(it
.key(), it
.value().width());
1915 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1917 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1921 const int itemCount
= m_model
->count();
1922 int rangesItemCount
= 0;
1923 foreach (const KItemRange
& range
, itemRanges
) {
1924 rangesItemCount
+= range
.count
;
1927 if (itemCount
== rangesItemCount
) {
1928 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1930 // Assure the the sizes are not smaller than the minimum defined by the header
1931 // TODO: Currently only implemented for a top-aligned header
1932 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1933 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1934 while (it
.hasNext()) {
1936 const QSizeF
& size
= it
.value();
1937 if (size
.width() < minHeaderRoleWidth
) {
1938 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1939 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1944 // Only a sub range of the roles need to be determined.
1945 // The chances are good that the sizes of the sub ranges
1946 // already fit into the available sizes and hence no
1947 // expensive update might be required.
1948 bool updateRequired
= false;
1950 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1951 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1952 while (it
.hasNext()) {
1954 const QByteArray
& role
= it
.key();
1955 const QSizeF
& updatedSize
= it
.value();
1956 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1957 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1958 m_visibleRolesSizes
.insert(role
, updatedSize
);
1959 updateRequired
= true;
1963 if (!updateRequired
) {
1964 // All the updated sizes are smaller than the current sizes and no change
1965 // of the stretched roles-widths is required
1970 updateStretchedVisibleRolesSizes();
1973 void KItemListView::updateVisibleRolesSizes()
1979 const int itemCount
= m_model
->count();
1980 if (itemCount
> 0) {
1981 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1985 void KItemListView::updateStretchedVisibleRolesSizes()
1987 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1991 // Calculate the maximum size of an item by considering the
1992 // visible role sizes and apply them to the layouter. If the
1993 // size does not use the available view-size it the size of the
1994 // first role will get stretched.
1995 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1996 const QByteArray role
= m_visibleRoles
.first();
1997 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1999 QSizeF dynamicItemSize
= m_itemSize
;
2001 if (dynamicItemSize
.width() <= 0) {
2002 const qreal requiredWidth
= visibleRolesSizesWidthSum();
2003 const qreal availableWidth
= size().width();
2004 if (requiredWidth
< availableWidth
) {
2005 // Stretch the first role to use the whole width for the item
2006 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
2007 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
2009 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
2012 if (dynamicItemSize
.height() <= 0) {
2013 const qreal requiredHeight
= visibleRolesSizesHeightSum();
2014 const qreal availableHeight
= size().height();
2015 if (requiredHeight
< availableHeight
) {
2016 // Stretch the first role to use the whole height for the item
2017 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
2018 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
2020 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
2023 m_layouter
->setItemSize(dynamicItemSize
);
2026 m_header
->setVisibleRolesWidths(headerRolesWidths());
2027 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
2030 // Update the role sizes for all visible widgets
2031 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2032 while (it
.hasNext()) {
2034 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
2038 qreal
KItemListView::visibleRolesSizesWidthSum() const
2041 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2042 while (it
.hasNext()) {
2044 widthSum
+= it
.value().width();
2049 qreal
KItemListView::visibleRolesSizesHeightSum() const
2051 qreal heightSum
= 0;
2052 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2053 while (it
.hasNext()) {
2055 heightSum
+= it
.value().height();
2060 QRectF
KItemListView::headerBoundaries() const
2062 return m_header
? m_header
->geometry() : QRectF();
2065 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2066 const QSizeF
& newItemSize
,
2067 const QSizeF
& newItemMargin
) const
2069 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2073 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2074 const qreal itemWidth
= m_layouter
->itemSize().width();
2075 if (itemWidth
> 0) {
2076 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2077 newItemSize
.width(),
2078 newItemMargin
.width());
2079 if (m_model
->count() > newColumnCount
) {
2080 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2082 m_layouter
->itemMargin().width());
2083 return oldColumnCount
!= newColumnCount
;
2087 const qreal itemHeight
= m_layouter
->itemSize().height();
2088 if (itemHeight
> 0) {
2089 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2090 newItemSize
.height(),
2091 newItemMargin
.height());
2092 if (m_model
->count() > newRowCount
) {
2093 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2095 m_layouter
->itemMargin().height());
2096 return oldRowCount
!= newRowCount
;
2104 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2106 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2110 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2111 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2112 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2113 // Only animate if up to 2/3 of a row or column are inserted or removed
2114 return changedItemCount
<= maximum
* 2 / 3;
2118 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2120 const QSizeF oldSize
= m_layouter
->size();
2122 m_layouter
->setSize(size
);
2123 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2124 m_layouter
->setSize(oldSize
);
2126 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2127 : maxOffset
> size
.width();
2130 void KItemListView::updateGroupHeaderHeight()
2132 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2133 qreal groupHeaderMargin
= 0;
2135 if (scrollOrientation() == Qt::Horizontal
) {
2136 // The vertical margin above and below the header should be
2137 // equal to the horizontal margin, not the vertical margin
2138 // from m_styleOption.
2139 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2140 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2141 } else if (m_itemSize
.isEmpty()){
2142 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2143 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2145 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2146 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2148 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2149 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2151 updateVisibleGroupHeaders();
2154 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2156 if (!supportsItemExpanding() || !m_model
) {
2160 if (firstIndex
< 0 || lastIndex
< 0) {
2161 firstIndex
= m_layouter
->firstVisibleIndex();
2162 lastIndex
= m_layouter
->lastVisibleIndex();
2164 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2165 lastIndex
>= m_layouter
->firstVisibleIndex());
2166 if (!isRangeVisible
) {
2171 int previousParents
= 0;
2172 QBitArray previousSiblings
;
2174 // The rootIndex describes the first index where the siblings get
2175 // calculated from. For the calculation the upper most parent item
2176 // is required. For performance reasons it is checked first whether
2177 // the visible items before or after the current range already
2178 // contain a siblings information which can be used as base.
2179 int rootIndex
= firstIndex
;
2181 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2183 // There is no visible widget before the range, check whether there
2184 // is one after the range:
2185 widget
= m_visibleItems
.value(lastIndex
+ 1);
2187 // The sibling information of the widget may only be used if
2188 // all items of the range have the same number of parents.
2189 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2190 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2191 if (m_model
->expandedParentsCount(i
) != parents
) {
2200 // Performance optimization: Use the sibling information of the visible
2201 // widget beside the given range.
2202 previousSiblings
= widget
->siblingsInformation();
2203 if (previousSiblings
.isEmpty()) {
2206 previousParents
= previousSiblings
.count() - 1;
2207 previousSiblings
.truncate(previousParents
);
2209 // Potentially slow path: Go back to the upper most parent of firstIndex
2210 // to be able to calculate the initial value for the siblings.
2211 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2216 Q_ASSERT(previousParents
>= 0);
2217 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2218 // Update the parent-siblings in case if the current item represents
2219 // a child or an upper parent.
2220 const int currentParents
= m_model
->expandedParentsCount(i
);
2221 Q_ASSERT(currentParents
>= 0);
2222 if (previousParents
< currentParents
) {
2223 previousParents
= currentParents
;
2224 previousSiblings
.resize(currentParents
);
2225 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2226 } else if (previousParents
> currentParents
) {
2227 previousParents
= currentParents
;
2228 previousSiblings
.truncate(currentParents
);
2231 if (i
>= firstIndex
) {
2232 // The index represents a visible item. Apply the parent-siblings
2233 // and update the sibling of the current item.
2234 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2239 QBitArray siblings
= previousSiblings
;
2240 siblings
.resize(siblings
.count() + 1);
2241 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2243 widget
->setSiblingsInformation(siblings
);
2248 bool KItemListView::hasSiblingSuccessor(int index
) const
2250 bool hasSuccessor
= false;
2251 const int parentsCount
= m_model
->expandedParentsCount(index
);
2252 int successorIndex
= index
+ 1;
2254 // Search the next sibling
2255 const int itemCount
= m_model
->count();
2256 while (successorIndex
< itemCount
) {
2257 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2258 if (currentParentsCount
== parentsCount
) {
2259 hasSuccessor
= true;
2261 } else if (currentParentsCount
< parentsCount
) {
2267 if (m_grouped
&& hasSuccessor
) {
2268 // If the sibling is part of another group, don't mark it as
2269 // successor as the group header is between the sibling connections.
2270 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2271 if (m_layouter
->isFirstGroupItem(i
)) {
2272 hasSuccessor
= false;
2278 return hasSuccessor
;
2281 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2285 const int minSpeed
= 4;
2286 const int maxSpeed
= 128;
2287 const int speedLimiter
= 96;
2288 const int autoScrollBorder
= 64;
2290 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2291 // This assures that the autoscrolling speed grows gradually.
2292 const int incLimiter
= 1;
2294 if (pos
< autoScrollBorder
) {
2295 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2296 inc
= qMax(inc
, -maxSpeed
);
2297 inc
= qMax(inc
, oldInc
- incLimiter
);
2298 } else if (pos
> range
- autoScrollBorder
) {
2299 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2300 inc
= qMin(inc
, maxSpeed
);
2301 inc
= qMin(inc
, oldInc
+ incLimiter
);
2307 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2309 const qreal availableSize
= size
- itemMargin
;
2310 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2316 KItemListCreatorBase::~KItemListCreatorBase()
2318 qDeleteAll(m_recycleableWidgets
);
2319 qDeleteAll(m_createdWidgets
);
2322 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2324 m_createdWidgets
.insert(widget
);
2327 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2329 Q_ASSERT(m_createdWidgets
.contains(widget
));
2330 m_createdWidgets
.remove(widget
);
2332 if (m_recycleableWidgets
.count() < 100) {
2333 m_recycleableWidgets
.append(widget
);
2334 widget
->setVisible(false);
2340 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2342 if (m_recycleableWidgets
.isEmpty()) {
2346 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2347 m_createdWidgets
.insert(widget
);
2351 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2355 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2357 widget
->setParentItem(0);
2358 widget
->setOpacity(1.0);
2359 pushRecycleableWidget(widget
);
2362 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2366 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2368 header
->setOpacity(1.0);
2369 pushRecycleableWidget(header
);
2372 #include "kitemlistview.moc"