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 "kitemlistheader_p.h"
28 #include "kitemlistrubberband_p.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistsizehintresolver_p.h"
31 #include "kitemlistviewlayouter_p.h"
32 #include "kitemlistviewanimation_p.h"
33 #include "kitemlistwidget.h"
38 #include <QGraphicsSceneMouseEvent>
40 #include <QPropertyAnimation>
42 #include <QStyleOptionRubberBand>
46 // Time in ms until reaching the autoscroll margin triggers
47 // an initial autoscrolling
48 const int InitialAutoScrollDelay
= 700;
50 // Delay in ms for triggering the next autoscroll
51 const int RepeatingAutoScrollDelay
= 1000 / 60;
54 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
55 QGraphicsWidget(parent
),
57 m_activeTransactions(0),
62 m_visibleRolesSizes(),
64 m_groupHeaderCreator(0),
68 m_sizeHintResolver(0),
73 m_oldMaximumOffset(0),
74 m_skipAutoScrollForRubberBand(false),
77 m_autoScrollIncrement(0),
80 m_useHeaderWidths(false)
82 setAcceptHoverEvents(true);
84 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
86 m_layouter
= new KItemListViewLayouter(this);
87 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
89 m_animation
= new KItemListViewAnimation(this);
90 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
91 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
93 m_layoutTimer
= new QTimer(this);
94 m_layoutTimer
->setInterval(300);
95 m_layoutTimer
->setSingleShot(true);
96 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
98 m_rubberBand
= new KItemListRubberBand(this);
99 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
102 KItemListView::~KItemListView()
104 delete m_sizeHintResolver
;
105 m_sizeHintResolver
= 0;
108 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
110 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
111 if (orientation
== previousOrientation
) {
115 m_layouter
->setScrollOrientation(orientation
);
116 m_animation
->setScrollOrientation(orientation
);
117 m_sizeHintResolver
->clearCache();
119 onScrollOrientationChanged(orientation
, previousOrientation
);
122 Qt::Orientation
KItemListView::scrollOrientation() const
124 return m_layouter
->scrollOrientation();
127 void KItemListView::setItemSize(const QSizeF
& itemSize
)
129 const QSizeF previousSize
= m_itemSize
;
130 if (itemSize
== previousSize
) {
134 m_itemSize
= itemSize
;
136 if (!markVisibleRolesSizesAsDirty()) {
137 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
138 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
140 m_layouter
->setItemSize(itemSize
);
144 m_sizeHintResolver
->clearCache();
146 onItemSizeChanged(itemSize
, previousSize
);
149 QSizeF
KItemListView::itemSize() const
154 void KItemListView::setOffset(qreal offset
)
160 const qreal previousOffset
= m_layouter
->offset();
161 if (offset
== previousOffset
) {
165 m_layouter
->setOffset(offset
);
166 m_animation
->setOffset(offset
);
167 if (!m_layoutTimer
->isActive()) {
168 doLayout(NoAnimation
, 0, 0);
171 onOffsetChanged(offset
, previousOffset
);
174 qreal
KItemListView::offset() const
176 return m_layouter
->offset();
179 qreal
KItemListView::maximumOffset() const
181 return m_layouter
->maximumOffset();
184 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
186 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
187 m_visibleRoles
= roles
;
189 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
190 while (it
.hasNext()) {
192 KItemListWidget
* widget
= it
.value();
193 widget
->setVisibleRoles(roles
);
194 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
197 m_sizeHintResolver
->clearCache();
198 m_layouter
->markAsDirty();
199 onVisibleRolesChanged(roles
, previousRoles
);
201 markVisibleRolesSizesAsDirty();
205 m_header
->setVisibleRoles(roles
);
206 m_header
->setVisibleRolesWidths(headerRolesWidths());
207 m_useHeaderWidths
= false;
211 QList
<QByteArray
> KItemListView::visibleRoles() const
213 return m_visibleRoles
;
216 void KItemListView::setAutoScroll(bool enabled
)
218 if (enabled
&& !m_autoScrollTimer
) {
219 m_autoScrollTimer
= new QTimer(this);
220 m_autoScrollTimer
->setSingleShot(false);
221 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
222 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
223 } else if (!enabled
&& m_autoScrollTimer
) {
224 delete m_autoScrollTimer
;
225 m_autoScrollTimer
= 0;
230 bool KItemListView::autoScroll() const
232 return m_autoScrollTimer
!= 0;
235 void KItemListView::setHeaderShown(bool show
)
237 if (show
&& !m_header
) {
238 m_header
= new KItemListHeader(this);
239 m_header
->setPos(0, 0);
240 m_header
->setModel(m_model
);
241 m_header
->setVisibleRoles(m_visibleRoles
);
242 m_header
->setVisibleRolesWidths(headerRolesWidths());
243 m_header
->setZValue(1);
245 m_useHeaderWidths
= false;
248 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
249 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
251 m_layouter
->setHeaderHeight(m_header
->size().height());
252 } else if (!show
&& m_header
) {
255 m_useHeaderWidths
= false;
256 m_layouter
->setHeaderHeight(0);
260 bool KItemListView::isHeaderShown() const
262 return m_header
!= 0;
265 KItemListController
* KItemListView::controller() const
270 KItemModelBase
* KItemListView::model() const
275 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
277 m_widgetCreator
= widgetCreator
;
280 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
282 return m_widgetCreator
;
285 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
287 m_groupHeaderCreator
= groupHeaderCreator
;
290 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
292 return m_groupHeaderCreator
;
295 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
297 const KItemListStyleOption previousOption
= m_styleOption
;
298 m_styleOption
= option
;
300 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
301 while (it
.hasNext()) {
303 it
.value()->setStyleOption(option
);
306 m_sizeHintResolver
->clearCache();
308 onStyleOptionChanged(option
, previousOption
);
311 const KItemListStyleOption
& KItemListView::styleOption() const
313 return m_styleOption
;
316 void KItemListView::setGeometry(const QRectF
& rect
)
318 QGraphicsWidget::setGeometry(rect
);
323 if (m_itemSize
.isEmpty()) {
324 m_layouter
->setItemSize(QSizeF());
327 if (m_model
->count() > 0) {
328 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
330 m_layouter
->setSize(rect
.size());
333 if (!m_layoutTimer
->isActive()) {
334 m_layoutTimer
->start();
338 int KItemListView::itemAt(const QPointF
& pos
) const
340 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
341 while (it
.hasNext()) {
344 const KItemListWidget
* widget
= it
.value();
345 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
346 if (widget
->contains(mappedPos
)) {
354 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
361 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
363 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
365 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
366 if (!expansionToggleRect
.isEmpty()) {
367 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
368 return expansionToggleRect
.contains(mappedPos
);
374 int KItemListView::firstVisibleIndex() const
376 return m_layouter
->firstVisibleIndex();
379 int KItemListView::lastVisibleIndex() const
381 return m_layouter
->lastVisibleIndex();
384 QSizeF
KItemListView::itemSizeHint(int index
) const
390 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRoleSizes() const
392 return QHash
<QByteArray
, QSizeF
>();
395 QRectF
KItemListView::itemBoundingRect(int index
) const
397 return m_layouter
->itemBoundingRect(index
);
400 int KItemListView::itemsPerOffset() const
402 return m_layouter
->itemsPerOffset();
405 void KItemListView::beginTransaction()
407 ++m_activeTransactions
;
408 if (m_activeTransactions
== 1) {
409 onTransactionBegin();
413 void KItemListView::endTransaction()
415 --m_activeTransactions
;
416 if (m_activeTransactions
< 0) {
417 m_activeTransactions
= 0;
418 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
421 if (m_activeTransactions
== 0) {
427 bool KItemListView::isTransactionActive() const
429 return m_activeTransactions
> 0;
432 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
438 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
440 QGraphicsWidget::paint(painter
, option
, widget
);
442 if (m_rubberBand
->isActive()) {
443 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
444 m_rubberBand
->endPosition()).normalized();
446 const QPointF topLeft
= rubberBandRect
.topLeft();
447 if (scrollOrientation() == Qt::Vertical
) {
448 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - offset());
450 rubberBandRect
.moveTo(topLeft
.x() - offset(), topLeft
.y());
453 QStyleOptionRubberBand opt
;
454 opt
.initFrom(widget
);
455 opt
.shape
= QRubberBand::Rectangle
;
457 opt
.rect
= rubberBandRect
.toRect();
458 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
462 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
467 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
469 Q_UNUSED(changedRoles
);
473 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
479 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
485 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
491 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
497 void KItemListView::onOffsetChanged(qreal current
, qreal previous
)
503 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
509 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
515 void KItemListView::onTransactionBegin()
519 void KItemListView::onTransactionEnd()
523 bool KItemListView::event(QEvent
* event
)
525 // Forward all events to the controller and handle them there
526 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
530 return QGraphicsWidget::event(event
);
533 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
535 m_mousePos
= transform().map(event
->pos());
539 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
541 QGraphicsWidget::mouseMoveEvent(event
);
543 m_mousePos
= transform().map(event
->pos());
544 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
545 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
549 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
551 event
->setAccepted(true);
555 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
557 QGraphicsWidget::dragMoveEvent(event
);
559 m_mousePos
= transform().map(event
->pos());
560 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
561 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
565 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
567 QGraphicsWidget::dragLeaveEvent(event
);
568 setAutoScroll(false);
571 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
573 QGraphicsWidget::dropEvent(event
);
574 setAutoScroll(false);
577 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
579 return m_visibleItems
.values();
582 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
584 QGraphicsWidget::resizeEvent(event
);
588 bool KItemListView::markVisibleRolesSizesAsDirty()
590 const bool dirty
= m_itemSize
.isEmpty();
591 if (dirty
&& !m_useHeaderWidths
) {
592 m_visibleRolesSizes
.clear();
593 m_layouter
->setItemSize(QSizeF());
598 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
600 markVisibleRolesSizesAsDirty();
602 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
603 if (hasMultipleRanges
) {
607 int previouslyInsertedCount
= 0;
608 foreach (const KItemRange
& range
, itemRanges
) {
609 // range.index is related to the model before anything has been inserted.
610 // As in each loop the current item-range gets inserted the index must
611 // be increased by the already previously inserted items.
612 const int index
= range
.index
+ previouslyInsertedCount
;
613 const int count
= range
.count
;
614 if (index
< 0 || count
<= 0) {
615 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
618 previouslyInsertedCount
+= count
;
620 m_sizeHintResolver
->itemsInserted(index
, count
);
622 // Determine which visible items must be moved
623 QList
<int> itemsToMove
;
624 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
625 while (it
.hasNext()) {
627 const int visibleItemIndex
= it
.key();
628 if (visibleItemIndex
>= index
) {
629 itemsToMove
.append(visibleItemIndex
);
633 // Update the indexes of all KItemListWidget instances that are located
634 // after the inserted items. It is important to adjust the indexes in the order
635 // from the highest index to the lowest index to prevent overlaps when setting the new index.
637 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
638 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
640 setWidgetIndex(widget
, widget
->index() + count
);
643 m_layouter
->markAsDirty();
644 if (m_model
->count() == count
&& maximumOffset() > size().height()) {
645 kDebug() << "Scrollbar required, skipping layout";
646 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
647 QSizeF layouterSize
= m_layouter
->size();
648 if (scrollOrientation() == Qt::Vertical
) {
649 layouterSize
.rwidth() -= scrollBarExtent
;
651 layouterSize
.rheight() -= scrollBarExtent
;
653 m_layouter
->setSize(layouterSize
);
656 if (!hasMultipleRanges
) {
657 doLayout(Animation
, index
, count
);
663 m_controller
->selectionManager()->itemsInserted(itemRanges
);
666 if (hasMultipleRanges
) {
671 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
673 markVisibleRolesSizesAsDirty();
675 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
676 if (hasMultipleRanges
) {
680 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
681 const KItemRange
& range
= itemRanges
.at(i
);
682 const int index
= range
.index
;
683 const int count
= range
.count
;
684 if (index
< 0 || count
<= 0) {
685 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
689 m_sizeHintResolver
->itemsRemoved(index
, count
);
691 const int firstRemovedIndex
= index
;
692 const int lastRemovedIndex
= index
+ count
- 1;
693 const int lastIndex
= m_model
->count() + count
- 1;
695 // Remove all KItemListWidget instances that got deleted
696 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
697 KItemListWidget
* widget
= m_visibleItems
.value(i
);
702 m_animation
->stop(widget
);
703 // Stopping the animation might lead to recycling the widget if
704 // it is invisible (see slotAnimationFinished()).
705 // Check again whether it is still visible:
706 if (!m_visibleItems
.contains(i
)) {
710 if (m_model
->count() == 0) {
711 // For performance reasons no animation is done when all items have
713 recycleWidget(widget
);
715 // Animate the removing of the items. Special case: When removing an item there
716 // is no valid model index available anymore. For the
717 // remove-animation the item gets removed from m_visibleItems but the widget
718 // will stay alive until the animation has been finished and will
719 // be recycled (deleted) in KItemListView::slotAnimationFinished().
720 m_visibleItems
.remove(i
);
721 widget
->setIndex(-1);
722 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
726 // Update the indexes of all KItemListWidget instances that are located
727 // after the deleted items
728 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
729 KItemListWidget
* widget
= m_visibleItems
.value(i
);
731 const int newIndex
= i
- count
;
732 setWidgetIndex(widget
, newIndex
);
736 m_layouter
->markAsDirty();
737 if (!hasMultipleRanges
) {
738 doLayout(Animation
, index
, -count
);
744 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
747 if (hasMultipleRanges
) {
752 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
753 const QSet
<QByteArray
>& roles
)
755 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
756 if (updateSizeHints
) {
757 markVisibleRolesSizesAsDirty();
760 foreach (const KItemRange
& itemRange
, itemRanges
) {
761 const int index
= itemRange
.index
;
762 const int count
= itemRange
.count
;
764 if (updateSizeHints
) {
765 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
766 m_layouter
->markAsDirty();
770 // Apply the changed roles to the visible item-widgets
771 const int lastIndex
= index
+ count
- 1;
772 for (int i
= index
; i
<= lastIndex
; ++i
) {
773 KItemListWidget
* widget
= m_visibleItems
.value(i
);
775 widget
->setData(m_model
->data(i
), roles
);
782 void KItemListView::slotCurrentChanged(int current
, int previous
)
786 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
787 if (previousWidget
) {
788 Q_ASSERT(previousWidget
->isCurrent());
789 previousWidget
->setCurrent(false);
792 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
794 Q_ASSERT(!currentWidget
->isCurrent());
795 currentWidget
->setCurrent(true);
798 const QRectF viewGeometry
= geometry();
799 const QRectF currentBoundingRect
= itemBoundingRect(current
);
801 if (!viewGeometry
.contains(currentBoundingRect
)) {
802 // Make sure that the new current item is fully visible in the view.
803 qreal newOffset
= offset();
804 if (currentBoundingRect
.top() < viewGeometry
.top()) {
805 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
806 newOffset
+= currentBoundingRect
.top() - viewGeometry
.top();
807 } else if ((currentBoundingRect
.bottom() > viewGeometry
.bottom())) {
808 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
809 newOffset
+= currentBoundingRect
.bottom() - viewGeometry
.bottom();
810 } else if (currentBoundingRect
.left() < viewGeometry
.left()) {
811 if (scrollOrientation() == Qt::Horizontal
) {
812 newOffset
+= currentBoundingRect
.left() - viewGeometry
.left();
814 } else if ((currentBoundingRect
.right() > viewGeometry
.right())) {
815 if (scrollOrientation() == Qt::Horizontal
) {
816 newOffset
+= currentBoundingRect
.right() - viewGeometry
.right();
820 if (newOffset
!= offset()) {
821 emit
scrollTo(newOffset
);
826 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
830 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
831 while (it
.hasNext()) {
833 const int index
= it
.key();
834 KItemListWidget
* widget
= it
.value();
835 widget
->setSelected(current
.contains(index
));
839 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
840 KItemListViewAnimation::AnimationType type
)
842 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
843 Q_ASSERT(itemListWidget
);
846 case KItemListViewAnimation::DeleteAnimation
: {
847 // As we recycle the widget in this case it is important to assure that no
848 // other animation has been started. This is a convention in KItemListView and
849 // not a requirement defined by KItemListViewAnimation.
850 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
852 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
853 // by m_visibleWidgets and must be deleted manually after the animation has
855 KItemListGroupHeader
* header
= m_visibleGroups
.value(itemListWidget
);
857 m_groupHeaderCreator
->recycle(header
);
858 m_visibleGroups
.remove(itemListWidget
);
860 m_widgetCreator
->recycle(itemListWidget
);
864 case KItemListViewAnimation::CreateAnimation
:
865 case KItemListViewAnimation::MovingAnimation
:
866 case KItemListViewAnimation::ResizeAnimation
: {
867 const int index
= itemListWidget
->index();
868 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
869 (index
> m_layouter
->lastVisibleIndex());
870 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
871 recycleWidget(itemListWidget
);
880 void KItemListView::slotLayoutTimerFinished()
882 m_layouter
->setSize(geometry().size());
883 doLayout(Animation
, 0, 0);
886 void KItemListView::slotRubberBandPosChanged()
891 void KItemListView::slotRubberBandActivationChanged(bool active
)
894 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
895 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
896 m_skipAutoScrollForRubberBand
= true;
898 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
899 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
900 m_skipAutoScrollForRubberBand
= false;
906 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
910 Q_UNUSED(previousWidth
);
912 m_useHeaderWidths
= true;
914 if (m_visibleRolesSizes
.contains(role
)) {
915 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
916 roleSize
.setWidth(currentWidth
);
917 m_visibleRolesSizes
.insert(role
, roleSize
);
920 m_layouter
->setItemSize(QSizeF()); // Forces an update in applyDynamicItemSize()
924 void KItemListView::triggerAutoScrolling()
926 if (!m_autoScrollTimer
) {
932 if (scrollOrientation() == Qt::Vertical
) {
933 pos
= m_mousePos
.y();
934 visibleSize
= size().height();
936 pos
= m_mousePos
.x();
937 visibleSize
= size().width();
940 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
941 m_autoScrollIncrement
= 0;
944 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
945 if (m_autoScrollIncrement
== 0) {
946 // The mouse position is not above an autoscroll margin (the autoscroll timer
947 // will be restarted in mouseMoveEvent())
948 m_autoScrollTimer
->stop();
952 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
953 // If a rubberband selection is ongoing the autoscrolling may only get triggered
954 // if the direction of the rubberband is similar to the autoscroll direction. This
955 // prevents that starting to create a rubberband within the autoscroll margins starts
958 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
959 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
960 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
961 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
962 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
963 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
964 // been moved up although the autoscroll direction might be down)
965 m_autoScrollTimer
->stop();
970 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
971 // the autoscrolling may not get skipped anymore until a new rubberband is created
972 m_skipAutoScrollForRubberBand
= false;
974 setOffset(offset() + m_autoScrollIncrement
);
976 // Trigger the autoscroll timer which will periodically call
977 // triggerAutoScrolling()
978 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
981 void KItemListView::setController(KItemListController
* controller
)
983 if (m_controller
!= controller
) {
984 KItemListController
* previous
= m_controller
;
986 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
987 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
988 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
991 m_controller
= controller
;
994 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
995 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
996 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
999 onControllerChanged(controller
, previous
);
1003 void KItemListView::setModel(KItemModelBase
* model
)
1005 if (m_model
== model
) {
1009 KItemModelBase
* previous
= m_model
;
1012 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1013 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1014 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1015 this, SLOT(slotItemsInserted(KItemRangeList
)));
1016 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1017 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1021 m_layouter
->setModel(model
);
1022 m_grouped
= !model
->groupRole().isEmpty();
1025 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1026 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1027 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1028 this, SLOT(slotItemsInserted(KItemRangeList
)));
1029 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1030 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1033 onModelChanged(model
, previous
);
1036 KItemListRubberBand
* KItemListView::rubberBand() const
1038 return m_rubberBand
;
1041 void KItemListView::updateLayout()
1043 doLayout(Animation
, 0, 0);
1047 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1049 if (m_layoutTimer
->isActive()) {
1050 kDebug() << "Stopping layout timer, synchronous layout requested";
1051 m_layoutTimer
->stop();
1054 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
1058 applyDynamicItemSize();
1060 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1061 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1062 if (firstVisibleIndex
< 0) {
1063 emitOffsetChanges();
1067 // Do a sanity check of the offset-property: When properties of the itemlist-view have been changed
1068 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1069 // is still shown if the maximum offset got decreased.
1070 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1071 const qreal maxOffsetToShowFullRange
= maximumOffset() - visibleOffsetRange
;
1072 if (offset() > maxOffsetToShowFullRange
) {
1073 m_layouter
->setOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1076 // Determine all items that are completely invisible and might be
1077 // reused for items that just got (at least partly) visible.
1078 // Items that do e.g. an animated moving of their position are not
1079 // marked as invisible: This assures that a scrolling inside the view
1080 // can be done without breaking an animation.
1081 QList
<int> reusableItems
;
1082 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1083 while (it
.hasNext()) {
1085 KItemListWidget
* widget
= it
.value();
1086 const int index
= widget
->index();
1087 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1088 if (invisible
&& !m_animation
->isStarted(widget
)) {
1089 widget
->setVisible(false);
1090 reusableItems
.append(index
);
1094 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1095 // instances from invisible items are reused. If no reusable items are
1096 // found then new KItemListWidget instances get created.
1097 const bool animate
= (hint
== Animation
);
1098 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1099 bool applyNewPos
= true;
1100 bool wasHidden
= false;
1102 const QRectF itemBounds
= m_layouter
->itemBoundingRect(i
);
1103 const QPointF newPos
= itemBounds
.topLeft();
1104 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1107 if (!reusableItems
.isEmpty()) {
1108 // Reuse a KItemListWidget instance from an invisible item
1109 const int oldIndex
= reusableItems
.takeLast();
1110 widget
= m_visibleItems
.value(oldIndex
);
1111 setWidgetIndex(widget
, i
);
1113 // No reusable KItemListWidget instance is available, create a new one
1114 widget
= createWidget(i
);
1116 widget
->resize(itemBounds
.size());
1118 if (animate
&& changedCount
< 0) {
1119 // Items have been deleted, move the created item to the
1120 // imaginary old position.
1121 const QRectF itemBoundingRect
= m_layouter
->itemBoundingRect(i
- changedCount
);
1122 if (itemBoundingRect
.isEmpty()) {
1123 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1124 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1125 widget
->setPos(invisibleOldPos
);
1127 widget
->setPos(itemBoundingRect
.topLeft());
1129 applyNewPos
= false;
1131 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1132 applyNewPos
= false;
1136 const bool itemsRemoved
= (changedCount
< 0);
1137 const bool itemsInserted
= (changedCount
> 0);
1139 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1140 // The item is located after the removed items. Animate the moving of the position.
1141 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1142 applyNewPos
= false;
1143 } else if (itemsInserted
&& i
>= changedIndex
) {
1144 // The item is located after the first inserted item
1145 if (i
<= changedIndex
+ changedCount
- 1) {
1146 // The item is an inserted item. Animate the appearing of the item.
1147 // For performance reasons no animation is done when changedCount is equal
1148 // to all available items.
1149 if (changedCount
< m_model
->count()) {
1150 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1152 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1153 // The item was already there before, so animate the moving of the position.
1154 // No moving animation is done if the item is animated by a create animation: This
1155 // prevents a "move animation mess" when inserting several ranges in parallel.
1156 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1157 applyNewPos
= false;
1159 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1160 // The size of the view might have been changed. Animate the moving of the position.
1161 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1162 applyNewPos
= false;
1167 widget
->setPos(newPos
);
1170 Q_ASSERT(widget
->index() == i
);
1171 widget
->setVisible(true);
1173 if (widget
->size() != itemBounds
.size()) {
1174 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1178 // Delete invisible KItemListWidget instances that have not been reused
1179 foreach (int index
, reusableItems
) {
1180 recycleWidget(m_visibleItems
.value(index
));
1183 emitOffsetChanges();
1186 void KItemListView::emitOffsetChanges()
1188 const qreal newOffset
= m_layouter
->offset();
1189 if (m_oldOffset
!= newOffset
) {
1190 emit
offsetChanged(newOffset
, m_oldOffset
);
1191 m_oldOffset
= newOffset
;
1194 const qreal newMaximumOffset
= m_layouter
->maximumOffset();
1195 if (m_oldMaximumOffset
!= newMaximumOffset
) {
1196 emit
maximumOffsetChanged(newMaximumOffset
, m_oldMaximumOffset
);
1197 m_oldMaximumOffset
= newMaximumOffset
;
1201 KItemListWidget
* KItemListView::createWidget(int index
)
1203 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1204 updateWidgetProperties(widget
, index
);
1205 m_visibleItems
.insert(index
, widget
);
1208 if (m_layouter
->isFirstGroupItem(index
)) {
1209 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1210 header
->setPos(0, -50);
1211 header
->resize(50, 50);
1212 m_visibleGroups
.insert(widget
, header
);
1216 initializeItemListWidget(widget
);
1220 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1223 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1225 m_groupHeaderCreator
->recycle(header
);
1226 m_visibleGroups
.remove(widget
);
1230 m_visibleItems
.remove(widget
->index());
1231 m_widgetCreator
->recycle(widget
);
1234 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1237 bool createHeader
= m_layouter
->isFirstGroupItem(index
);
1238 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1241 createHeader
= false;
1243 m_groupHeaderCreator
->recycle(header
);
1244 m_visibleGroups
.remove(widget
);
1249 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1250 header
->setPos(0, -50);
1251 header
->resize(50, 50);
1252 m_visibleGroups
.insert(widget
, header
);
1256 const int oldIndex
= widget
->index();
1257 m_visibleItems
.remove(oldIndex
);
1258 updateWidgetProperties(widget
, index
);
1259 m_visibleItems
.insert(index
, widget
);
1261 initializeItemListWidget(widget
);
1264 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1266 // Calculate the first visible index and last visible index for the current size
1267 const int currentFirst
= m_layouter
->firstVisibleIndex();
1268 const int currentLast
= m_layouter
->lastVisibleIndex();
1270 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1272 // Calculate the first visible index and last visible index for the new size
1273 setLayouterSize(size
, sizeType
);
1274 const int newFirst
= m_layouter
->firstVisibleIndex();
1275 const int newLast
= m_layouter
->lastVisibleIndex();
1277 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1278 // At least one index has been changed. Assure that widgets for all possible
1279 // visible items get created so that a move-animation can be started later.
1280 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1281 int minFirst
= qMin(newFirst
, currentFirst
);
1282 const int maxLast
= qMax(newLast
, currentLast
);
1284 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1285 // Increasing the size might result in a smaller KItemListView::offset().
1286 // Decrease the first visible index in a way that at least the maximum
1287 // visible items are shown.
1288 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1291 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1292 // The creating of widgets is quite expensive. Assure that never more
1293 // than 50 % of the maximum visible items get created for the animations.
1297 setLayouterSize(currentSize
, sizeType
);
1298 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1299 if (!m_visibleItems
.contains(i
)) {
1300 KItemListWidget
* widget
= createWidget(i
);
1301 const QPointF pos
= m_layouter
->itemBoundingRect(i
).topLeft();
1302 widget
->setPos(pos
);
1305 setLayouterSize(size
, sizeType
);
1309 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1312 case LayouterSize
: m_layouter
->setSize(size
); break;
1313 case ItemSize
: m_layouter
->setItemSize(size
); break;
1318 void KItemListView::applyDynamicItemSize()
1320 if (!m_itemSize
.isEmpty()) {
1324 if (m_visibleRolesSizes
.isEmpty()) {
1325 m_visibleRolesSizes
= visibleRoleSizes();
1327 m_header
->setVisibleRolesWidths(headerRolesWidths());
1331 if (m_layouter
->itemSize().isEmpty()) {
1332 // Calculate the maximum size of an item by considering the
1333 // visible role sizes and apply them to the layouter.
1334 qreal requiredWidth
= 0;
1335 qreal requiredHeight
= 0;
1337 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1338 while (it
.hasNext()) {
1340 const QSizeF
& visibleRoleSize
= it
.value();
1341 requiredWidth
+= visibleRoleSize
.width();
1342 requiredHeight
+= visibleRoleSize
.height();
1345 QSizeF dynamicItemSize
= m_itemSize
;
1346 if (dynamicItemSize
.width() <= 0) {
1347 dynamicItemSize
.setWidth(qMax(requiredWidth
, size().width()));
1349 if (dynamicItemSize
.height() <= 0) {
1350 dynamicItemSize
.setHeight(qMax(requiredHeight
, size().height()));
1353 m_layouter
->setItemSize(dynamicItemSize
);
1355 // Update the role sizes for all visible widgets
1356 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1357 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1362 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1364 widget
->setVisibleRoles(m_visibleRoles
);
1365 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1366 widget
->setStyleOption(m_styleOption
);
1368 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1369 widget
->setCurrent(index
== selectionManager
->currentItem());
1371 if (selectionManager
->hasSelection()) {
1372 const QSet
<int> selectedItems
= selectionManager
->selectedItems();
1373 widget
->setSelected(selectedItems
.contains(index
));
1375 widget
->setSelected(false);
1378 widget
->setHovered(false);
1380 widget
->setIndex(index
);
1381 widget
->setData(m_model
->data(index
));
1384 void KItemListView::updateHeaderWidth()
1390 // TODO 1: Use the required width of all roles
1391 m_header
->resize(size().width(), m_header
->size().height());
1394 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1396 QHash
<QByteArray
, qreal
> rolesWidths
;
1398 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1399 while (it
.hasNext()) {
1401 rolesWidths
.insert(it
.key(), it
.value().width());
1407 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1411 const int minSpeed
= 4;
1412 const int maxSpeed
= 128;
1413 const int speedLimiter
= 96;
1414 const int autoScrollBorder
= 64;
1416 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1417 // This assures that the autoscrolling speed grows gradually.
1418 const int incLimiter
= 1;
1420 if (pos
< autoScrollBorder
) {
1421 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1422 inc
= qMax(inc
, -maxSpeed
);
1423 inc
= qMax(inc
, oldInc
- incLimiter
);
1424 } else if (pos
> range
- autoScrollBorder
) {
1425 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1426 inc
= qMin(inc
, maxSpeed
);
1427 inc
= qMin(inc
, oldInc
+ incLimiter
);
1434 KItemListCreatorBase::~KItemListCreatorBase()
1436 qDeleteAll(m_recycleableWidgets
);
1437 qDeleteAll(m_createdWidgets
);
1440 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1442 m_createdWidgets
.insert(widget
);
1445 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1447 Q_ASSERT(m_createdWidgets
.contains(widget
));
1448 m_createdWidgets
.remove(widget
);
1450 if (m_recycleableWidgets
.count() < 100) {
1451 m_recycleableWidgets
.append(widget
);
1452 widget
->setVisible(false);
1458 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1460 if (m_recycleableWidgets
.isEmpty()) {
1464 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1465 m_createdWidgets
.insert(widget
);
1469 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1473 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1475 widget
->setOpacity(1.0);
1476 pushRecycleableWidget(widget
);
1479 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1483 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1485 header
->setOpacity(1.0);
1486 pushRecycleableWidget(header
);
1489 #include "kitemlistview.moc"