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 "kitemlistgroupheader.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>
44 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
45 QGraphicsWidget(parent
),
46 m_autoScrollMarginEnabled(false),
48 m_activeTransactions(0),
53 m_visibleRolesSizes(),
55 m_groupHeaderCreator(0),
59 m_sizeHintResolver(0),
64 m_oldMaximumOffset(0),
68 setAcceptHoverEvents(true);
70 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
72 m_layouter
= new KItemListViewLayouter(this);
73 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
75 m_animation
= new KItemListViewAnimation(this);
76 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
77 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
79 m_layoutTimer
= new QTimer(this);
80 m_layoutTimer
->setInterval(300);
81 m_layoutTimer
->setSingleShot(true);
82 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
84 m_rubberBand
= new KItemListRubberBand(this);
85 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
88 KItemListView::~KItemListView()
90 delete m_sizeHintResolver
;
91 m_sizeHintResolver
= 0;
94 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
96 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
97 if (orientation
== previousOrientation
) {
101 m_layouter
->setScrollOrientation(orientation
);
102 m_animation
->setScrollOrientation(orientation
);
103 m_sizeHintResolver
->clearCache();
105 onScrollOrientationChanged(orientation
, previousOrientation
);
108 Qt::Orientation
KItemListView::scrollOrientation() const
110 return m_layouter
->scrollOrientation();
113 void KItemListView::setItemSize(const QSizeF
& itemSize
)
115 const QSizeF previousSize
= m_itemSize
;
116 if (itemSize
== previousSize
) {
120 m_itemSize
= itemSize
;
122 if (!markVisibleRolesSizesAsDirty()) {
123 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
124 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
126 m_layouter
->setItemSize(itemSize
);
130 m_sizeHintResolver
->clearCache();
132 onItemSizeChanged(itemSize
, previousSize
);
135 QSizeF
KItemListView::itemSize() const
140 void KItemListView::setOffset(qreal offset
)
146 const qreal previousOffset
= m_layouter
->offset();
147 if (offset
== previousOffset
) {
151 m_layouter
->setOffset(offset
);
152 m_animation
->setOffset(offset
);
153 if (!m_layoutTimer
->isActive()) {
154 doLayout(NoAnimation
, 0, 0);
157 onOffsetChanged(offset
, previousOffset
);
160 qreal
KItemListView::offset() const
162 return m_layouter
->offset();
165 qreal
KItemListView::maximumOffset() const
167 return m_layouter
->maximumOffset();
170 void KItemListView::setVisibleRoles(const QHash
<QByteArray
, int>& roles
)
172 const QHash
<QByteArray
, int> previousRoles
= m_visibleRoles
;
173 m_visibleRoles
= roles
;
175 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
176 while (it
.hasNext()) {
178 KItemListWidget
* widget
= it
.value();
179 widget
->setVisibleRoles(roles
);
180 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
183 m_sizeHintResolver
->clearCache();
184 m_layouter
->markAsDirty();
185 onVisibleRolesChanged(roles
, previousRoles
);
187 markVisibleRolesSizesAsDirty();
191 QHash
<QByteArray
, int> KItemListView::visibleRoles() const
193 return m_visibleRoles
;
196 KItemListController
* KItemListView::controller() const
201 KItemModelBase
* KItemListView::model() const
206 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
208 m_widgetCreator
= widgetCreator
;
211 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
213 return m_widgetCreator
;
216 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
218 m_groupHeaderCreator
= groupHeaderCreator
;
221 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
223 return m_groupHeaderCreator
;
226 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
228 const KItemListStyleOption previousOption
= m_styleOption
;
229 m_styleOption
= option
;
231 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
232 while (it
.hasNext()) {
234 it
.value()->setStyleOption(option
);
237 m_sizeHintResolver
->clearCache();
239 onStyleOptionChanged(option
, previousOption
);
242 const KItemListStyleOption
& KItemListView::styleOption() const
244 return m_styleOption
;
247 void KItemListView::setGeometry(const QRectF
& rect
)
249 QGraphicsWidget::setGeometry(rect
);
254 if (m_itemSize
.isEmpty()) {
255 m_layouter
->setItemSize(QSizeF());
258 if (m_model
->count() > 0) {
259 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
261 m_layouter
->setSize(rect
.size());
264 m_layoutTimer
->start();
267 int KItemListView::itemAt(const QPointF
& pos
) const
269 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
270 while (it
.hasNext()) {
273 const KItemListWidget
* widget
= it
.value();
274 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
275 if (widget
->contains(mappedPos
)) {
283 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
290 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
292 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
294 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
295 if (!expansionToggleRect
.isEmpty()) {
296 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
297 return expansionToggleRect
.contains(mappedPos
);
303 int KItemListView::firstVisibleIndex() const
305 return m_layouter
->firstVisibleIndex();
308 int KItemListView::lastVisibleIndex() const
310 return m_layouter
->lastVisibleIndex();
313 QSizeF
KItemListView::itemSizeHint(int index
) const
319 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRoleSizes() const
321 return QHash
<QByteArray
, QSizeF
>();
324 QRectF
KItemListView::itemBoundingRect(int index
) const
326 return m_layouter
->itemBoundingRect(index
);
329 int KItemListView::itemsPerOffset() const
331 return m_layouter
->itemsPerOffset();
334 void KItemListView::beginTransaction()
336 ++m_activeTransactions
;
337 if (m_activeTransactions
== 1) {
338 onTransactionBegin();
342 void KItemListView::endTransaction()
344 --m_activeTransactions
;
345 if (m_activeTransactions
< 0) {
346 m_activeTransactions
= 0;
347 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
350 if (m_activeTransactions
== 0) {
356 bool KItemListView::isTransactionActive() const
358 return m_activeTransactions
> 0;
361 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
367 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
369 QGraphicsWidget::paint(painter
, option
, widget
);
371 if (m_rubberBand
->isActive()) {
372 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
373 m_rubberBand
->endPosition()).normalized();
375 const QPointF topLeft
= rubberBandRect
.topLeft();
376 if (scrollOrientation() == Qt::Vertical
) {
377 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - offset());
379 rubberBandRect
.moveTo(topLeft
.x() - offset(), topLeft
.y());
382 QStyleOptionRubberBand opt
;
383 opt
.initFrom(widget
);
384 opt
.shape
= QRubberBand::Rectangle
;
386 opt
.rect
= rubberBandRect
.toRect();
387 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
391 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
396 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
402 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
408 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
414 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
420 void KItemListView::onOffsetChanged(qreal current
, qreal previous
)
426 void KItemListView::onVisibleRolesChanged(const QHash
<QByteArray
, int>& current
, const QHash
<QByteArray
, int>& previous
)
432 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
438 void KItemListView::onTransactionBegin()
442 void KItemListView::onTransactionEnd()
446 bool KItemListView::event(QEvent
* event
)
448 // Forward all events to the controller and handle them there
449 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
453 return QGraphicsWidget::event(event
);
456 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
458 m_mousePos
= transform().map(event
->pos());
462 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
464 m_mousePos
= transform().map(event
->pos());
465 QGraphicsWidget::mouseMoveEvent(event
);
468 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
470 event
->setAccepted(true);
473 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
475 return m_visibleItems
.values();
478 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
480 markVisibleRolesSizesAsDirty();
482 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
483 if (hasMultipleRanges
) {
487 int previouslyInsertedCount
= 0;
488 foreach (const KItemRange
& range
, itemRanges
) {
489 // range.index is related to the model before anything has been inserted.
490 // As in each loop the current item-range gets inserted the index must
491 // be increased by the already previously inserted items.
492 const int index
= range
.index
+ previouslyInsertedCount
;
493 const int count
= range
.count
;
494 if (index
< 0 || count
<= 0) {
495 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
498 previouslyInsertedCount
+= count
;
500 m_sizeHintResolver
->itemsInserted(index
, count
);
502 // Determine which visible items must be moved
503 QList
<int> itemsToMove
;
504 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
505 while (it
.hasNext()) {
507 const int visibleItemIndex
= it
.key();
508 if (visibleItemIndex
>= index
) {
509 itemsToMove
.append(visibleItemIndex
);
513 // Update the indexes of all KItemListWidget instances that are located
514 // after the inserted items. It is important to adjust the indexes in the order
515 // from the highest index to the lowest index to prevent overlaps when setting the new index.
517 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
518 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
520 setWidgetIndex(widget
, widget
->index() + count
);
523 m_layouter
->markAsDirty();
524 if (m_model
->count() == count
&& maximumOffset() > size().height()) {
525 kDebug() << "Scrollbar required, skipping layout";
526 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
527 QSizeF layouterSize
= m_layouter
->size();
528 if (scrollOrientation() == Qt::Vertical
) {
529 layouterSize
.rwidth() -= scrollBarExtent
;
531 layouterSize
.rheight() -= scrollBarExtent
;
533 m_layouter
->setSize(layouterSize
);
536 if (!hasMultipleRanges
) {
537 doLayout(Animation
, index
, count
);
543 m_controller
->selectionManager()->itemsInserted(itemRanges
);
546 if (hasMultipleRanges
) {
551 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
553 markVisibleRolesSizesAsDirty();
555 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
556 if (hasMultipleRanges
) {
560 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
561 const KItemRange
& range
= itemRanges
.at(i
);
562 const int index
= range
.index
;
563 const int count
= range
.count
;
564 if (index
< 0 || count
<= 0) {
565 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
569 m_sizeHintResolver
->itemsRemoved(index
, count
);
571 const int firstRemovedIndex
= index
;
572 const int lastRemovedIndex
= index
+ count
- 1;
573 const int lastIndex
= m_model
->count() + count
- 1;
575 // Remove all KItemListWidget instances that got deleted
576 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
577 KItemListWidget
* widget
= m_visibleItems
.value(i
);
582 m_animation
->stop(widget
);
583 // Stopping the animation might lead to recycling the widget if
584 // it is invisible (see slotAnimationFinished()).
585 // Check again whether it is still visible:
586 if (!m_visibleItems
.contains(i
)) {
590 if (m_model
->count() == 0) {
591 // For performance reasons no animation is done when all items have
593 recycleWidget(widget
);
595 // Animate the removing of the items. Special case: When removing an item there
596 // is no valid model index available anymore. For the
597 // remove-animation the item gets removed from m_visibleItems but the widget
598 // will stay alive until the animation has been finished and will
599 // be recycled (deleted) in KItemListView::slotAnimationFinished().
600 m_visibleItems
.remove(i
);
601 widget
->setIndex(-1);
602 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
606 // Update the indexes of all KItemListWidget instances that are located
607 // after the deleted items
608 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
609 KItemListWidget
* widget
= m_visibleItems
.value(i
);
611 const int newIndex
= i
- count
;
612 setWidgetIndex(widget
, newIndex
);
616 m_layouter
->markAsDirty();
617 if (!hasMultipleRanges
) {
618 doLayout(Animation
, index
, -count
);
624 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
627 if (hasMultipleRanges
) {
632 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
633 const QSet
<QByteArray
>& roles
)
635 foreach (const KItemRange
& itemRange
, itemRanges
) {
636 const int index
= itemRange
.index
;
637 const int count
= itemRange
.count
;
639 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
641 const int lastIndex
= index
+ count
- 1;
642 for (int i
= index
; i
<= lastIndex
; ++i
) {
643 KItemListWidget
* widget
= m_visibleItems
.value(i
);
645 widget
->setData(m_model
->data(i
), roles
);
651 void KItemListView::slotCurrentChanged(int current
, int previous
)
655 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
656 if (previousWidget
) {
657 Q_ASSERT(previousWidget
->isCurrent());
658 previousWidget
->setCurrent(false);
661 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
663 Q_ASSERT(!currentWidget
->isCurrent());
664 currentWidget
->setCurrent(true);
667 const QRectF viewGeometry
= geometry();
668 const QRectF currentBoundingRect
= itemBoundingRect(current
);
670 if (!viewGeometry
.contains(currentBoundingRect
)) {
671 // Make sure that the new current item is fully visible in the view.
672 qreal newOffset
= offset();
673 if (currentBoundingRect
.top() < viewGeometry
.top()) {
674 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
675 newOffset
+= currentBoundingRect
.top() - viewGeometry
.top();
677 else if ((currentBoundingRect
.bottom() > viewGeometry
.bottom())) {
678 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
679 newOffset
+= currentBoundingRect
.bottom() - viewGeometry
.bottom();
681 else if (currentBoundingRect
.left() < viewGeometry
.left()) {
682 if (scrollOrientation() == Qt::Horizontal
) {
683 newOffset
+= currentBoundingRect
.left() - viewGeometry
.left();
686 else if ((currentBoundingRect
.right() > viewGeometry
.right())) {
687 if (scrollOrientation() == Qt::Horizontal
) {
688 newOffset
+= currentBoundingRect
.right() - viewGeometry
.right();
692 if (newOffset
!= offset()) {
693 emit
scrollTo(newOffset
);
698 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
702 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
703 while (it
.hasNext()) {
705 const int index
= it
.key();
706 KItemListWidget
* widget
= it
.value();
707 widget
->setSelected(current
.contains(index
));
711 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
712 KItemListViewAnimation::AnimationType type
)
714 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
715 Q_ASSERT(itemListWidget
);
718 case KItemListViewAnimation::DeleteAnimation
: {
719 // As we recycle the widget in this case it is important to assure that no
720 // other animation has been started. This is a convention in KItemListView and
721 // not a requirement defined by KItemListViewAnimation.
722 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
724 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
725 // by m_visibleWidgets and must be deleted manually after the animation has
727 KItemListGroupHeader
* header
= m_visibleGroups
.value(itemListWidget
);
729 m_groupHeaderCreator
->recycle(header
);
730 m_visibleGroups
.remove(itemListWidget
);
732 m_widgetCreator
->recycle(itemListWidget
);
736 case KItemListViewAnimation::CreateAnimation
:
737 case KItemListViewAnimation::MovingAnimation
:
738 case KItemListViewAnimation::ResizeAnimation
: {
739 const int index
= itemListWidget
->index();
740 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
741 (index
> m_layouter
->lastVisibleIndex());
742 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
743 recycleWidget(itemListWidget
);
752 void KItemListView::slotLayoutTimerFinished()
754 m_layouter
->setSize(geometry().size());
755 doLayout(Animation
, 0, 0);
758 void KItemListView::slotRubberBandStartPosChanged()
763 void KItemListView::slotRubberBandEndPosChanged()
765 // The autoscrolling is triggered asynchronously otherwise it
766 // might be possible to have an endless recursion: The autoscrolling
767 // might adjust the position which might result in updating the
768 // rubberband end-position.
769 QTimer::singleShot(0, this, SLOT(triggerAutoScrolling()));
773 void KItemListView::slotRubberBandActivationChanged(bool active
)
776 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandStartPosChanged()));
777 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandEndPosChanged()));
779 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandStartPosChanged()));
780 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandEndPosChanged()));
786 void KItemListView::triggerAutoScrolling()
790 if (scrollOrientation() == Qt::Vertical
) {
791 pos
= m_mousePos
.y();
792 visibleSize
= size().height();
794 pos
= m_mousePos
.x();
795 visibleSize
= size().width();
798 const int inc
= calculateAutoScrollingIncrement(pos
, visibleSize
);
800 // The mouse position is not above an autoscroll margin
804 if (m_rubberBand
->isActive()) {
805 // If a rubberband selection is ongoing the autoscrolling may only get triggered
806 // if the direction of the rubberband is similar to the autoscroll direction.
808 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
809 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
810 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
811 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
812 if (qAbs(diff
) < minDiff
|| (inc
< 0 && diff
> 0) || (inc
> 0 && diff
< 0)) {
813 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
814 // been moved up although the autoscroll direction might be down)
819 emit
scrollTo(offset() + inc
);
822 void KItemListView::setController(KItemListController
* controller
)
824 if (m_controller
!= controller
) {
825 KItemListController
* previous
= m_controller
;
827 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
828 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
829 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
832 m_controller
= controller
;
835 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
836 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
837 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
840 onControllerChanged(controller
, previous
);
844 void KItemListView::setModel(KItemModelBase
* model
)
846 if (m_model
== model
) {
850 KItemModelBase
* previous
= m_model
;
853 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
854 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
855 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
856 this, SLOT(slotItemsInserted(KItemRangeList
)));
857 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
858 this, SLOT(slotItemsRemoved(KItemRangeList
)));
862 m_layouter
->setModel(model
);
863 m_grouped
= !model
->groupRole().isEmpty();
866 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
867 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
868 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
869 this, SLOT(slotItemsInserted(KItemRangeList
)));
870 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
871 this, SLOT(slotItemsRemoved(KItemRangeList
)));
874 onModelChanged(model
, previous
);
877 KItemListRubberBand
* KItemListView::rubberBand() const
882 void KItemListView::updateLayout()
884 doLayout(Animation
, 0, 0);
888 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
890 if (m_layoutTimer
->isActive()) {
891 kDebug() << "Stopping layout timer, synchronous layout requested";
892 m_layoutTimer
->stop();
895 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
899 applyDynamicItemSize();
901 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
902 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
903 if (firstVisibleIndex
< 0) {
908 // Do a sanity check of the offset-property: When properties of the itemlist-view have been changed
909 // it might be possible that the maximum offset got changed too. Assure that the full visible range
910 // is still shown if the maximum offset got decreased.
911 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
912 const qreal maxOffsetToShowFullRange
= maximumOffset() - visibleOffsetRange
;
913 if (offset() > maxOffsetToShowFullRange
) {
914 m_layouter
->setOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
917 // Determine all items that are completely invisible and might be
918 // reused for items that just got (at least partly) visible.
919 // Items that do e.g. an animated moving of their position are not
920 // marked as invisible: This assures that a scrolling inside the view
921 // can be done without breaking an animation.
922 QList
<int> reusableItems
;
923 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
924 while (it
.hasNext()) {
926 KItemListWidget
* widget
= it
.value();
927 const int index
= widget
->index();
928 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
929 if (invisible
&& !m_animation
->isStarted(widget
)) {
930 widget
->setVisible(false);
931 reusableItems
.append(index
);
935 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
936 // instances from invisible items are reused. If no reusable items are
937 // found then new KItemListWidget instances get created.
938 const bool animate
= (hint
== Animation
);
939 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
940 bool applyNewPos
= true;
941 bool wasHidden
= false;
943 const QRectF itemBounds
= m_layouter
->itemBoundingRect(i
);
944 const QPointF newPos
= itemBounds
.topLeft();
945 KItemListWidget
* widget
= m_visibleItems
.value(i
);
948 if (!reusableItems
.isEmpty()) {
949 // Reuse a KItemListWidget instance from an invisible item
950 const int oldIndex
= reusableItems
.takeLast();
951 widget
= m_visibleItems
.value(oldIndex
);
952 setWidgetIndex(widget
, i
);
954 // No reusable KItemListWidget instance is available, create a new one
955 widget
= createWidget(i
);
957 widget
->resize(itemBounds
.size());
959 if (animate
&& changedCount
< 0) {
960 // Items have been deleted, move the created item to the
961 // imaginary old position.
962 const QRectF itemBoundingRect
= m_layouter
->itemBoundingRect(i
- changedCount
);
963 if (itemBoundingRect
.isEmpty()) {
964 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
965 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
966 widget
->setPos(invisibleOldPos
);
968 widget
->setPos(itemBoundingRect
.topLeft());
972 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
977 const bool itemsRemoved
= (changedCount
< 0);
978 const bool itemsInserted
= (changedCount
> 0);
980 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
981 // The item is located after the removed items. Animate the moving of the position.
982 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
984 } else if (itemsInserted
&& i
>= changedIndex
) {
985 // The item is located after the first inserted item
986 if (i
<= changedIndex
+ changedCount
- 1) {
987 // The item is an inserted item. Animate the appearing of the item.
988 // For performance reasons no animation is done when changedCount is equal
989 // to all available items.
990 if (changedCount
< m_model
->count()) {
991 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
993 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
994 // The item was already there before, so animate the moving of the position.
995 // No moving animation is done if the item is animated by a create animation: This
996 // prevents a "move animation mess" when inserting several ranges in parallel.
997 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1000 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1001 // The size of the view might have been changed. Animate the moving of the position.
1002 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1003 applyNewPos
= false;
1008 widget
->setPos(newPos
);
1011 Q_ASSERT(widget
->index() == i
);
1012 widget
->setVisible(true);
1014 if (widget
->size() != itemBounds
.size()) {
1015 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1019 // Delete invisible KItemListWidget instances that have not been reused
1020 foreach (int index
, reusableItems
) {
1021 recycleWidget(m_visibleItems
.value(index
));
1024 emitOffsetChanges();
1027 void KItemListView::emitOffsetChanges()
1029 const qreal newOffset
= m_layouter
->offset();
1030 if (m_oldOffset
!= newOffset
) {
1031 emit
offsetChanged(newOffset
, m_oldOffset
);
1032 m_oldOffset
= newOffset
;
1035 const qreal newMaximumOffset
= m_layouter
->maximumOffset();
1036 if (m_oldMaximumOffset
!= newMaximumOffset
) {
1037 emit
maximumOffsetChanged(newMaximumOffset
, m_oldMaximumOffset
);
1038 m_oldMaximumOffset
= newMaximumOffset
;
1042 KItemListWidget
* KItemListView::createWidget(int index
)
1044 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1045 updateWidgetProperties(widget
, index
);
1046 m_visibleItems
.insert(index
, widget
);
1049 if (m_layouter
->isFirstGroupItem(index
)) {
1050 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1051 header
->setPos(0, -50);
1052 header
->resize(50, 50);
1053 m_visibleGroups
.insert(widget
, header
);
1057 initializeItemListWidget(widget
);
1061 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1064 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1066 m_groupHeaderCreator
->recycle(header
);
1067 m_visibleGroups
.remove(widget
);
1071 m_visibleItems
.remove(widget
->index());
1072 m_widgetCreator
->recycle(widget
);
1075 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1078 bool createHeader
= m_layouter
->isFirstGroupItem(index
);
1079 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1082 createHeader
= false;
1084 m_groupHeaderCreator
->recycle(header
);
1085 m_visibleGroups
.remove(widget
);
1090 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1091 header
->setPos(0, -50);
1092 header
->resize(50, 50);
1093 m_visibleGroups
.insert(widget
, header
);
1097 const int oldIndex
= widget
->index();
1098 m_visibleItems
.remove(oldIndex
);
1099 updateWidgetProperties(widget
, index
);
1100 m_visibleItems
.insert(index
, widget
);
1102 initializeItemListWidget(widget
);
1105 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1107 // Calculate the first visible index and last visible index for the current size
1108 const int currentFirst
= m_layouter
->firstVisibleIndex();
1109 const int currentLast
= m_layouter
->lastVisibleIndex();
1111 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1113 // Calculate the first visible index and last visible index for the new size
1114 setLayouterSize(size
, sizeType
);
1115 const int newFirst
= m_layouter
->firstVisibleIndex();
1116 const int newLast
= m_layouter
->lastVisibleIndex();
1118 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1119 // At least one index has been changed. Assure that widgets for all possible
1120 // visible items get created so that a move-animation can be started later.
1121 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1122 int minFirst
= qMin(newFirst
, currentFirst
);
1123 const int maxLast
= qMax(newLast
, currentLast
);
1125 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1126 // Increasing the size might result in a smaller KItemListView::offset().
1127 // Decrease the first visible index in a way that at least the maximum
1128 // visible items are shown.
1129 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1132 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1133 // The creating of widgets is quite expensive. Assure that never more
1134 // than 50 % of the maximum visible items get created for the animations.
1138 setLayouterSize(currentSize
, sizeType
);
1139 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1140 if (!m_visibleItems
.contains(i
)) {
1141 KItemListWidget
* widget
= createWidget(i
);
1142 const QPointF pos
= m_layouter
->itemBoundingRect(i
).topLeft();
1143 widget
->setPos(pos
);
1146 setLayouterSize(size
, sizeType
);
1150 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1153 case LayouterSize
: m_layouter
->setSize(size
); break;
1154 case ItemSize
: m_layouter
->setItemSize(size
); break;
1159 bool KItemListView::markVisibleRolesSizesAsDirty()
1161 const bool dirty
= m_itemSize
.isEmpty();
1163 m_visibleRolesSizes
.clear();
1164 m_layouter
->setItemSize(QSizeF());
1169 void KItemListView::applyDynamicItemSize()
1171 if (!m_itemSize
.isEmpty()) {
1175 if (m_visibleRolesSizes
.isEmpty()) {
1176 m_visibleRolesSizes
= visibleRoleSizes();
1177 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1178 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1182 if (m_layouter
->itemSize().isEmpty()) {
1183 qreal requiredWidth
= 0;
1184 qreal requiredHeight
= 0;
1186 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1187 while (it
.hasNext()) {
1189 const QSizeF
& visibleRoleSize
= it
.value();
1190 requiredWidth
+= visibleRoleSize
.width();
1191 requiredHeight
+= visibleRoleSize
.height();
1194 QSizeF dynamicItemSize
= m_itemSize
;
1195 if (dynamicItemSize
.width() <= 0) {
1196 dynamicItemSize
.setWidth(qMax(requiredWidth
, size().width()));
1198 if (dynamicItemSize
.height() <= 0) {
1199 dynamicItemSize
.setHeight(qMax(requiredHeight
, size().height()));
1202 m_layouter
->setItemSize(dynamicItemSize
);
1206 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1208 widget
->setVisibleRoles(m_visibleRoles
);
1209 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1210 widget
->setStyleOption(m_styleOption
);
1212 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1213 widget
->setCurrent(index
== selectionManager
->currentItem());
1215 if (selectionManager
->hasSelection()) {
1216 const QSet
<int> selectedItems
= selectionManager
->selectedItems();
1217 widget
->setSelected(selectedItems
.contains(index
));
1219 widget
->setSelected(false);
1222 widget
->setHovered(false);
1224 widget
->setIndex(index
);
1225 widget
->setData(m_model
->data(index
));
1228 int KItemListView::calculateAutoScrollingIncrement(int pos
, int size
)
1232 const int minSpeed
= 4;
1233 const int maxSpeed
= 768;
1234 const int speedLimiter
= 48;
1235 const int autoScrollBorder
= 64;
1237 if (pos
< autoScrollBorder
) {
1238 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1239 if (inc
< -maxSpeed
) {
1242 } else if (pos
> size
- autoScrollBorder
) {
1243 inc
= minSpeed
+ qAbs(pos
- size
+ autoScrollBorder
) * (pos
- size
+ autoScrollBorder
) / speedLimiter
;
1244 if (inc
> maxSpeed
) {
1253 KItemListCreatorBase::~KItemListCreatorBase()
1255 qDeleteAll(m_recycleableWidgets
);
1256 qDeleteAll(m_createdWidgets
);
1259 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1261 m_createdWidgets
.insert(widget
);
1264 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1266 Q_ASSERT(m_createdWidgets
.contains(widget
));
1267 m_createdWidgets
.remove(widget
);
1269 if (m_recycleableWidgets
.count() < 100) {
1270 m_recycleableWidgets
.append(widget
);
1271 widget
->setVisible(false);
1277 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1279 if (m_recycleableWidgets
.isEmpty()) {
1283 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1284 m_createdWidgets
.insert(widget
);
1288 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1292 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1294 widget
->setOpacity(1.0);
1295 pushRecycleableWidget(widget
);
1298 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1302 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1304 header
->setOpacity(1.0);
1305 pushRecycleableWidget(header
);
1308 #include "kitemlistview.moc"