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_activeTransactions(0),
58 m_endTransactionAnimationHint(Animation
),
63 m_visibleRolesSizes(),
64 m_stretchedVisibleRolesSizes(),
66 m_groupHeaderCreator(0),
70 m_sizeHintResolver(0),
75 m_oldMaximumScrollOffset(0),
77 m_oldMaximumItemOffset(0),
78 m_skipAutoScrollForRubberBand(false),
81 m_autoScrollIncrement(0),
84 m_useHeaderWidths(false)
86 setAcceptHoverEvents(true);
88 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
90 m_layouter
= new KItemListViewLayouter(this);
91 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
93 m_animation
= new KItemListViewAnimation(this);
94 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
95 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
97 m_layoutTimer
= new QTimer(this);
98 m_layoutTimer
->setInterval(300);
99 m_layoutTimer
->setSingleShot(true);
100 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
102 m_rubberBand
= new KItemListRubberBand(this);
103 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
106 KItemListView::~KItemListView()
108 delete m_sizeHintResolver
;
109 m_sizeHintResolver
= 0;
112 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
114 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
115 if (orientation
== previousOrientation
) {
119 m_layouter
->setScrollOrientation(orientation
);
120 m_animation
->setScrollOrientation(orientation
);
121 m_sizeHintResolver
->clearCache();
124 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
125 while (it
.hasNext()) {
127 it
.value()->setScrollOrientation(orientation
);
129 updateGroupHeaderHeight();
133 doLayout(NoAnimation
);
135 onScrollOrientationChanged(orientation
, previousOrientation
);
136 emit
scrollOrientationChanged(orientation
, previousOrientation
);
139 Qt::Orientation
KItemListView::scrollOrientation() const
141 return m_layouter
->scrollOrientation();
144 void KItemListView::setItemSize(const QSizeF
& itemSize
)
146 const QSizeF previousSize
= m_itemSize
;
147 if (itemSize
== previousSize
) {
151 // Skip animations when the number of rows or columns
152 // are changed in the grid layout. Although the animation
153 // engine can handle this usecase, it looks obtrusive.
154 const bool animate
= !changesItemGridLayout(m_layouter
->size(), itemSize
);
156 m_itemSize
= itemSize
;
158 if (itemSize
.isEmpty()) {
159 updateVisibleRolesSizes();
161 m_layouter
->setItemSize(itemSize
);
164 m_sizeHintResolver
->clearCache();
165 doLayout(animate
? Animation
: NoAnimation
);
166 onItemSizeChanged(itemSize
, previousSize
);
169 QSizeF
KItemListView::itemSize() const
174 void KItemListView::setScrollOffset(qreal offset
)
180 const qreal previousOffset
= m_layouter
->scrollOffset();
181 if (offset
== previousOffset
) {
185 m_layouter
->setScrollOffset(offset
);
186 m_animation
->setScrollOffset(offset
);
188 // Don't check whether the m_layoutTimer is active: Changing the
189 // scroll offset must always trigger a synchronous layout, otherwise
190 // the smooth-scrolling might get jerky.
191 doLayout(NoAnimation
);
192 onScrollOffsetChanged(offset
, previousOffset
);
195 qreal
KItemListView::scrollOffset() const
197 return m_layouter
->scrollOffset();
200 qreal
KItemListView::maximumScrollOffset() const
202 return m_layouter
->maximumScrollOffset();
205 void KItemListView::setItemOffset(qreal offset
)
207 if (m_layouter
->itemOffset() == offset
) {
211 m_layouter
->setItemOffset(offset
);
213 m_header
->setPos(-offset
, 0);
216 // Don't check whether the m_layoutTimer is active: Changing the
217 // item offset must always trigger a synchronous layout, otherwise
218 // the smooth-scrolling might get jerky.
219 doLayout(NoAnimation
);
222 qreal
KItemListView::itemOffset() const
224 return m_layouter
->itemOffset();
227 qreal
KItemListView::maximumItemOffset() const
229 return m_layouter
->maximumItemOffset();
232 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
234 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
235 m_visibleRoles
= roles
;
237 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
238 while (it
.hasNext()) {
240 KItemListWidget
* widget
= it
.value();
241 widget
->setVisibleRoles(roles
);
242 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
245 m_sizeHintResolver
->clearCache();
246 m_layouter
->markAsDirty();
249 m_header
->setVisibleRoles(roles
);
250 m_header
->setVisibleRolesWidths(headerRolesWidths());
251 m_useHeaderWidths
= false;
254 updateVisibleRolesSizes();
255 doLayout(NoAnimation
);
257 onVisibleRolesChanged(roles
, previousRoles
);
260 QList
<QByteArray
> KItemListView::visibleRoles() const
262 return m_visibleRoles
;
265 void KItemListView::setAutoScroll(bool enabled
)
267 if (enabled
&& !m_autoScrollTimer
) {
268 m_autoScrollTimer
= new QTimer(this);
269 m_autoScrollTimer
->setSingleShot(true);
270 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
271 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
272 } else if (!enabled
&& m_autoScrollTimer
) {
273 delete m_autoScrollTimer
;
274 m_autoScrollTimer
= 0;
279 bool KItemListView::autoScroll() const
281 return m_autoScrollTimer
!= 0;
284 void KItemListView::setEnabledSelectionToggles(bool enabled
)
286 if (m_enabledSelectionToggles
!= enabled
) {
287 m_enabledSelectionToggles
= enabled
;
289 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
290 while (it
.hasNext()) {
292 it
.value()->setEnabledSelectionToggle(enabled
);
297 bool KItemListView::enabledSelectionToggles() const
299 return m_enabledSelectionToggles
;
302 KItemListController
* KItemListView::controller() const
307 KItemModelBase
* KItemListView::model() const
312 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
314 m_widgetCreator
= widgetCreator
;
317 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
319 return m_widgetCreator
;
322 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
324 m_groupHeaderCreator
= groupHeaderCreator
;
327 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
329 return m_groupHeaderCreator
;
332 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
334 const KItemListStyleOption previousOption
= m_styleOption
;
335 m_styleOption
= option
;
338 updateGroupHeaderHeight();
341 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
342 while (it
.hasNext()) {
344 it
.value()->setStyleOption(option
);
347 m_sizeHintResolver
->clearCache();
350 onStyleOptionChanged(option
, previousOption
);
353 const KItemListStyleOption
& KItemListView::styleOption() const
355 return m_styleOption
;
358 void KItemListView::setGeometry(const QRectF
& rect
)
360 QGraphicsWidget::setGeometry(rect
);
366 const QSizeF newSize
= rect
.size();
367 if (m_itemSize
.isEmpty()) {
368 // The item size is dynamic:
369 // Changing the geometry does not require to do an expensive
370 // update of the visible-roles sizes, only the stretched sizes
371 // need to be adjusted to the new size.
372 updateStretchedVisibleRolesSizes();
374 if (m_useHeaderWidths
) {
375 QSizeF dynamicItemSize
= m_layouter
->itemSize();
377 if (m_itemSize
.width() < 0) {
378 const qreal requiredWidth
= visibleRolesSizesWidthSum();
379 if (newSize
.width() > requiredWidth
) {
380 dynamicItemSize
.setWidth(newSize
.width());
382 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
383 m_header
->resize(headerWidth
, m_header
->size().height());
386 if (m_itemSize
.height() < 0) {
387 const qreal requiredHeight
= visibleRolesSizesHeightSum();
388 if (newSize
.height() > requiredHeight
) {
389 dynamicItemSize
.setHeight(newSize
.height());
391 // TODO: KItemListHeader is not prepared for vertical alignment
394 m_layouter
->setItemSize(dynamicItemSize
);
397 // Triggering a synchronous layout is fine from a performance point of view,
398 // as with dynamic item sizes no moving animation must be done.
399 m_layouter
->setSize(newSize
);
402 const bool animate
= !changesItemGridLayout(newSize
, m_layouter
->itemSize());
403 m_layouter
->setSize(newSize
);
406 // Trigger an asynchronous relayout with m_layoutTimer to prevent
407 // performance bottlenecks. If the timer is exceeded, an animated layout
408 // will be triggered.
409 if (!m_layoutTimer
->isActive()) {
410 m_layoutTimer
->start();
413 m_layoutTimer
->stop();
414 doLayout(NoAnimation
);
419 int KItemListView::itemAt(const QPointF
& pos
) const
421 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
422 while (it
.hasNext()) {
425 const KItemListWidget
* widget
= it
.value();
426 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
427 if (widget
->contains(mappedPos
)) {
435 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
437 if (!m_enabledSelectionToggles
) {
441 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
443 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
444 if (!selectionToggleRect
.isEmpty()) {
445 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
446 return selectionToggleRect
.contains(mappedPos
);
452 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
454 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
456 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
457 if (!expansionToggleRect
.isEmpty()) {
458 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
459 return expansionToggleRect
.contains(mappedPos
);
465 int KItemListView::firstVisibleIndex() const
467 return m_layouter
->firstVisibleIndex();
470 int KItemListView::lastVisibleIndex() const
472 return m_layouter
->lastVisibleIndex();
475 QSizeF
KItemListView::itemSizeHint(int index
) const
481 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
483 Q_UNUSED(itemRanges
);
484 return QHash
<QByteArray
, QSizeF
>();
487 bool KItemListView::supportsItemExpanding() const
492 QRectF
KItemListView::itemRect(int index
) const
494 return m_layouter
->itemRect(index
);
497 QRectF
KItemListView::itemContextRect(int index
) const
501 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
503 contextRect
= widget
->iconRect() | widget
->textRect();
504 contextRect
.translate(itemRect(index
).topLeft());
510 void KItemListView::scrollToItem(int index
)
512 QRectF viewGeometry
= geometry();
514 const qreal headerHeight
= m_header
->size().height();
515 viewGeometry
.adjust(0, headerHeight
, 0, 0);
517 const QRectF currentRect
= itemRect(index
);
519 if (!viewGeometry
.contains(currentRect
)) {
520 qreal newOffset
= scrollOffset();
521 if (scrollOrientation() == Qt::Vertical
) {
522 if (currentRect
.top() < viewGeometry
.top()) {
523 newOffset
+= currentRect
.top() - viewGeometry
.top();
524 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
525 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
528 if (currentRect
.left() < viewGeometry
.left()) {
529 newOffset
+= currentRect
.left() - viewGeometry
.left();
530 } else if (currentRect
.right() > viewGeometry
.right()) {
531 newOffset
+= currentRect
.right() - viewGeometry
.right();
535 if (newOffset
!= scrollOffset()) {
536 emit
scrollTo(newOffset
);
541 void KItemListView::beginTransaction()
543 ++m_activeTransactions
;
544 if (m_activeTransactions
== 1) {
545 onTransactionBegin();
549 void KItemListView::endTransaction()
551 --m_activeTransactions
;
552 if (m_activeTransactions
< 0) {
553 m_activeTransactions
= 0;
554 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
557 if (m_activeTransactions
== 0) {
559 doLayout(m_endTransactionAnimationHint
);
560 m_endTransactionAnimationHint
= Animation
;
564 bool KItemListView::isTransactionActive() const
566 return m_activeTransactions
> 0;
569 void KItemListView::setHeaderShown(bool show
)
572 if (show
&& !m_header
) {
573 m_header
= new KItemListHeader(this);
574 m_header
->setPos(0, 0);
575 m_header
->setModel(m_model
);
576 m_header
->setVisibleRoles(m_visibleRoles
);
577 m_header
->setVisibleRolesWidths(headerRolesWidths());
578 m_header
->setZValue(1);
580 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
581 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
582 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
583 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
584 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
585 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
587 m_useHeaderWidths
= false;
589 m_layouter
->setHeaderHeight(m_header
->size().height());
590 } else if (!show
&& m_header
) {
593 m_useHeaderWidths
= false;
594 m_layouter
->setHeaderHeight(0);
598 bool KItemListView::isHeaderShown() const
600 return m_header
!= 0;
603 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
609 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
611 QGraphicsWidget::paint(painter
, option
, widget
);
613 if (m_rubberBand
->isActive()) {
614 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
615 m_rubberBand
->endPosition()).normalized();
617 const QPointF topLeft
= rubberBandRect
.topLeft();
618 if (scrollOrientation() == Qt::Vertical
) {
619 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
621 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
624 QStyleOptionRubberBand opt
;
625 opt
.initFrom(widget
);
626 opt
.shape
= QRubberBand::Rectangle
;
628 opt
.rect
= rubberBandRect
.toRect();
629 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
633 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
638 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
640 Q_UNUSED(changedRoles
);
644 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
650 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
656 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
662 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
668 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
674 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
680 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
686 void KItemListView::onTransactionBegin()
690 void KItemListView::onTransactionEnd()
694 bool KItemListView::event(QEvent
* event
)
696 // Forward all events to the controller and handle them there
697 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
701 return QGraphicsWidget::event(event
);
704 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
706 m_mousePos
= transform().map(event
->pos());
710 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
712 QGraphicsWidget::mouseMoveEvent(event
);
714 m_mousePos
= transform().map(event
->pos());
715 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
716 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
720 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
722 event
->setAccepted(true);
726 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
728 QGraphicsWidget::dragMoveEvent(event
);
730 m_mousePos
= transform().map(event
->pos());
731 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
732 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
736 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
738 QGraphicsWidget::dragLeaveEvent(event
);
739 setAutoScroll(false);
742 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
744 QGraphicsWidget::dropEvent(event
);
745 setAutoScroll(false);
748 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
750 return m_visibleItems
.values();
753 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
755 updateVisibleRolesSizes(itemRanges
);
757 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
758 if (hasMultipleRanges
) {
762 int previouslyInsertedCount
= 0;
763 foreach (const KItemRange
& range
, itemRanges
) {
764 // range.index is related to the model before anything has been inserted.
765 // As in each loop the current item-range gets inserted the index must
766 // be increased by the already previously inserted items.
767 const int index
= range
.index
+ previouslyInsertedCount
;
768 const int count
= range
.count
;
769 if (index
< 0 || count
<= 0) {
770 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
773 previouslyInsertedCount
+= count
;
775 m_sizeHintResolver
->itemsInserted(index
, count
);
777 // Determine which visible items must be moved
778 QList
<int> itemsToMove
;
779 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
780 while (it
.hasNext()) {
782 const int visibleItemIndex
= it
.key();
783 if (visibleItemIndex
>= index
) {
784 itemsToMove
.append(visibleItemIndex
);
788 // Update the indexes of all KItemListWidget instances that are located
789 // after the inserted items. It is important to adjust the indexes in the order
790 // from the highest index to the lowest index to prevent overlaps when setting the new index.
792 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
793 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
795 setWidgetIndex(widget
, widget
->index() + count
);
798 m_layouter
->markAsDirty();
799 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
800 // Check whether a scrollbar is required to show the inserted items. In this case
801 // the size of the layouter will be decreased before calling doLayout(): This prevents
802 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
803 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
804 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
805 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
806 if (decreaseLayouterSize
) {
807 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
808 QSizeF layouterSize
= m_layouter
->size();
809 if (verticalScrollOrientation
) {
810 layouterSize
.rwidth() -= scrollBarExtent
;
812 layouterSize
.rheight() -= scrollBarExtent
;
814 m_layouter
->setSize(layouterSize
);
818 if (!hasMultipleRanges
) {
819 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
824 m_controller
->selectionManager()->itemsInserted(itemRanges
);
827 if (hasMultipleRanges
) {
832 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
834 updateVisibleRolesSizes();
836 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
837 if (hasMultipleRanges
) {
841 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
842 const KItemRange
& range
= itemRanges
.at(i
);
843 const int index
= range
.index
;
844 const int count
= range
.count
;
845 if (index
< 0 || count
<= 0) {
846 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
850 m_sizeHintResolver
->itemsRemoved(index
, count
);
852 const int firstRemovedIndex
= index
;
853 const int lastRemovedIndex
= index
+ count
- 1;
854 const int lastIndex
= m_model
->count() + count
- 1;
856 // Remove all KItemListWidget instances that got deleted
857 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
858 KItemListWidget
* widget
= m_visibleItems
.value(i
);
863 m_animation
->stop(widget
);
864 // Stopping the animation might lead to recycling the widget if
865 // it is invisible (see slotAnimationFinished()).
866 // Check again whether it is still visible:
867 if (!m_visibleItems
.contains(i
)) {
871 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
872 // Remove the widget without animation
873 recycleWidget(widget
);
875 // Animate the removing of the items. Special case: When removing an item there
876 // is no valid model index available anymore. For the
877 // remove-animation the item gets removed from m_visibleItems but the widget
878 // will stay alive until the animation has been finished and will
879 // be recycled (deleted) in KItemListView::slotAnimationFinished().
880 m_visibleItems
.remove(i
);
881 widget
->setIndex(-1);
882 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
886 // Update the indexes of all KItemListWidget instances that are located
887 // after the deleted items
888 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
889 KItemListWidget
* widget
= m_visibleItems
.value(i
);
891 const int newIndex
= i
- count
;
892 setWidgetIndex(widget
, newIndex
);
896 m_layouter
->markAsDirty();
897 if (!hasMultipleRanges
) {
898 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
899 // assumes an updated geometry. If items are removed during an active transaction,
900 // the transaction will be temporary deactivated so that doLayout() triggers a
901 // geometry update if necessary.
902 const int activeTransactions
= m_activeTransactions
;
903 m_activeTransactions
= 0;
904 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
905 m_activeTransactions
= activeTransactions
;
910 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
913 if (hasMultipleRanges
) {
918 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
920 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
921 m_layouter
->markAsDirty();
924 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
927 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
928 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
930 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
931 KItemListWidget
* widget
= m_visibleItems
.value(index
);
933 updateWidgetProperties(widget
, index
);
935 updateGroupHeaderForWidget(widget
);
937 initializeItemListWidget(widget
);
941 doLayout(NoAnimation
);
944 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
945 const QSet
<QByteArray
>& roles
)
947 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
948 if (updateSizeHints
) {
949 updateVisibleRolesSizes(itemRanges
);
952 foreach (const KItemRange
& itemRange
, itemRanges
) {
953 const int index
= itemRange
.index
;
954 const int count
= itemRange
.count
;
956 if (updateSizeHints
) {
957 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
958 m_layouter
->markAsDirty();
960 if (!m_layoutTimer
->isActive()) {
961 m_layoutTimer
->start();
965 // Apply the changed roles to the visible item-widgets
966 const int lastIndex
= index
+ count
- 1;
967 for (int i
= index
; i
<= lastIndex
; ++i
) {
968 KItemListWidget
* widget
= m_visibleItems
.value(i
);
970 widget
->setData(m_model
->data(i
), roles
);
974 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
975 // The sort-role has been changed which might result
976 // in modified group headers
977 updateVisibleGroupHeaders();
978 doLayout(NoAnimation
);
983 void KItemListView::slotGroupedSortingChanged(bool current
)
986 m_layouter
->markAsDirty();
989 updateGroupHeaderHeight();
991 // Clear all visible headers
992 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
993 while (it
.hasNext()) {
995 recycleGroupHeaderForWidget(it
.key());
997 Q_ASSERT(m_visibleGroups
.isEmpty());
1000 doLayout(NoAnimation
);
1003 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1008 updateVisibleGroupHeaders();
1009 doLayout(NoAnimation
);
1013 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1018 updateVisibleGroupHeaders();
1019 doLayout(NoAnimation
);
1023 void KItemListView::slotCurrentChanged(int current
, int previous
)
1027 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1028 if (previousWidget
) {
1029 Q_ASSERT(previousWidget
->isCurrent());
1030 previousWidget
->setCurrent(false);
1033 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1034 if (currentWidget
) {
1035 Q_ASSERT(!currentWidget
->isCurrent());
1036 currentWidget
->setCurrent(true);
1040 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1044 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1045 while (it
.hasNext()) {
1047 const int index
= it
.key();
1048 KItemListWidget
* widget
= it
.value();
1049 widget
->setSelected(current
.contains(index
));
1053 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1054 KItemListViewAnimation::AnimationType type
)
1056 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1057 Q_ASSERT(itemListWidget
);
1060 case KItemListViewAnimation::DeleteAnimation
: {
1061 // As we recycle the widget in this case it is important to assure that no
1062 // other animation has been started. This is a convention in KItemListView and
1063 // not a requirement defined by KItemListViewAnimation.
1064 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1066 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1067 // by m_visibleWidgets and must be deleted manually after the animation has
1069 recycleGroupHeaderForWidget(itemListWidget
);
1070 m_widgetCreator
->recycle(itemListWidget
);
1074 case KItemListViewAnimation::CreateAnimation
:
1075 case KItemListViewAnimation::MovingAnimation
:
1076 case KItemListViewAnimation::ResizeAnimation
: {
1077 const int index
= itemListWidget
->index();
1078 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1079 (index
> m_layouter
->lastVisibleIndex());
1080 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1081 recycleWidget(itemListWidget
);
1090 void KItemListView::slotLayoutTimerFinished()
1092 m_layouter
->setSize(geometry().size());
1093 doLayout(Animation
);
1096 void KItemListView::slotRubberBandPosChanged()
1101 void KItemListView::slotRubberBandActivationChanged(bool active
)
1104 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1105 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1106 m_skipAutoScrollForRubberBand
= true;
1108 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1109 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1110 m_skipAutoScrollForRubberBand
= false;
1116 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1118 qreal previousWidth
)
1120 Q_UNUSED(previousWidth
);
1122 m_useHeaderWidths
= true;
1124 if (m_visibleRolesSizes
.contains(role
)) {
1125 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1126 roleSize
.setWidth(currentWidth
);
1127 m_visibleRolesSizes
.insert(role
, roleSize
);
1128 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1130 // Apply the new size to the layouter
1131 QSizeF dynamicItemSize
= m_itemSize
;
1132 if (dynamicItemSize
.width() < 0) {
1133 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1134 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1136 if (dynamicItemSize
.height() < 0) {
1137 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1138 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1141 m_layouter
->setItemSize(dynamicItemSize
);
1143 // Update the role sizes for all visible widgets
1144 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1145 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1148 doLayout(NoAnimation
);
1152 void KItemListView::triggerAutoScrolling()
1154 if (!m_autoScrollTimer
) {
1159 int visibleSize
= 0;
1160 if (scrollOrientation() == Qt::Vertical
) {
1161 pos
= m_mousePos
.y();
1162 visibleSize
= size().height();
1164 pos
= m_mousePos
.x();
1165 visibleSize
= size().width();
1168 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1169 m_autoScrollIncrement
= 0;
1172 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1173 if (m_autoScrollIncrement
== 0) {
1174 // The mouse position is not above an autoscroll margin (the autoscroll timer
1175 // will be restarted in mouseMoveEvent())
1176 m_autoScrollTimer
->stop();
1180 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1181 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1182 // if the direction of the rubberband is similar to the autoscroll direction. This
1183 // prevents that starting to create a rubberband within the autoscroll margins starts
1184 // an autoscrolling.
1186 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1187 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1188 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1189 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1190 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1191 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1192 // been moved up although the autoscroll direction might be down)
1193 m_autoScrollTimer
->stop();
1198 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1199 // the autoscrolling may not get skipped anymore until a new rubberband is created
1200 m_skipAutoScrollForRubberBand
= false;
1202 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1203 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1204 setScrollOffset(newScrollOffset
);
1206 // Trigger the autoscroll timer which will periodically call
1207 // triggerAutoScrolling()
1208 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1211 void KItemListView::setController(KItemListController
* controller
)
1213 if (m_controller
!= controller
) {
1214 KItemListController
* previous
= m_controller
;
1216 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1217 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1218 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1221 m_controller
= controller
;
1224 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1225 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1226 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1229 onControllerChanged(controller
, previous
);
1233 void KItemListView::setModel(KItemModelBase
* model
)
1235 if (m_model
== model
) {
1239 KItemModelBase
* previous
= m_model
;
1242 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1243 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1244 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1245 this, SLOT(slotItemsInserted(KItemRangeList
)));
1246 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1247 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1248 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1249 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1250 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1251 this, SLOT(slotGroupedSortingChanged(bool)));
1252 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1253 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1254 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1255 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1259 m_layouter
->setModel(model
);
1260 m_grouped
= model
->groupedSorting();
1263 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1264 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1265 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1266 this, SLOT(slotItemsInserted(KItemRangeList
)));
1267 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1268 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1269 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1270 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1271 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1272 this, SLOT(slotGroupedSortingChanged(bool)));
1273 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1274 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1275 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1276 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1279 onModelChanged(model
, previous
);
1282 KItemListRubberBand
* KItemListView::rubberBand() const
1284 return m_rubberBand
;
1287 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1289 if (m_layoutTimer
->isActive()) {
1290 m_layoutTimer
->stop();
1293 if (m_activeTransactions
> 0) {
1294 if (hint
== NoAnimation
) {
1295 // As soon as at least one property change should be done without animation,
1296 // the whole transaction will be marked as not animated.
1297 m_endTransactionAnimationHint
= NoAnimation
;
1302 if (!m_model
|| m_model
->count() < 0) {
1306 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1307 if (firstVisibleIndex
< 0) {
1308 emitOffsetChanges();
1312 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1313 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1314 // is still shown if the maximum offset got decreased.
1315 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1316 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1317 if (scrollOffset() > maxOffsetToShowFullRange
) {
1318 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1319 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1322 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1324 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1326 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1327 // instances from invisible items are reused. If no reusable items are
1328 // found then new KItemListWidget instances get created.
1329 const bool animate
= (hint
== Animation
);
1330 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1331 bool applyNewPos
= true;
1332 bool wasHidden
= false;
1334 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1335 const QPointF newPos
= itemBounds
.topLeft();
1336 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1339 if (!reusableItems
.isEmpty()) {
1340 // Reuse a KItemListWidget instance from an invisible item
1341 const int oldIndex
= reusableItems
.takeLast();
1342 widget
= m_visibleItems
.value(oldIndex
);
1343 setWidgetIndex(widget
, i
);
1346 updateGroupHeaderForWidget(widget
);
1349 // No reusable KItemListWidget instance is available, create a new one
1350 widget
= createWidget(i
);
1352 widget
->resize(itemBounds
.size());
1354 if (animate
&& changedCount
< 0) {
1355 // Items have been deleted, move the created item to the
1356 // imaginary old position. They will get animated to the new position
1358 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1359 if (itemRect
.isEmpty()) {
1360 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1361 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1362 widget
->setPos(invisibleOldPos
);
1364 widget
->setPos(itemRect
.topLeft());
1366 applyNewPos
= false;
1371 const bool itemsRemoved
= (changedCount
< 0);
1372 const bool itemsInserted
= (changedCount
> 0);
1373 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1374 // The item is located after the removed items. Animate the moving of the position.
1375 applyNewPos
= !moveWidget(widget
, itemBounds
);
1376 } else if (itemsInserted
&& i
>= changedIndex
) {
1377 // The item is located after the first inserted item
1378 if (i
<= changedIndex
+ changedCount
- 1) {
1379 // The item is an inserted item. Animate the appearing of the item.
1380 // For performance reasons no animation is done when changedCount is equal
1381 // to all available items.
1382 if (changedCount
< m_model
->count()) {
1383 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1385 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1386 // The item was already there before, so animate the moving of the position.
1387 // No moving animation is done if the item is animated by a create animation: This
1388 // prevents a "move animation mess" when inserting several ranges in parallel.
1389 applyNewPos
= !moveWidget(widget
, itemBounds
);
1391 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1392 // The size of the view might have been changed. Animate the moving of the position.
1393 applyNewPos
= !moveWidget(widget
, itemBounds
);
1396 m_animation
->stop(widget
);
1400 widget
->setPos(newPos
);
1403 Q_ASSERT(widget
->index() == i
);
1404 widget
->setVisible(true);
1406 if (widget
->size() != itemBounds
.size()) {
1407 // Resize the widget for the item to the changed size.
1409 // If a dynamic item size is used then no animation is done in the direction
1410 // of the dynamic size.
1411 if (m_itemSize
.width() <= 0) {
1412 // The width is dynamic, apply the new width without animation.
1413 widget
->resize(itemBounds
.width(), widget
->size().height());
1414 } else if (m_itemSize
.height() <= 0) {
1415 // The height is dynamic, apply the new height without animation.
1416 widget
->resize(widget
->size().width(), itemBounds
.height());
1418 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1420 widget
->resize(itemBounds
.size());
1425 // Delete invisible KItemListWidget instances that have not been reused
1426 foreach (int index
, reusableItems
) {
1427 recycleWidget(m_visibleItems
.value(index
));
1431 // Update the layout of all visible group headers
1432 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1433 while (it
.hasNext()) {
1435 updateGroupHeaderLayout(it
.key());
1439 emitOffsetChanges();
1442 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1443 int lastVisibleIndex
,
1444 LayoutAnimationHint hint
)
1446 // Determine all items that are completely invisible and might be
1447 // reused for items that just got (at least partly) visible. If the
1448 // animation hint is set to 'Animation' items that do e.g. an animated
1449 // moving of their position are not marked as invisible: This assures
1450 // that a scrolling inside the view can be done without breaking an animation.
1454 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1455 while (it
.hasNext()) {
1458 KItemListWidget
* widget
= it
.value();
1459 const int index
= widget
->index();
1460 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1463 if (m_animation
->isStarted(widget
)) {
1464 if (hint
== NoAnimation
) {
1465 // Stopping the animation will call KItemListView::slotAnimationFinished()
1466 // and the widget will be recycled if necessary there.
1467 m_animation
->stop(widget
);
1470 widget
->setVisible(false);
1471 items
.append(index
);
1474 recycleGroupHeaderForWidget(widget
);
1483 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QRectF
& itemBounds
)
1485 const QPointF oldPos
= widget
->pos();
1486 const QPointF newPos
= itemBounds
.topLeft();
1487 if (oldPos
== newPos
) {
1491 bool startMovingAnim
= m_itemSize
.isEmpty() || widget
->size() != itemBounds
.size();
1492 if (!startMovingAnim
) {
1493 // When having a grid the moving-animation should only be started, if it is done within
1494 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1495 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1496 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1497 const qreal xMax
= m_itemSize
.width();
1498 const qreal yMax
= m_itemSize
.height();
1499 qreal xDiff
= qAbs(oldPos
.x() - newPos
.x());
1500 qreal yDiff
= qAbs(oldPos
.y() - newPos
.y());
1501 if (scrollOrientation() == Qt::Vertical
) {
1502 startMovingAnim
= (xDiff
> yDiff
&& yDiff
< yMax
);
1504 startMovingAnim
= (yDiff
> xDiff
&& xDiff
< xMax
);
1508 if (startMovingAnim
) {
1509 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1513 m_animation
->stop(widget
);
1514 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1518 void KItemListView::emitOffsetChanges()
1520 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1521 if (m_oldScrollOffset
!= newScrollOffset
) {
1522 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1523 m_oldScrollOffset
= newScrollOffset
;
1526 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1527 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1528 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1529 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1532 const qreal newItemOffset
= m_layouter
->itemOffset();
1533 if (m_oldItemOffset
!= newItemOffset
) {
1534 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1535 m_oldItemOffset
= newItemOffset
;
1538 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1539 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1540 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1541 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1545 KItemListWidget
* KItemListView::createWidget(int index
)
1547 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1548 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1550 updateWidgetProperties(widget
, index
);
1551 m_visibleItems
.insert(index
, widget
);
1554 updateGroupHeaderForWidget(widget
);
1557 initializeItemListWidget(widget
);
1561 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1564 recycleGroupHeaderForWidget(widget
);
1567 m_visibleItems
.remove(widget
->index());
1568 m_widgetCreator
->recycle(widget
);
1571 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1573 const int oldIndex
= widget
->index();
1574 m_visibleItems
.remove(oldIndex
);
1575 updateWidgetProperties(widget
, index
);
1576 m_visibleItems
.insert(index
, widget
);
1578 initializeItemListWidget(widget
);
1581 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1584 case LayouterSize
: m_layouter
->setSize(size
); break;
1585 case ItemSize
: m_layouter
->setItemSize(size
); break;
1590 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1592 widget
->setVisibleRoles(m_visibleRoles
);
1593 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1594 widget
->setStyleOption(m_styleOption
);
1596 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1597 widget
->setCurrent(index
== selectionManager
->currentItem());
1598 widget
->setSelected(selectionManager
->isSelected(index
));
1599 widget
->setHovered(false);
1600 widget
->setAlternatingBackgroundColors(false);
1601 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1602 widget
->setIndex(index
);
1603 widget
->setData(m_model
->data(index
));
1606 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1608 Q_ASSERT(m_grouped
);
1610 const int index
= widget
->index();
1611 if (!m_layouter
->isFirstGroupItem(index
)) {
1612 // The widget does not represent the first item of a group
1613 // and hence requires no header
1614 recycleGroupHeaderForWidget(widget
);
1618 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1619 if (groups
.isEmpty()) {
1623 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1625 groupHeader
= m_groupHeaderCreator
->create(this);
1626 groupHeader
->setParentItem(widget
);
1627 m_visibleGroups
.insert(widget
, groupHeader
);
1629 Q_ASSERT(groupHeader
->parentItem() == widget
);
1631 // Determine the shown data for the header by doing a binary
1632 // search in the groups-list
1634 int max
= groups
.count() - 1;
1637 mid
= (min
+ max
) / 2;
1638 if (index
> groups
.at(mid
).first
) {
1643 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1645 groupHeader
->setData(groups
.at(mid
).second
);
1646 groupHeader
->setRole(model()->sortRole());
1647 groupHeader
->setStyleOption(m_styleOption
);
1648 groupHeader
->setScrollOrientation(scrollOrientation());
1650 groupHeader
->show();
1653 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1655 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1656 Q_ASSERT(groupHeader
);
1658 const int index
= widget
->index();
1659 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1660 const QRectF itemRect
= m_layouter
->itemRect(index
);
1662 // The group-header is a child of the itemlist widget. Translate the
1663 // group header position to the relative position.
1664 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1665 - groupHeaderRect
.height());
1666 groupHeader
->setPos(groupHeaderPos
);
1667 groupHeader
->resize(groupHeaderRect
.size());
1670 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1672 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1674 header
->setParentItem(0);
1675 m_groupHeaderCreator
->recycle(header
);
1676 m_visibleGroups
.remove(widget
);
1680 void KItemListView::updateVisibleGroupHeaders()
1682 Q_ASSERT(m_grouped
);
1683 m_layouter
->markAsDirty();
1685 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1686 while (it
.hasNext()) {
1688 updateGroupHeaderForWidget(it
.value());
1692 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1694 QHash
<QByteArray
, qreal
> rolesWidths
;
1696 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1697 while (it
.hasNext()) {
1699 rolesWidths
.insert(it
.key(), it
.value().width());
1705 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1707 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1711 const int itemCount
= m_model
->count();
1712 int rangesItemCount
= 0;
1713 foreach (const KItemRange
& range
, itemRanges
) {
1714 rangesItemCount
+= range
.count
;
1717 if (itemCount
== rangesItemCount
) {
1718 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1720 // Assure the the sizes are not smaller than the minimum defined by the header
1721 // TODO: Currently only implemented for a top-aligned header
1722 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1723 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1724 while (it
.hasNext()) {
1726 const QSizeF
& size
= it
.value();
1727 if (size
.width() < minHeaderRoleWidth
) {
1728 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1729 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1734 // Only a sub range of the roles need to be determined.
1735 // The chances are good that the sizes of the sub ranges
1736 // already fit into the available sizes and hence no
1737 // expensive update might be required.
1738 bool updateRequired
= false;
1740 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1741 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1742 while (it
.hasNext()) {
1744 const QByteArray
& role
= it
.key();
1745 const QSizeF
& updatedSize
= it
.value();
1746 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1747 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1748 m_visibleRolesSizes
.insert(role
, updatedSize
);
1749 updateRequired
= true;
1753 if (!updateRequired
) {
1754 // All the updated sizes are smaller than the current sizes and no change
1755 // of the stretched roles-widths is required
1760 updateStretchedVisibleRolesSizes();
1763 void KItemListView::updateVisibleRolesSizes()
1769 const int itemCount
= m_model
->count();
1770 if (itemCount
> 0) {
1771 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1775 void KItemListView::updateStretchedVisibleRolesSizes()
1777 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1781 // Calculate the maximum size of an item by considering the
1782 // visible role sizes and apply them to the layouter. If the
1783 // size does not use the available view-size it the size of the
1784 // first role will get stretched.
1785 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1786 const QByteArray role
= m_visibleRoles
.first();
1787 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1789 QSizeF dynamicItemSize
= m_itemSize
;
1791 if (dynamicItemSize
.width() <= 0) {
1792 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1793 const qreal availableWidth
= size().width();
1794 if (requiredWidth
< availableWidth
) {
1795 // Stretch the first role to use the whole width for the item
1796 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1797 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1799 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1802 if (dynamicItemSize
.height() <= 0) {
1803 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1804 const qreal availableHeight
= size().height();
1805 if (requiredHeight
< availableHeight
) {
1806 // Stretch the first role to use the whole height for the item
1807 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1808 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1810 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1813 m_layouter
->setItemSize(dynamicItemSize
);
1816 m_header
->setVisibleRolesWidths(headerRolesWidths());
1817 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1820 // Update the role sizes for all visible widgets
1821 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1822 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1826 qreal
KItemListView::visibleRolesSizesWidthSum() const
1829 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1830 while (it
.hasNext()) {
1832 widthSum
+= it
.value().width();
1837 qreal
KItemListView::visibleRolesSizesHeightSum() const
1839 qreal heightSum
= 0;
1840 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1841 while (it
.hasNext()) {
1843 heightSum
+= it
.value().height();
1848 QRectF
KItemListView::headerBoundaries() const
1850 return m_header
? m_header
->geometry() : QRectF();
1853 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
, const QSizeF
& newItemSize
) const
1855 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
1859 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
1860 const qreal itemWidth
= m_layouter
->itemSize().width();
1861 if (itemWidth
> 0) {
1862 const int newColumnCount
= newGridSize
.width() / newItemSize
.width();
1863 if (m_model
->count() > newColumnCount
) {
1864 const int oldColumnCount
= m_layouter
->size().width() / itemWidth
;
1865 return oldColumnCount
!= newColumnCount
;
1869 const qreal itemHeight
= m_layouter
->itemSize().height();
1870 if (itemHeight
> 0) {
1871 const int newRowCount
= newGridSize
.height() / newItemSize
.height();
1872 if (m_model
->count() > newRowCount
) {
1873 const int oldRowCount
= m_layouter
->size().height() / itemHeight
;
1874 return oldRowCount
!= newRowCount
;
1882 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
1884 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
1888 const int maximum
= (scrollOrientation() == Qt::Vertical
)
1889 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
1890 : m_layouter
->size().height() / m_layouter
->itemSize().height();
1891 // Only animate if up to 2/3 of a row or column are inserted or removed
1892 return changedItemCount
<= maximum
* 2 / 3;
1896 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
1898 const QSizeF oldSize
= m_layouter
->size();
1900 m_layouter
->setSize(size
);
1901 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
1902 m_layouter
->setSize(oldSize
);
1904 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
1905 : maxOffset
> size
.width();
1908 void KItemListView::updateGroupHeaderHeight()
1910 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
1911 groupHeaderHeight
+= (scrollOrientation() == Qt::Vertical
)
1912 ? m_styleOption
.margin
* 4 : m_styleOption
.margin
* 2;
1913 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
1915 updateVisibleGroupHeaders();
1918 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1922 const int minSpeed
= 4;
1923 const int maxSpeed
= 128;
1924 const int speedLimiter
= 96;
1925 const int autoScrollBorder
= 64;
1927 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1928 // This assures that the autoscrolling speed grows gradually.
1929 const int incLimiter
= 1;
1931 if (pos
< autoScrollBorder
) {
1932 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1933 inc
= qMax(inc
, -maxSpeed
);
1934 inc
= qMax(inc
, oldInc
- incLimiter
);
1935 } else if (pos
> range
- autoScrollBorder
) {
1936 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1937 inc
= qMin(inc
, maxSpeed
);
1938 inc
= qMin(inc
, oldInc
+ incLimiter
);
1946 KItemListCreatorBase::~KItemListCreatorBase()
1948 qDeleteAll(m_recycleableWidgets
);
1949 qDeleteAll(m_createdWidgets
);
1952 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1954 m_createdWidgets
.insert(widget
);
1957 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1959 Q_ASSERT(m_createdWidgets
.contains(widget
));
1960 m_createdWidgets
.remove(widget
);
1962 if (m_recycleableWidgets
.count() < 100) {
1963 m_recycleableWidgets
.append(widget
);
1964 widget
->setVisible(false);
1970 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1972 if (m_recycleableWidgets
.isEmpty()) {
1976 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1977 m_createdWidgets
.insert(widget
);
1981 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1985 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1987 widget
->setParentItem(0);
1988 widget
->setOpacity(1.0);
1989 pushRecycleableWidget(widget
);
1992 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1996 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1998 header
->setOpacity(1.0);
1999 pushRecycleableWidget(header
);
2002 #include "kitemlistview.moc"