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),
62 m_visibleRolesSizes(),
63 m_stretchedVisibleRolesSizes(),
65 m_groupHeaderCreator(0),
69 m_sizeHintResolver(0),
74 m_oldMaximumScrollOffset(0),
76 m_oldMaximumItemOffset(0),
77 m_skipAutoScrollForRubberBand(false),
80 m_autoScrollIncrement(0),
83 m_useHeaderWidths(false)
85 setAcceptHoverEvents(true);
87 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
89 m_layouter
= new KItemListViewLayouter(this);
90 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
92 m_animation
= new KItemListViewAnimation(this);
93 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
94 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
96 m_layoutTimer
= new QTimer(this);
97 m_layoutTimer
->setInterval(300);
98 m_layoutTimer
->setSingleShot(true);
99 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
101 m_rubberBand
= new KItemListRubberBand(this);
102 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
105 KItemListView::~KItemListView()
107 delete m_sizeHintResolver
;
108 m_sizeHintResolver
= 0;
111 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
113 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
114 if (orientation
== previousOrientation
) {
118 m_layouter
->setScrollOrientation(orientation
);
119 m_animation
->setScrollOrientation(orientation
);
120 m_sizeHintResolver
->clearCache();
123 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
124 while (it
.hasNext()) {
126 it
.value()->setScrollOrientation(orientation
);
132 onScrollOrientationChanged(orientation
, previousOrientation
);
133 emit
scrollOrientationChanged(orientation
, previousOrientation
);
136 Qt::Orientation
KItemListView::scrollOrientation() const
138 return m_layouter
->scrollOrientation();
141 void KItemListView::setItemSize(const QSizeF
& itemSize
)
143 const QSizeF previousSize
= m_itemSize
;
144 if (itemSize
== previousSize
) {
148 m_itemSize
= itemSize
;
150 const bool emptySize
= itemSize
.isEmpty();
152 updateVisibleRolesSizes();
154 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
155 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
157 m_layouter
->setItemSize(itemSize
);
161 m_sizeHintResolver
->clearCache();
163 onItemSizeChanged(itemSize
, previousSize
);
166 QSizeF
KItemListView::itemSize() const
171 void KItemListView::setScrollOffset(qreal offset
)
177 const qreal previousOffset
= m_layouter
->scrollOffset();
178 if (offset
== previousOffset
) {
182 m_layouter
->setScrollOffset(offset
);
183 m_animation
->setScrollOffset(offset
);
185 // Don't check whether the m_layoutTimer is active: Changing the
186 // scroll offset must always trigger a synchronous layout, otherwise
187 // the smooth-scrolling might get jerky.
188 doLayout(NoAnimation
);
189 onScrollOffsetChanged(offset
, previousOffset
);
192 qreal
KItemListView::scrollOffset() const
194 return m_layouter
->scrollOffset();
197 qreal
KItemListView::maximumScrollOffset() const
199 return m_layouter
->maximumScrollOffset();
202 void KItemListView::setItemOffset(qreal offset
)
204 if (m_layouter
->itemOffset() == offset
) {
208 m_layouter
->setItemOffset(offset
);
210 m_header
->setPos(-offset
, 0);
213 // Don't check whether the m_layoutTimer is active: Changing the
214 // item offset must always trigger a synchronous layout, otherwise
215 // the smooth-scrolling might get jerky.
216 doLayout(NoAnimation
);
219 qreal
KItemListView::itemOffset() const
221 return m_layouter
->itemOffset();
224 qreal
KItemListView::maximumItemOffset() const
226 return m_layouter
->maximumItemOffset();
229 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
231 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
232 m_visibleRoles
= roles
;
234 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
235 while (it
.hasNext()) {
237 KItemListWidget
* widget
= it
.value();
238 widget
->setVisibleRoles(roles
);
239 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
242 m_sizeHintResolver
->clearCache();
243 m_layouter
->markAsDirty();
246 m_header
->setVisibleRoles(roles
);
247 m_header
->setVisibleRolesWidths(headerRolesWidths());
248 m_useHeaderWidths
= false;
251 updateVisibleRolesSizes();
254 onVisibleRolesChanged(roles
, previousRoles
);
257 QList
<QByteArray
> KItemListView::visibleRoles() const
259 return m_visibleRoles
;
262 void KItemListView::setAutoScroll(bool enabled
)
264 if (enabled
&& !m_autoScrollTimer
) {
265 m_autoScrollTimer
= new QTimer(this);
266 m_autoScrollTimer
->setSingleShot(false);
267 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
268 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
269 } else if (!enabled
&& m_autoScrollTimer
) {
270 delete m_autoScrollTimer
;
271 m_autoScrollTimer
= 0;
276 bool KItemListView::autoScroll() const
278 return m_autoScrollTimer
!= 0;
281 void KItemListView::setEnabledSelectionToggles(bool enabled
)
283 if (m_enabledSelectionToggles
!= enabled
) {
284 m_enabledSelectionToggles
= enabled
;
286 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
287 while (it
.hasNext()) {
289 it
.value()->setEnabledSelectionToggle(enabled
);
294 bool KItemListView::enabledSelectionToggles() const
296 return m_enabledSelectionToggles
;
299 KItemListController
* KItemListView::controller() const
304 KItemModelBase
* KItemListView::model() const
309 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
311 m_widgetCreator
= widgetCreator
;
314 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
316 return m_widgetCreator
;
319 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
321 m_groupHeaderCreator
= groupHeaderCreator
;
324 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
326 return m_groupHeaderCreator
;
329 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
331 const KItemListStyleOption previousOption
= m_styleOption
;
332 m_styleOption
= option
;
334 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
335 while (it
.hasNext()) {
337 it
.value()->setStyleOption(option
);
340 m_sizeHintResolver
->clearCache();
342 onStyleOptionChanged(option
, previousOption
);
345 const KItemListStyleOption
& KItemListView::styleOption() const
347 return m_styleOption
;
350 void KItemListView::setGeometry(const QRectF
& rect
)
352 QGraphicsWidget::setGeometry(rect
);
358 if (m_model
->count() > 0) {
359 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
361 m_layouter
->setSize(rect
.size());
364 if (!m_layoutTimer
->isActive()) {
365 m_layoutTimer
->start();
368 // Changing the geometry does not require to do an expensive
369 // update of the visible-roles sizes, only the stretched sizes
370 // need to be adjusted to the new size.
371 updateStretchedVisibleRolesSizes();
374 int KItemListView::itemAt(const QPointF
& pos
) const
376 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
377 while (it
.hasNext()) {
380 const KItemListWidget
* widget
= it
.value();
381 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
382 if (widget
->contains(mappedPos
)) {
390 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
392 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
394 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
395 if (!selectionToggleRect
.isEmpty()) {
396 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
397 return selectionToggleRect
.contains(mappedPos
);
403 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
405 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
407 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
408 if (!expansionToggleRect
.isEmpty()) {
409 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
410 return expansionToggleRect
.contains(mappedPos
);
416 int KItemListView::firstVisibleIndex() const
418 return m_layouter
->firstVisibleIndex();
421 int KItemListView::lastVisibleIndex() const
423 return m_layouter
->lastVisibleIndex();
426 QSizeF
KItemListView::itemSizeHint(int index
) const
432 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
434 Q_UNUSED(itemRanges
);
435 return QHash
<QByteArray
, QSizeF
>();
438 bool KItemListView::supportsItemExpanding() const
443 QRectF
KItemListView::itemRect(int index
) const
445 return m_layouter
->itemRect(index
);
448 QRectF
KItemListView::itemContextRect(int index
) const
452 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
454 contextRect
= widget
->iconRect() | widget
->textRect();
455 contextRect
.translate(itemRect(index
).topLeft());
461 void KItemListView::scrollToItem(int index
)
463 QRectF viewGeometry
= geometry();
465 const qreal headerHeight
= m_header
->size().height();
466 viewGeometry
.adjust(0, headerHeight
, 0, 0);
468 const QRectF currentRect
= itemRect(index
);
470 if (!viewGeometry
.contains(currentRect
)) {
471 qreal newOffset
= scrollOffset();
472 if (currentRect
.top() < viewGeometry
.top()) {
473 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
474 newOffset
+= currentRect
.top() - viewGeometry
.top();
475 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
476 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
477 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
478 } else if (currentRect
.left() < viewGeometry
.left()) {
479 if (scrollOrientation() == Qt::Horizontal
) {
480 newOffset
+= currentRect
.left() - viewGeometry
.left();
482 } else if ((currentRect
.right() > viewGeometry
.right())) {
483 if (scrollOrientation() == Qt::Horizontal
) {
484 newOffset
+= currentRect
.right() - viewGeometry
.right();
488 if (newOffset
!= scrollOffset()) {
489 emit
scrollTo(newOffset
);
494 void KItemListView::beginTransaction()
496 ++m_activeTransactions
;
497 if (m_activeTransactions
== 1) {
498 onTransactionBegin();
502 void KItemListView::endTransaction()
504 --m_activeTransactions
;
505 if (m_activeTransactions
< 0) {
506 m_activeTransactions
= 0;
507 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
510 if (m_activeTransactions
== 0) {
516 bool KItemListView::isTransactionActive() const
518 return m_activeTransactions
> 0;
522 void KItemListView::setHeaderShown(bool show
)
525 if (show
&& !m_header
) {
526 m_header
= new KItemListHeader(this);
527 m_header
->setPos(0, 0);
528 m_header
->setModel(m_model
);
529 m_header
->setVisibleRoles(m_visibleRoles
);
530 m_header
->setVisibleRolesWidths(headerRolesWidths());
531 m_header
->setZValue(1);
533 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
534 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
535 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
536 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
537 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
538 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
540 m_useHeaderWidths
= false;
542 m_layouter
->setHeaderHeight(m_header
->size().height());
543 } else if (!show
&& m_header
) {
546 m_useHeaderWidths
= false;
547 m_layouter
->setHeaderHeight(0);
551 bool KItemListView::isHeaderShown() const
553 return m_header
!= 0;
556 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
562 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
564 QGraphicsWidget::paint(painter
, option
, widget
);
566 if (m_rubberBand
->isActive()) {
567 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
568 m_rubberBand
->endPosition()).normalized();
570 const QPointF topLeft
= rubberBandRect
.topLeft();
571 if (scrollOrientation() == Qt::Vertical
) {
572 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
574 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
577 QStyleOptionRubberBand opt
;
578 opt
.initFrom(widget
);
579 opt
.shape
= QRubberBand::Rectangle
;
581 opt
.rect
= rubberBandRect
.toRect();
582 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
586 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
591 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
593 Q_UNUSED(changedRoles
);
597 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
603 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
609 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
615 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
621 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
627 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
633 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
639 void KItemListView::onTransactionBegin()
643 void KItemListView::onTransactionEnd()
647 bool KItemListView::event(QEvent
* event
)
649 // Forward all events to the controller and handle them there
650 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
654 return QGraphicsWidget::event(event
);
657 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
659 m_mousePos
= transform().map(event
->pos());
663 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
665 QGraphicsWidget::mouseMoveEvent(event
);
667 m_mousePos
= transform().map(event
->pos());
668 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
669 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
673 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
675 event
->setAccepted(true);
679 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
681 QGraphicsWidget::dragMoveEvent(event
);
683 m_mousePos
= transform().map(event
->pos());
684 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
685 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
689 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
691 QGraphicsWidget::dragLeaveEvent(event
);
692 setAutoScroll(false);
695 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
697 QGraphicsWidget::dropEvent(event
);
698 setAutoScroll(false);
701 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
703 return m_visibleItems
.values();
706 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
708 QGraphicsWidget::resizeEvent(event
);
709 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
710 QSizeF dynamicItemSize
= m_layouter
->itemSize();
711 const QSizeF newSize
= event
->newSize();
713 if (m_itemSize
.width() < 0) {
714 const qreal requiredWidth
= visibleRolesSizesWidthSum();
715 if (newSize
.width() > requiredWidth
) {
716 dynamicItemSize
.setWidth(newSize
.width());
718 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
719 m_header
->resize(headerWidth
, m_header
->size().height());
722 if (m_itemSize
.height() < 0) {
723 const qreal requiredHeight
= visibleRolesSizesHeightSum();
724 if (newSize
.height() > requiredHeight
) {
725 dynamicItemSize
.setHeight(newSize
.height());
727 // TODO: KItemListHeader is not prepared for vertical alignment
730 m_layouter
->setItemSize(dynamicItemSize
);
734 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
736 updateVisibleRolesSizes(itemRanges
);
738 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
739 if (hasMultipleRanges
) {
743 int previouslyInsertedCount
= 0;
744 foreach (const KItemRange
& range
, itemRanges
) {
745 // range.index is related to the model before anything has been inserted.
746 // As in each loop the current item-range gets inserted the index must
747 // be increased by the already previously inserted items.
748 const int index
= range
.index
+ previouslyInsertedCount
;
749 const int count
= range
.count
;
750 if (index
< 0 || count
<= 0) {
751 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
754 previouslyInsertedCount
+= count
;
756 m_sizeHintResolver
->itemsInserted(index
, count
);
758 // Determine which visible items must be moved
759 QList
<int> itemsToMove
;
760 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
761 while (it
.hasNext()) {
763 const int visibleItemIndex
= it
.key();
764 if (visibleItemIndex
>= index
) {
765 itemsToMove
.append(visibleItemIndex
);
769 // Update the indexes of all KItemListWidget instances that are located
770 // after the inserted items. It is important to adjust the indexes in the order
771 // from the highest index to the lowest index to prevent overlaps when setting the new index.
773 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
774 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
776 setWidgetIndex(widget
, widget
->index() + count
);
779 m_layouter
->markAsDirty();
780 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
781 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
782 QSizeF layouterSize
= m_layouter
->size();
783 if (scrollOrientation() == Qt::Vertical
) {
784 layouterSize
.rwidth() -= scrollBarExtent
;
786 layouterSize
.rheight() -= scrollBarExtent
;
788 m_layouter
->setSize(layouterSize
);
791 if (!hasMultipleRanges
) {
792 doLayout(Animation
, index
, count
);
797 m_controller
->selectionManager()->itemsInserted(itemRanges
);
800 if (hasMultipleRanges
) {
805 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
807 updateVisibleRolesSizes();
809 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
810 if (hasMultipleRanges
) {
814 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
815 const KItemRange
& range
= itemRanges
.at(i
);
816 const int index
= range
.index
;
817 const int count
= range
.count
;
818 if (index
< 0 || count
<= 0) {
819 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
823 m_sizeHintResolver
->itemsRemoved(index
, count
);
825 const int firstRemovedIndex
= index
;
826 const int lastRemovedIndex
= index
+ count
- 1;
827 const int lastIndex
= m_model
->count() + count
- 1;
829 // Remove all KItemListWidget instances that got deleted
830 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
831 KItemListWidget
* widget
= m_visibleItems
.value(i
);
836 m_animation
->stop(widget
);
837 // Stopping the animation might lead to recycling the widget if
838 // it is invisible (see slotAnimationFinished()).
839 // Check again whether it is still visible:
840 if (!m_visibleItems
.contains(i
)) {
844 if (m_model
->count() == 0) {
845 // For performance reasons no animation is done when all items have
847 recycleWidget(widget
);
849 // Animate the removing of the items. Special case: When removing an item there
850 // is no valid model index available anymore. For the
851 // remove-animation the item gets removed from m_visibleItems but the widget
852 // will stay alive until the animation has been finished and will
853 // be recycled (deleted) in KItemListView::slotAnimationFinished().
854 m_visibleItems
.remove(i
);
855 widget
->setIndex(-1);
856 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
860 // Update the indexes of all KItemListWidget instances that are located
861 // after the deleted items
862 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
863 KItemListWidget
* widget
= m_visibleItems
.value(i
);
865 const int newIndex
= i
- count
;
866 setWidgetIndex(widget
, newIndex
);
870 m_layouter
->markAsDirty();
871 if (!hasMultipleRanges
) {
872 doLayout(Animation
, index
, -count
);
877 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
880 if (hasMultipleRanges
) {
885 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
887 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
888 m_layouter
->markAsDirty();
891 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
894 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
895 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
897 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
898 KItemListWidget
* widget
= m_visibleItems
.value(index
);
900 updateWidgetProperties(widget
, index
);
902 updateGroupHeaderForWidget(widget
);
904 initializeItemListWidget(widget
);
908 doLayout(NoAnimation
);
911 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
912 const QSet
<QByteArray
>& roles
)
914 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
915 if (updateSizeHints
) {
916 updateVisibleRolesSizes(itemRanges
);
919 foreach (const KItemRange
& itemRange
, itemRanges
) {
920 const int index
= itemRange
.index
;
921 const int count
= itemRange
.count
;
923 if (updateSizeHints
) {
924 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
925 m_layouter
->markAsDirty();
927 if (!m_layoutTimer
->isActive()) {
928 m_layoutTimer
->start();
932 // Apply the changed roles to the visible item-widgets
933 const int lastIndex
= index
+ count
- 1;
934 for (int i
= index
; i
<= lastIndex
; ++i
) {
935 KItemListWidget
* widget
= m_visibleItems
.value(i
);
937 widget
->setData(m_model
->data(i
), roles
);
941 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
942 // The sort-role has been changed which might result
943 // in modified group headers
944 updateVisibleGroupHeaders();
945 doLayout(NoAnimation
);
950 void KItemListView::slotGroupedSortingChanged(bool current
)
953 m_layouter
->markAsDirty();
956 // Apply the height of the header to the layouter
957 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
958 m_styleOption
.margin
* 2;
959 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
961 updateVisibleGroupHeaders();
963 // Clear all visible headers
964 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
965 while (it
.hasNext()) {
967 recycleGroupHeaderForWidget(it
.key());
969 Q_ASSERT(m_visibleGroups
.isEmpty());
975 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
980 updateVisibleGroupHeaders();
985 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
990 updateVisibleGroupHeaders();
995 void KItemListView::slotCurrentChanged(int current
, int previous
)
999 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1000 if (previousWidget
) {
1001 Q_ASSERT(previousWidget
->isCurrent());
1002 previousWidget
->setCurrent(false);
1005 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1006 if (currentWidget
) {
1007 Q_ASSERT(!currentWidget
->isCurrent());
1008 currentWidget
->setCurrent(true);
1012 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1016 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1017 while (it
.hasNext()) {
1019 const int index
= it
.key();
1020 KItemListWidget
* widget
= it
.value();
1021 widget
->setSelected(current
.contains(index
));
1025 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1026 KItemListViewAnimation::AnimationType type
)
1028 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1029 Q_ASSERT(itemListWidget
);
1032 case KItemListViewAnimation::DeleteAnimation
: {
1033 // As we recycle the widget in this case it is important to assure that no
1034 // other animation has been started. This is a convention in KItemListView and
1035 // not a requirement defined by KItemListViewAnimation.
1036 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1038 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1039 // by m_visibleWidgets and must be deleted manually after the animation has
1041 recycleGroupHeaderForWidget(itemListWidget
);
1042 m_widgetCreator
->recycle(itemListWidget
);
1046 case KItemListViewAnimation::CreateAnimation
:
1047 case KItemListViewAnimation::MovingAnimation
:
1048 case KItemListViewAnimation::ResizeAnimation
: {
1049 const int index
= itemListWidget
->index();
1050 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1051 (index
> m_layouter
->lastVisibleIndex());
1052 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1053 recycleWidget(itemListWidget
);
1062 void KItemListView::slotLayoutTimerFinished()
1064 m_layouter
->setSize(geometry().size());
1065 doLayout(Animation
);
1068 void KItemListView::slotRubberBandPosChanged()
1073 void KItemListView::slotRubberBandActivationChanged(bool active
)
1076 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1077 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1078 m_skipAutoScrollForRubberBand
= true;
1080 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1081 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1082 m_skipAutoScrollForRubberBand
= false;
1088 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1090 qreal previousWidth
)
1092 Q_UNUSED(previousWidth
);
1094 m_useHeaderWidths
= true;
1096 if (m_visibleRolesSizes
.contains(role
)) {
1097 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1098 roleSize
.setWidth(currentWidth
);
1099 m_visibleRolesSizes
.insert(role
, roleSize
);
1100 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1102 // Apply the new size to the layouter
1103 QSizeF dynamicItemSize
= m_itemSize
;
1104 if (dynamicItemSize
.width() < 0) {
1105 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1106 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1108 if (dynamicItemSize
.height() < 0) {
1109 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1110 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1113 m_layouter
->setItemSize(dynamicItemSize
);
1115 // Update the role sizes for all visible widgets
1116 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1117 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1120 doLayout(Animation
);
1124 void KItemListView::triggerAutoScrolling()
1126 if (!m_autoScrollTimer
) {
1131 int visibleSize
= 0;
1132 if (scrollOrientation() == Qt::Vertical
) {
1133 pos
= m_mousePos
.y();
1134 visibleSize
= size().height();
1136 pos
= m_mousePos
.x();
1137 visibleSize
= size().width();
1140 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1141 m_autoScrollIncrement
= 0;
1144 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1145 if (m_autoScrollIncrement
== 0) {
1146 // The mouse position is not above an autoscroll margin (the autoscroll timer
1147 // will be restarted in mouseMoveEvent())
1148 m_autoScrollTimer
->stop();
1152 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1153 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1154 // if the direction of the rubberband is similar to the autoscroll direction. This
1155 // prevents that starting to create a rubberband within the autoscroll margins starts
1156 // an autoscrolling.
1158 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1159 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1160 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1161 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1162 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1163 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1164 // been moved up although the autoscroll direction might be down)
1165 m_autoScrollTimer
->stop();
1170 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1171 // the autoscrolling may not get skipped anymore until a new rubberband is created
1172 m_skipAutoScrollForRubberBand
= false;
1174 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1175 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1176 setScrollOffset(newScrollOffset
);
1178 // Trigger the autoscroll timer which will periodically call
1179 // triggerAutoScrolling()
1180 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1183 void KItemListView::setController(KItemListController
* controller
)
1185 if (m_controller
!= controller
) {
1186 KItemListController
* previous
= m_controller
;
1188 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1189 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1190 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1193 m_controller
= controller
;
1196 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1197 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1198 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1201 onControllerChanged(controller
, previous
);
1205 void KItemListView::setModel(KItemModelBase
* model
)
1207 if (m_model
== model
) {
1211 KItemModelBase
* previous
= m_model
;
1214 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1215 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1216 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1217 this, SLOT(slotItemsInserted(KItemRangeList
)));
1218 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1219 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1220 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1221 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1222 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1223 this, SLOT(slotGroupedSortingChanged(bool)));
1224 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1225 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1226 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1227 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1231 m_layouter
->setModel(model
);
1232 m_grouped
= model
->groupedSorting();
1235 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1236 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1237 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1238 this, SLOT(slotItemsInserted(KItemRangeList
)));
1239 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1240 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1241 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1242 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1243 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1244 this, SLOT(slotGroupedSortingChanged(bool)));
1245 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1246 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1247 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1248 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1251 onModelChanged(model
, previous
);
1254 KItemListRubberBand
* KItemListView::rubberBand() const
1256 return m_rubberBand
;
1259 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1261 if (m_layoutTimer
->isActive()) {
1262 m_layoutTimer
->stop();
1265 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1269 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1270 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1271 if (firstVisibleIndex
< 0) {
1272 emitOffsetChanges();
1276 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1277 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1278 // is still shown if the maximum offset got decreased.
1279 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1280 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1281 if (scrollOffset() > maxOffsetToShowFullRange
) {
1282 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1285 // Determine all items that are completely invisible and might be
1286 // reused for items that just got (at least partly) visible.
1287 // Items that do e.g. an animated moving of their position are not
1288 // marked as invisible: This assures that a scrolling inside the view
1289 // can be done without breaking an animation.
1290 QList
<int> reusableItems
;
1291 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1292 while (it
.hasNext()) {
1294 KItemListWidget
* widget
= it
.value();
1295 const int index
= widget
->index();
1296 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1297 if (invisible
&& !m_animation
->isStarted(widget
)) {
1298 widget
->setVisible(false);
1299 reusableItems
.append(index
);
1302 recycleGroupHeaderForWidget(widget
);
1307 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1308 // instances from invisible items are reused. If no reusable items are
1309 // found then new KItemListWidget instances get created.
1310 const bool animate
= (hint
== Animation
);
1311 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1312 bool applyNewPos
= true;
1313 bool wasHidden
= false;
1315 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1316 const QPointF newPos
= itemBounds
.topLeft();
1317 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1320 if (!reusableItems
.isEmpty()) {
1321 // Reuse a KItemListWidget instance from an invisible item
1322 const int oldIndex
= reusableItems
.takeLast();
1323 widget
= m_visibleItems
.value(oldIndex
);
1324 setWidgetIndex(widget
, i
);
1327 updateGroupHeaderForWidget(widget
);
1330 // No reusable KItemListWidget instance is available, create a new one
1331 widget
= createWidget(i
);
1333 widget
->resize(itemBounds
.size());
1335 if (animate
&& changedCount
< 0) {
1336 // Items have been deleted, move the created item to the
1337 // imaginary old position. They will get animated to the new position
1339 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1340 if (itemRect
.isEmpty()) {
1341 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1342 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1343 widget
->setPos(invisibleOldPos
);
1345 widget
->setPos(itemRect
.topLeft());
1347 applyNewPos
= false;
1349 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1350 applyNewPos
= false;
1354 const bool itemsRemoved
= (changedCount
< 0);
1355 const bool itemsInserted
= (changedCount
> 0);
1356 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1357 // The item is located after the removed items. Animate the moving of the position.
1358 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1359 applyNewPos
= false;
1360 } else if (itemsInserted
&& i
>= changedIndex
) {
1361 // The item is located after the first inserted item
1362 if (i
<= changedIndex
+ changedCount
- 1) {
1363 // The item is an inserted item. Animate the appearing of the item.
1364 // For performance reasons no animation is done when changedCount is equal
1365 // to all available items.
1366 if (changedCount
< m_model
->count()) {
1367 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1369 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1370 // The item was already there before, so animate the moving of the position.
1371 // No moving animation is done if the item is animated by a create animation: This
1372 // prevents a "move animation mess" when inserting several ranges in parallel.
1373 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1374 applyNewPos
= false;
1376 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1377 // The size of the view might have been changed. Animate the moving of the position.
1378 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1379 applyNewPos
= false;
1384 widget
->setPos(newPos
);
1387 Q_ASSERT(widget
->index() == i
);
1388 widget
->setVisible(true);
1390 if (widget
->size() != itemBounds
.size()) {
1391 // Resize the widget for the item to the changed size.
1393 // If a dynamic item size is used then no animation is done in the direction
1394 // of the dynamic size.
1395 if (m_itemSize
.width() <= 0) {
1396 // The width is dynamic, apply the new width without animation.
1397 widget
->resize(itemBounds
.width(), widget
->size().height());
1398 } else if (m_itemSize
.height() <= 0) {
1399 // The height is dynamic, apply the new height without animation.
1400 widget
->resize(widget
->size().width(), itemBounds
.height());
1402 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1404 widget
->resize(itemBounds
.size());
1409 // Delete invisible KItemListWidget instances that have not been reused
1410 foreach (int index
, reusableItems
) {
1411 recycleWidget(m_visibleItems
.value(index
));
1415 // Update the layout of all visible group headers
1416 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1417 while (it
.hasNext()) {
1419 updateGroupHeaderLayout(it
.key());
1423 emitOffsetChanges();
1426 void KItemListView::emitOffsetChanges()
1428 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1429 if (m_oldScrollOffset
!= newScrollOffset
) {
1430 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1431 m_oldScrollOffset
= newScrollOffset
;
1434 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1435 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1436 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1437 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1440 const qreal newItemOffset
= m_layouter
->itemOffset();
1441 if (m_oldItemOffset
!= newItemOffset
) {
1442 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1443 m_oldItemOffset
= newItemOffset
;
1446 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1447 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1448 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1449 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1453 KItemListWidget
* KItemListView::createWidget(int index
)
1455 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1456 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1458 updateWidgetProperties(widget
, index
);
1459 m_visibleItems
.insert(index
, widget
);
1462 updateGroupHeaderForWidget(widget
);
1465 initializeItemListWidget(widget
);
1469 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1472 recycleGroupHeaderForWidget(widget
);
1475 m_visibleItems
.remove(widget
->index());
1476 m_widgetCreator
->recycle(widget
);
1479 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1481 const int oldIndex
= widget
->index();
1482 m_visibleItems
.remove(oldIndex
);
1483 updateWidgetProperties(widget
, index
);
1484 m_visibleItems
.insert(index
, widget
);
1486 initializeItemListWidget(widget
);
1489 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1491 // Calculate the first visible index and last visible index for the current size
1492 const int currentFirst
= m_layouter
->firstVisibleIndex();
1493 const int currentLast
= m_layouter
->lastVisibleIndex();
1495 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1497 // Calculate the first visible index and last visible index for the new size
1498 setLayouterSize(size
, sizeType
);
1499 const int newFirst
= m_layouter
->firstVisibleIndex();
1500 const int newLast
= m_layouter
->lastVisibleIndex();
1502 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1503 // At least one index has been changed. Assure that widgets for all possible
1504 // visible items get created so that a move-animation can be started later.
1505 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1506 int minFirst
= qMin(newFirst
, currentFirst
);
1507 const int maxLast
= qMax(newLast
, currentLast
);
1509 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1510 // Increasing the size might result in a smaller KItemListView::offset().
1511 // Decrease the first visible index in a way that at least the maximum
1512 // visible items are shown.
1513 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1516 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1517 // The creating of widgets is quite expensive. Assure that never more
1518 // than 50 % of the maximum visible items get created for the animations.
1522 setLayouterSize(currentSize
, sizeType
);
1523 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1524 if (!m_visibleItems
.contains(i
)) {
1525 KItemListWidget
* widget
= createWidget(i
);
1526 const QRectF itemRect
= m_layouter
->itemRect(i
);
1527 widget
->setPos(itemRect
.topLeft());
1528 widget
->resize(itemRect
.size());
1531 setLayouterSize(size
, sizeType
);
1535 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1538 case LayouterSize
: m_layouter
->setSize(size
); break;
1539 case ItemSize
: m_layouter
->setItemSize(size
); break;
1544 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1546 widget
->setVisibleRoles(m_visibleRoles
);
1547 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1548 widget
->setStyleOption(m_styleOption
);
1550 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1551 widget
->setCurrent(index
== selectionManager
->currentItem());
1552 widget
->setSelected(selectionManager
->isSelected(index
));
1553 widget
->setHovered(false);
1554 widget
->setAlternatingBackgroundColors(false);
1555 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1556 widget
->setIndex(index
);
1557 widget
->setData(m_model
->data(index
));
1560 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1562 Q_ASSERT(m_grouped
);
1564 const int index
= widget
->index();
1565 if (!m_layouter
->isFirstGroupItem(index
)) {
1566 // The widget does not represent the first item of a group
1567 // and hence requires no header
1568 recycleGroupHeaderForWidget(widget
);
1572 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1573 if (groups
.isEmpty()) {
1577 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1579 header
= m_groupHeaderCreator
->create(this);
1580 header
->setParentItem(widget
);
1581 m_visibleGroups
.insert(widget
, header
);
1583 Q_ASSERT(header
->parentItem() == widget
);
1585 // Determine the shown data for the header by doing a binary
1586 // search in the groups-list
1588 int max
= groups
.count() - 1;
1591 mid
= (min
+ max
) / 2;
1592 if (index
> groups
.at(mid
).first
) {
1597 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1599 header
->setData(groups
.at(mid
).second
);
1600 header
->setRole(model()->sortRole());
1601 header
->setStyleOption(m_styleOption
);
1602 header
->setScrollOrientation(scrollOrientation());
1607 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1609 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1612 const int index
= widget
->index();
1613 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1614 const QRectF itemRect
= m_layouter
->itemRect(index
);
1616 // The group-header is a child of the itemlist widget. Translate the
1617 // group header position to the relative position.
1618 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1619 - groupHeaderRect
.height());
1620 header
->setPos(groupHeaderPos
);
1621 header
->resize(groupHeaderRect
.size());
1624 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1626 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1628 header
->setParentItem(0);
1629 m_groupHeaderCreator
->recycle(header
);
1630 m_visibleGroups
.remove(widget
);
1634 void KItemListView::updateVisibleGroupHeaders()
1636 Q_ASSERT(m_grouped
);
1637 m_layouter
->markAsDirty();
1639 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1640 while (it
.hasNext()) {
1642 updateGroupHeaderForWidget(it
.value());
1646 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1648 QHash
<QByteArray
, qreal
> rolesWidths
;
1650 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1651 while (it
.hasNext()) {
1653 rolesWidths
.insert(it
.key(), it
.value().width());
1659 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1661 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1665 const int itemCount
= m_model
->count();
1666 int rangesItemCount
= 0;
1667 foreach (const KItemRange
& range
, itemRanges
) {
1668 rangesItemCount
+= range
.count
;
1671 if (itemCount
== rangesItemCount
) {
1672 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1674 // Assure the the sizes are not smaller than the minimum defined by the header
1675 // TODO: Currently only implemented for a top-aligned header
1676 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1677 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1678 while (it
.hasNext()) {
1680 const QSizeF
& size
= it
.value();
1681 if (size
.width() < minHeaderRoleWidth
) {
1682 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1683 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1688 // Only a sub range of the roles need to be determined.
1689 // The chances are good that the sizes of the sub ranges
1690 // already fit into the available sizes and hence no
1691 // expensive update might be required.
1692 bool updateRequired
= false;
1694 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1695 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1696 while (it
.hasNext()) {
1698 const QByteArray
& role
= it
.key();
1699 const QSizeF
& updatedSize
= it
.value();
1700 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1701 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1702 m_visibleRolesSizes
.insert(role
, updatedSize
);
1703 updateRequired
= true;
1707 if (!updateRequired
) {
1708 // All the updated sizes are smaller than the current sizes and no change
1709 // of the stretched roles-widths is required
1714 updateStretchedVisibleRolesSizes();
1717 void KItemListView::updateVisibleRolesSizes()
1723 const int itemCount
= m_model
->count();
1724 if (itemCount
> 0) {
1725 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1729 void KItemListView::updateStretchedVisibleRolesSizes()
1731 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1735 // Calculate the maximum size of an item by considering the
1736 // visible role sizes and apply them to the layouter. If the
1737 // size does not use the available view-size it the size of the
1738 // first role will get stretched.
1739 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1740 const QByteArray role
= m_visibleRoles
.first();
1741 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1743 QSizeF dynamicItemSize
= m_itemSize
;
1745 if (dynamicItemSize
.width() <= 0) {
1746 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1747 const qreal availableWidth
= size().width();
1748 if (requiredWidth
< availableWidth
) {
1749 // Stretch the first role to use the whole width for the item
1750 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1751 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1753 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1756 if (dynamicItemSize
.height() <= 0) {
1757 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1758 const qreal availableHeight
= size().height();
1759 if (requiredHeight
< availableHeight
) {
1760 // Stretch the first role to use the whole height for the item
1761 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1762 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1764 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1767 m_layouter
->setItemSize(dynamicItemSize
);
1770 m_header
->setVisibleRolesWidths(headerRolesWidths());
1771 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1774 // Update the role sizes for all visible widgets
1775 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1776 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1780 qreal
KItemListView::visibleRolesSizesWidthSum() const
1783 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1784 while (it
.hasNext()) {
1786 widthSum
+= it
.value().width();
1791 qreal
KItemListView::visibleRolesSizesHeightSum() const
1793 qreal heightSum
= 0;
1794 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1795 while (it
.hasNext()) {
1797 heightSum
+= it
.value().height();
1802 QRectF
KItemListView::headerBoundaries() const
1804 return m_header
? m_header
->geometry() : QRectF();
1807 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1811 const int minSpeed
= 4;
1812 const int maxSpeed
= 128;
1813 const int speedLimiter
= 96;
1814 const int autoScrollBorder
= 64;
1816 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1817 // This assures that the autoscrolling speed grows gradually.
1818 const int incLimiter
= 1;
1820 if (pos
< autoScrollBorder
) {
1821 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1822 inc
= qMax(inc
, -maxSpeed
);
1823 inc
= qMax(inc
, oldInc
- incLimiter
);
1824 } else if (pos
> range
- autoScrollBorder
) {
1825 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1826 inc
= qMin(inc
, maxSpeed
);
1827 inc
= qMin(inc
, oldInc
+ incLimiter
);
1835 KItemListCreatorBase::~KItemListCreatorBase()
1837 qDeleteAll(m_recycleableWidgets
);
1838 qDeleteAll(m_createdWidgets
);
1841 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1843 m_createdWidgets
.insert(widget
);
1846 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1848 Q_ASSERT(m_createdWidgets
.contains(widget
));
1849 m_createdWidgets
.remove(widget
);
1851 if (m_recycleableWidgets
.count() < 100) {
1852 m_recycleableWidgets
.append(widget
);
1853 widget
->setVisible(false);
1859 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1861 if (m_recycleableWidgets
.isEmpty()) {
1865 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1866 m_createdWidgets
.insert(widget
);
1870 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1874 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1876 widget
->setParentItem(0);
1877 widget
->setOpacity(1.0);
1878 pushRecycleableWidget(widget
);
1881 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1885 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1887 header
->setOpacity(1.0);
1888 pushRecycleableWidget(header
);
1891 #include "kitemlistview.moc"