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 if (!m_enabledSelectionToggles
) {
396 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
398 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
399 if (!selectionToggleRect
.isEmpty()) {
400 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
401 return selectionToggleRect
.contains(mappedPos
);
407 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
409 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
411 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
412 if (!expansionToggleRect
.isEmpty()) {
413 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
414 return expansionToggleRect
.contains(mappedPos
);
420 int KItemListView::firstVisibleIndex() const
422 return m_layouter
->firstVisibleIndex();
425 int KItemListView::lastVisibleIndex() const
427 return m_layouter
->lastVisibleIndex();
430 QSizeF
KItemListView::itemSizeHint(int index
) const
436 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
438 Q_UNUSED(itemRanges
);
439 return QHash
<QByteArray
, QSizeF
>();
442 bool KItemListView::supportsItemExpanding() const
447 QRectF
KItemListView::itemRect(int index
) const
449 return m_layouter
->itemRect(index
);
452 QRectF
KItemListView::itemContextRect(int index
) const
456 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
458 contextRect
= widget
->iconRect() | widget
->textRect();
459 contextRect
.translate(itemRect(index
).topLeft());
465 void KItemListView::scrollToItem(int index
)
467 QRectF viewGeometry
= geometry();
469 const qreal headerHeight
= m_header
->size().height();
470 viewGeometry
.adjust(0, headerHeight
, 0, 0);
472 const QRectF currentRect
= itemRect(index
);
474 if (!viewGeometry
.contains(currentRect
)) {
475 qreal newOffset
= scrollOffset();
476 if (currentRect
.top() < viewGeometry
.top()) {
477 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
478 newOffset
+= currentRect
.top() - viewGeometry
.top();
479 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
480 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
481 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
482 } else if (currentRect
.left() < viewGeometry
.left()) {
483 if (scrollOrientation() == Qt::Horizontal
) {
484 newOffset
+= currentRect
.left() - viewGeometry
.left();
486 } else if ((currentRect
.right() > viewGeometry
.right())) {
487 if (scrollOrientation() == Qt::Horizontal
) {
488 newOffset
+= currentRect
.right() - viewGeometry
.right();
492 if (newOffset
!= scrollOffset()) {
493 emit
scrollTo(newOffset
);
498 void KItemListView::beginTransaction()
500 ++m_activeTransactions
;
501 if (m_activeTransactions
== 1) {
502 onTransactionBegin();
506 void KItemListView::endTransaction()
508 --m_activeTransactions
;
509 if (m_activeTransactions
< 0) {
510 m_activeTransactions
= 0;
511 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
514 if (m_activeTransactions
== 0) {
520 bool KItemListView::isTransactionActive() const
522 return m_activeTransactions
> 0;
526 void KItemListView::setHeaderShown(bool show
)
529 if (show
&& !m_header
) {
530 m_header
= new KItemListHeader(this);
531 m_header
->setPos(0, 0);
532 m_header
->setModel(m_model
);
533 m_header
->setVisibleRoles(m_visibleRoles
);
534 m_header
->setVisibleRolesWidths(headerRolesWidths());
535 m_header
->setZValue(1);
537 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
538 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
539 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
540 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
541 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
542 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
544 m_useHeaderWidths
= false;
546 m_layouter
->setHeaderHeight(m_header
->size().height());
547 } else if (!show
&& m_header
) {
550 m_useHeaderWidths
= false;
551 m_layouter
->setHeaderHeight(0);
555 bool KItemListView::isHeaderShown() const
557 return m_header
!= 0;
560 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
566 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
568 QGraphicsWidget::paint(painter
, option
, widget
);
570 if (m_rubberBand
->isActive()) {
571 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
572 m_rubberBand
->endPosition()).normalized();
574 const QPointF topLeft
= rubberBandRect
.topLeft();
575 if (scrollOrientation() == Qt::Vertical
) {
576 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
578 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
581 QStyleOptionRubberBand opt
;
582 opt
.initFrom(widget
);
583 opt
.shape
= QRubberBand::Rectangle
;
585 opt
.rect
= rubberBandRect
.toRect();
586 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
590 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
595 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
597 Q_UNUSED(changedRoles
);
601 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
607 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
613 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
619 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
625 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
631 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
637 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
643 void KItemListView::onTransactionBegin()
647 void KItemListView::onTransactionEnd()
651 bool KItemListView::event(QEvent
* event
)
653 // Forward all events to the controller and handle them there
654 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
658 return QGraphicsWidget::event(event
);
661 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
663 m_mousePos
= transform().map(event
->pos());
667 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
669 QGraphicsWidget::mouseMoveEvent(event
);
671 m_mousePos
= transform().map(event
->pos());
672 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
673 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
677 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
679 event
->setAccepted(true);
683 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
685 QGraphicsWidget::dragMoveEvent(event
);
687 m_mousePos
= transform().map(event
->pos());
688 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
689 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
693 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
695 QGraphicsWidget::dragLeaveEvent(event
);
696 setAutoScroll(false);
699 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
701 QGraphicsWidget::dropEvent(event
);
702 setAutoScroll(false);
705 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
707 return m_visibleItems
.values();
710 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
712 QGraphicsWidget::resizeEvent(event
);
713 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
714 QSizeF dynamicItemSize
= m_layouter
->itemSize();
715 const QSizeF newSize
= event
->newSize();
717 if (m_itemSize
.width() < 0) {
718 const qreal requiredWidth
= visibleRolesSizesWidthSum();
719 if (newSize
.width() > requiredWidth
) {
720 dynamicItemSize
.setWidth(newSize
.width());
722 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
723 m_header
->resize(headerWidth
, m_header
->size().height());
726 if (m_itemSize
.height() < 0) {
727 const qreal requiredHeight
= visibleRolesSizesHeightSum();
728 if (newSize
.height() > requiredHeight
) {
729 dynamicItemSize
.setHeight(newSize
.height());
731 // TODO: KItemListHeader is not prepared for vertical alignment
734 m_layouter
->setItemSize(dynamicItemSize
);
738 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
740 updateVisibleRolesSizes(itemRanges
);
742 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
743 if (hasMultipleRanges
) {
747 int previouslyInsertedCount
= 0;
748 foreach (const KItemRange
& range
, itemRanges
) {
749 // range.index is related to the model before anything has been inserted.
750 // As in each loop the current item-range gets inserted the index must
751 // be increased by the already previously inserted items.
752 const int index
= range
.index
+ previouslyInsertedCount
;
753 const int count
= range
.count
;
754 if (index
< 0 || count
<= 0) {
755 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
758 previouslyInsertedCount
+= count
;
760 m_sizeHintResolver
->itemsInserted(index
, count
);
762 // Determine which visible items must be moved
763 QList
<int> itemsToMove
;
764 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
765 while (it
.hasNext()) {
767 const int visibleItemIndex
= it
.key();
768 if (visibleItemIndex
>= index
) {
769 itemsToMove
.append(visibleItemIndex
);
773 // Update the indexes of all KItemListWidget instances that are located
774 // after the inserted items. It is important to adjust the indexes in the order
775 // from the highest index to the lowest index to prevent overlaps when setting the new index.
777 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
778 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
780 setWidgetIndex(widget
, widget
->index() + count
);
783 m_layouter
->markAsDirty();
784 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
785 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
786 QSizeF layouterSize
= m_layouter
->size();
787 if (scrollOrientation() == Qt::Vertical
) {
788 layouterSize
.rwidth() -= scrollBarExtent
;
790 layouterSize
.rheight() -= scrollBarExtent
;
792 m_layouter
->setSize(layouterSize
);
795 if (!hasMultipleRanges
) {
796 doLayout(Animation
, index
, count
);
801 m_controller
->selectionManager()->itemsInserted(itemRanges
);
804 if (hasMultipleRanges
) {
809 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
811 updateVisibleRolesSizes();
813 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
814 if (hasMultipleRanges
) {
818 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
819 const KItemRange
& range
= itemRanges
.at(i
);
820 const int index
= range
.index
;
821 const int count
= range
.count
;
822 if (index
< 0 || count
<= 0) {
823 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
827 m_sizeHintResolver
->itemsRemoved(index
, count
);
829 const int firstRemovedIndex
= index
;
830 const int lastRemovedIndex
= index
+ count
- 1;
831 const int lastIndex
= m_model
->count() + count
- 1;
833 // Remove all KItemListWidget instances that got deleted
834 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
835 KItemListWidget
* widget
= m_visibleItems
.value(i
);
840 m_animation
->stop(widget
);
841 // Stopping the animation might lead to recycling the widget if
842 // it is invisible (see slotAnimationFinished()).
843 // Check again whether it is still visible:
844 if (!m_visibleItems
.contains(i
)) {
848 if (m_model
->count() == 0) {
849 // For performance reasons no animation is done when all items have
851 recycleWidget(widget
);
853 // Animate the removing of the items. Special case: When removing an item there
854 // is no valid model index available anymore. For the
855 // remove-animation the item gets removed from m_visibleItems but the widget
856 // will stay alive until the animation has been finished and will
857 // be recycled (deleted) in KItemListView::slotAnimationFinished().
858 m_visibleItems
.remove(i
);
859 widget
->setIndex(-1);
860 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
864 // Update the indexes of all KItemListWidget instances that are located
865 // after the deleted items
866 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
867 KItemListWidget
* widget
= m_visibleItems
.value(i
);
869 const int newIndex
= i
- count
;
870 setWidgetIndex(widget
, newIndex
);
874 m_layouter
->markAsDirty();
875 if (!hasMultipleRanges
) {
876 doLayout(Animation
, index
, -count
);
881 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
884 if (hasMultipleRanges
) {
889 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
891 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
892 m_layouter
->markAsDirty();
895 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
898 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
899 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
901 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
902 KItemListWidget
* widget
= m_visibleItems
.value(index
);
904 updateWidgetProperties(widget
, index
);
906 updateGroupHeaderForWidget(widget
);
908 initializeItemListWidget(widget
);
912 doLayout(NoAnimation
);
915 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
916 const QSet
<QByteArray
>& roles
)
918 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
919 if (updateSizeHints
) {
920 updateVisibleRolesSizes(itemRanges
);
923 foreach (const KItemRange
& itemRange
, itemRanges
) {
924 const int index
= itemRange
.index
;
925 const int count
= itemRange
.count
;
927 if (updateSizeHints
) {
928 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
929 m_layouter
->markAsDirty();
931 if (!m_layoutTimer
->isActive()) {
932 m_layoutTimer
->start();
936 // Apply the changed roles to the visible item-widgets
937 const int lastIndex
= index
+ count
- 1;
938 for (int i
= index
; i
<= lastIndex
; ++i
) {
939 KItemListWidget
* widget
= m_visibleItems
.value(i
);
941 widget
->setData(m_model
->data(i
), roles
);
945 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
946 // The sort-role has been changed which might result
947 // in modified group headers
948 updateVisibleGroupHeaders();
949 doLayout(NoAnimation
);
954 void KItemListView::slotGroupedSortingChanged(bool current
)
957 m_layouter
->markAsDirty();
960 // Apply the height of the header to the layouter
961 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
962 m_styleOption
.margin
* 2;
963 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
965 updateVisibleGroupHeaders();
967 // Clear all visible headers
968 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
969 while (it
.hasNext()) {
971 recycleGroupHeaderForWidget(it
.key());
973 Q_ASSERT(m_visibleGroups
.isEmpty());
979 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
984 updateVisibleGroupHeaders();
989 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
994 updateVisibleGroupHeaders();
999 void KItemListView::slotCurrentChanged(int current
, int previous
)
1003 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1004 if (previousWidget
) {
1005 Q_ASSERT(previousWidget
->isCurrent());
1006 previousWidget
->setCurrent(false);
1009 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1010 if (currentWidget
) {
1011 Q_ASSERT(!currentWidget
->isCurrent());
1012 currentWidget
->setCurrent(true);
1016 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1020 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1021 while (it
.hasNext()) {
1023 const int index
= it
.key();
1024 KItemListWidget
* widget
= it
.value();
1025 widget
->setSelected(current
.contains(index
));
1029 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1030 KItemListViewAnimation::AnimationType type
)
1032 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1033 Q_ASSERT(itemListWidget
);
1036 case KItemListViewAnimation::DeleteAnimation
: {
1037 // As we recycle the widget in this case it is important to assure that no
1038 // other animation has been started. This is a convention in KItemListView and
1039 // not a requirement defined by KItemListViewAnimation.
1040 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1042 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1043 // by m_visibleWidgets and must be deleted manually after the animation has
1045 recycleGroupHeaderForWidget(itemListWidget
);
1046 m_widgetCreator
->recycle(itemListWidget
);
1050 case KItemListViewAnimation::CreateAnimation
:
1051 case KItemListViewAnimation::MovingAnimation
:
1052 case KItemListViewAnimation::ResizeAnimation
: {
1053 const int index
= itemListWidget
->index();
1054 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1055 (index
> m_layouter
->lastVisibleIndex());
1056 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1057 recycleWidget(itemListWidget
);
1066 void KItemListView::slotLayoutTimerFinished()
1068 m_layouter
->setSize(geometry().size());
1069 doLayout(Animation
);
1072 void KItemListView::slotRubberBandPosChanged()
1077 void KItemListView::slotRubberBandActivationChanged(bool active
)
1080 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1081 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1082 m_skipAutoScrollForRubberBand
= true;
1084 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1085 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1086 m_skipAutoScrollForRubberBand
= false;
1092 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1094 qreal previousWidth
)
1096 Q_UNUSED(previousWidth
);
1098 m_useHeaderWidths
= true;
1100 if (m_visibleRolesSizes
.contains(role
)) {
1101 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1102 roleSize
.setWidth(currentWidth
);
1103 m_visibleRolesSizes
.insert(role
, roleSize
);
1104 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1106 // Apply the new size to the layouter
1107 QSizeF dynamicItemSize
= m_itemSize
;
1108 if (dynamicItemSize
.width() < 0) {
1109 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1110 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1112 if (dynamicItemSize
.height() < 0) {
1113 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1114 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1117 m_layouter
->setItemSize(dynamicItemSize
);
1119 // Update the role sizes for all visible widgets
1120 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1121 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1124 doLayout(Animation
);
1128 void KItemListView::triggerAutoScrolling()
1130 if (!m_autoScrollTimer
) {
1135 int visibleSize
= 0;
1136 if (scrollOrientation() == Qt::Vertical
) {
1137 pos
= m_mousePos
.y();
1138 visibleSize
= size().height();
1140 pos
= m_mousePos
.x();
1141 visibleSize
= size().width();
1144 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1145 m_autoScrollIncrement
= 0;
1148 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1149 if (m_autoScrollIncrement
== 0) {
1150 // The mouse position is not above an autoscroll margin (the autoscroll timer
1151 // will be restarted in mouseMoveEvent())
1152 m_autoScrollTimer
->stop();
1156 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1157 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1158 // if the direction of the rubberband is similar to the autoscroll direction. This
1159 // prevents that starting to create a rubberband within the autoscroll margins starts
1160 // an autoscrolling.
1162 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1163 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1164 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1165 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1166 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1167 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1168 // been moved up although the autoscroll direction might be down)
1169 m_autoScrollTimer
->stop();
1174 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1175 // the autoscrolling may not get skipped anymore until a new rubberband is created
1176 m_skipAutoScrollForRubberBand
= false;
1178 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1179 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1180 setScrollOffset(newScrollOffset
);
1182 // Trigger the autoscroll timer which will periodically call
1183 // triggerAutoScrolling()
1184 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1187 void KItemListView::setController(KItemListController
* controller
)
1189 if (m_controller
!= controller
) {
1190 KItemListController
* previous
= m_controller
;
1192 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1193 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1194 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1197 m_controller
= controller
;
1200 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1201 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1202 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1205 onControllerChanged(controller
, previous
);
1209 void KItemListView::setModel(KItemModelBase
* model
)
1211 if (m_model
== model
) {
1215 KItemModelBase
* previous
= m_model
;
1218 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1219 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1220 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1221 this, SLOT(slotItemsInserted(KItemRangeList
)));
1222 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1223 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1224 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1225 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1226 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1227 this, SLOT(slotGroupedSortingChanged(bool)));
1228 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1229 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1230 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1231 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1235 m_layouter
->setModel(model
);
1236 m_grouped
= model
->groupedSorting();
1239 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1240 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1241 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1242 this, SLOT(slotItemsInserted(KItemRangeList
)));
1243 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1244 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1245 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1246 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1247 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1248 this, SLOT(slotGroupedSortingChanged(bool)));
1249 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1250 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1251 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1252 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1255 onModelChanged(model
, previous
);
1258 KItemListRubberBand
* KItemListView::rubberBand() const
1260 return m_rubberBand
;
1263 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1265 if (m_layoutTimer
->isActive()) {
1266 m_layoutTimer
->stop();
1269 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1273 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1274 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1275 if (firstVisibleIndex
< 0) {
1276 emitOffsetChanges();
1280 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1281 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1282 // is still shown if the maximum offset got decreased.
1283 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1284 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1285 if (scrollOffset() > maxOffsetToShowFullRange
) {
1286 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1289 // Determine all items that are completely invisible and might be
1290 // reused for items that just got (at least partly) visible.
1291 // Items that do e.g. an animated moving of their position are not
1292 // marked as invisible: This assures that a scrolling inside the view
1293 // can be done without breaking an animation.
1294 QList
<int> reusableItems
;
1295 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1296 while (it
.hasNext()) {
1298 KItemListWidget
* widget
= it
.value();
1299 const int index
= widget
->index();
1300 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1301 if (invisible
&& !m_animation
->isStarted(widget
)) {
1302 widget
->setVisible(false);
1303 reusableItems
.append(index
);
1306 recycleGroupHeaderForWidget(widget
);
1311 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1312 // instances from invisible items are reused. If no reusable items are
1313 // found then new KItemListWidget instances get created.
1314 const bool animate
= (hint
== Animation
);
1315 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1316 bool applyNewPos
= true;
1317 bool wasHidden
= false;
1319 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1320 const QPointF newPos
= itemBounds
.topLeft();
1321 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1324 if (!reusableItems
.isEmpty()) {
1325 // Reuse a KItemListWidget instance from an invisible item
1326 const int oldIndex
= reusableItems
.takeLast();
1327 widget
= m_visibleItems
.value(oldIndex
);
1328 setWidgetIndex(widget
, i
);
1331 updateGroupHeaderForWidget(widget
);
1334 // No reusable KItemListWidget instance is available, create a new one
1335 widget
= createWidget(i
);
1337 widget
->resize(itemBounds
.size());
1339 if (animate
&& changedCount
< 0) {
1340 // Items have been deleted, move the created item to the
1341 // imaginary old position. They will get animated to the new position
1343 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1344 if (itemRect
.isEmpty()) {
1345 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1346 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1347 widget
->setPos(invisibleOldPos
);
1349 widget
->setPos(itemRect
.topLeft());
1351 applyNewPos
= false;
1353 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1354 applyNewPos
= false;
1358 const bool itemsRemoved
= (changedCount
< 0);
1359 const bool itemsInserted
= (changedCount
> 0);
1360 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1361 // The item is located after the removed items. Animate the moving of the position.
1362 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1363 applyNewPos
= false;
1364 } else if (itemsInserted
&& i
>= changedIndex
) {
1365 // The item is located after the first inserted item
1366 if (i
<= changedIndex
+ changedCount
- 1) {
1367 // The item is an inserted item. Animate the appearing of the item.
1368 // For performance reasons no animation is done when changedCount is equal
1369 // to all available items.
1370 if (changedCount
< m_model
->count()) {
1371 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1373 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1374 // The item was already there before, so animate the moving of the position.
1375 // No moving animation is done if the item is animated by a create animation: This
1376 // prevents a "move animation mess" when inserting several ranges in parallel.
1377 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1378 applyNewPos
= false;
1380 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1381 // The size of the view might have been changed. Animate the moving of the position.
1382 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1383 applyNewPos
= false;
1388 widget
->setPos(newPos
);
1391 Q_ASSERT(widget
->index() == i
);
1392 widget
->setVisible(true);
1394 if (widget
->size() != itemBounds
.size()) {
1395 // Resize the widget for the item to the changed size.
1397 // If a dynamic item size is used then no animation is done in the direction
1398 // of the dynamic size.
1399 if (m_itemSize
.width() <= 0) {
1400 // The width is dynamic, apply the new width without animation.
1401 widget
->resize(itemBounds
.width(), widget
->size().height());
1402 } else if (m_itemSize
.height() <= 0) {
1403 // The height is dynamic, apply the new height without animation.
1404 widget
->resize(widget
->size().width(), itemBounds
.height());
1406 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1408 widget
->resize(itemBounds
.size());
1413 // Delete invisible KItemListWidget instances that have not been reused
1414 foreach (int index
, reusableItems
) {
1415 recycleWidget(m_visibleItems
.value(index
));
1419 // Update the layout of all visible group headers
1420 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1421 while (it
.hasNext()) {
1423 updateGroupHeaderLayout(it
.key());
1427 emitOffsetChanges();
1430 void KItemListView::emitOffsetChanges()
1432 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1433 if (m_oldScrollOffset
!= newScrollOffset
) {
1434 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1435 m_oldScrollOffset
= newScrollOffset
;
1438 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1439 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1440 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1441 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1444 const qreal newItemOffset
= m_layouter
->itemOffset();
1445 if (m_oldItemOffset
!= newItemOffset
) {
1446 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1447 m_oldItemOffset
= newItemOffset
;
1450 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1451 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1452 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1453 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1457 KItemListWidget
* KItemListView::createWidget(int index
)
1459 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1460 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1462 updateWidgetProperties(widget
, index
);
1463 m_visibleItems
.insert(index
, widget
);
1466 updateGroupHeaderForWidget(widget
);
1469 initializeItemListWidget(widget
);
1473 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1476 recycleGroupHeaderForWidget(widget
);
1479 m_visibleItems
.remove(widget
->index());
1480 m_widgetCreator
->recycle(widget
);
1483 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1485 const int oldIndex
= widget
->index();
1486 m_visibleItems
.remove(oldIndex
);
1487 updateWidgetProperties(widget
, index
);
1488 m_visibleItems
.insert(index
, widget
);
1490 initializeItemListWidget(widget
);
1493 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1495 // Calculate the first visible index and last visible index for the current size
1496 const int currentFirst
= m_layouter
->firstVisibleIndex();
1497 const int currentLast
= m_layouter
->lastVisibleIndex();
1499 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1501 // Calculate the first visible index and last visible index for the new size
1502 setLayouterSize(size
, sizeType
);
1503 const int newFirst
= m_layouter
->firstVisibleIndex();
1504 const int newLast
= m_layouter
->lastVisibleIndex();
1506 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1507 // At least one index has been changed. Assure that widgets for all possible
1508 // visible items get created so that a move-animation can be started later.
1509 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1510 int minFirst
= qMin(newFirst
, currentFirst
);
1511 const int maxLast
= qMax(newLast
, currentLast
);
1513 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1514 // Increasing the size might result in a smaller KItemListView::offset().
1515 // Decrease the first visible index in a way that at least the maximum
1516 // visible items are shown.
1517 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1520 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1521 // The creating of widgets is quite expensive. Assure that never more
1522 // than 50 % of the maximum visible items get created for the animations.
1526 setLayouterSize(currentSize
, sizeType
);
1527 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1528 if (!m_visibleItems
.contains(i
)) {
1529 KItemListWidget
* widget
= createWidget(i
);
1530 const QRectF itemRect
= m_layouter
->itemRect(i
);
1531 widget
->setPos(itemRect
.topLeft());
1532 widget
->resize(itemRect
.size());
1535 setLayouterSize(size
, sizeType
);
1539 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1542 case LayouterSize
: m_layouter
->setSize(size
); break;
1543 case ItemSize
: m_layouter
->setItemSize(size
); break;
1548 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1550 widget
->setVisibleRoles(m_visibleRoles
);
1551 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1552 widget
->setStyleOption(m_styleOption
);
1554 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1555 widget
->setCurrent(index
== selectionManager
->currentItem());
1556 widget
->setSelected(selectionManager
->isSelected(index
));
1557 widget
->setHovered(false);
1558 widget
->setAlternatingBackgroundColors(false);
1559 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1560 widget
->setIndex(index
);
1561 widget
->setData(m_model
->data(index
));
1564 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1566 Q_ASSERT(m_grouped
);
1568 const int index
= widget
->index();
1569 if (!m_layouter
->isFirstGroupItem(index
)) {
1570 // The widget does not represent the first item of a group
1571 // and hence requires no header
1572 recycleGroupHeaderForWidget(widget
);
1576 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1577 if (groups
.isEmpty()) {
1581 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1583 header
= m_groupHeaderCreator
->create(this);
1584 header
->setParentItem(widget
);
1585 m_visibleGroups
.insert(widget
, header
);
1587 Q_ASSERT(header
->parentItem() == widget
);
1589 // Determine the shown data for the header by doing a binary
1590 // search in the groups-list
1592 int max
= groups
.count() - 1;
1595 mid
= (min
+ max
) / 2;
1596 if (index
> groups
.at(mid
).first
) {
1601 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1603 header
->setData(groups
.at(mid
).second
);
1604 header
->setRole(model()->sortRole());
1605 header
->setStyleOption(m_styleOption
);
1606 header
->setScrollOrientation(scrollOrientation());
1611 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1613 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1616 const int index
= widget
->index();
1617 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1618 const QRectF itemRect
= m_layouter
->itemRect(index
);
1620 // The group-header is a child of the itemlist widget. Translate the
1621 // group header position to the relative position.
1622 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1623 - groupHeaderRect
.height());
1624 header
->setPos(groupHeaderPos
);
1625 header
->resize(groupHeaderRect
.size());
1628 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1630 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1632 header
->setParentItem(0);
1633 m_groupHeaderCreator
->recycle(header
);
1634 m_visibleGroups
.remove(widget
);
1638 void KItemListView::updateVisibleGroupHeaders()
1640 Q_ASSERT(m_grouped
);
1641 m_layouter
->markAsDirty();
1643 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1644 while (it
.hasNext()) {
1646 updateGroupHeaderForWidget(it
.value());
1650 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1652 QHash
<QByteArray
, qreal
> rolesWidths
;
1654 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1655 while (it
.hasNext()) {
1657 rolesWidths
.insert(it
.key(), it
.value().width());
1663 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1665 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1669 const int itemCount
= m_model
->count();
1670 int rangesItemCount
= 0;
1671 foreach (const KItemRange
& range
, itemRanges
) {
1672 rangesItemCount
+= range
.count
;
1675 if (itemCount
== rangesItemCount
) {
1676 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1678 // Assure the the sizes are not smaller than the minimum defined by the header
1679 // TODO: Currently only implemented for a top-aligned header
1680 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1681 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1682 while (it
.hasNext()) {
1684 const QSizeF
& size
= it
.value();
1685 if (size
.width() < minHeaderRoleWidth
) {
1686 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1687 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1692 // Only a sub range of the roles need to be determined.
1693 // The chances are good that the sizes of the sub ranges
1694 // already fit into the available sizes and hence no
1695 // expensive update might be required.
1696 bool updateRequired
= false;
1698 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1699 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1700 while (it
.hasNext()) {
1702 const QByteArray
& role
= it
.key();
1703 const QSizeF
& updatedSize
= it
.value();
1704 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1705 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1706 m_visibleRolesSizes
.insert(role
, updatedSize
);
1707 updateRequired
= true;
1711 if (!updateRequired
) {
1712 // All the updated sizes are smaller than the current sizes and no change
1713 // of the stretched roles-widths is required
1718 updateStretchedVisibleRolesSizes();
1721 void KItemListView::updateVisibleRolesSizes()
1727 const int itemCount
= m_model
->count();
1728 if (itemCount
> 0) {
1729 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1733 void KItemListView::updateStretchedVisibleRolesSizes()
1735 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1739 // Calculate the maximum size of an item by considering the
1740 // visible role sizes and apply them to the layouter. If the
1741 // size does not use the available view-size it the size of the
1742 // first role will get stretched.
1743 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1744 const QByteArray role
= m_visibleRoles
.first();
1745 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1747 QSizeF dynamicItemSize
= m_itemSize
;
1749 if (dynamicItemSize
.width() <= 0) {
1750 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1751 const qreal availableWidth
= size().width();
1752 if (requiredWidth
< availableWidth
) {
1753 // Stretch the first role to use the whole width for the item
1754 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1755 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1757 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1760 if (dynamicItemSize
.height() <= 0) {
1761 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1762 const qreal availableHeight
= size().height();
1763 if (requiredHeight
< availableHeight
) {
1764 // Stretch the first role to use the whole height for the item
1765 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1766 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1768 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1771 m_layouter
->setItemSize(dynamicItemSize
);
1774 m_header
->setVisibleRolesWidths(headerRolesWidths());
1775 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1778 // Update the role sizes for all visible widgets
1779 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1780 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1784 qreal
KItemListView::visibleRolesSizesWidthSum() const
1787 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1788 while (it
.hasNext()) {
1790 widthSum
+= it
.value().width();
1795 qreal
KItemListView::visibleRolesSizesHeightSum() const
1797 qreal heightSum
= 0;
1798 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1799 while (it
.hasNext()) {
1801 heightSum
+= it
.value().height();
1806 QRectF
KItemListView::headerBoundaries() const
1808 return m_header
? m_header
->geometry() : QRectF();
1811 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1815 const int minSpeed
= 4;
1816 const int maxSpeed
= 128;
1817 const int speedLimiter
= 96;
1818 const int autoScrollBorder
= 64;
1820 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1821 // This assures that the autoscrolling speed grows gradually.
1822 const int incLimiter
= 1;
1824 if (pos
< autoScrollBorder
) {
1825 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1826 inc
= qMax(inc
, -maxSpeed
);
1827 inc
= qMax(inc
, oldInc
- incLimiter
);
1828 } else if (pos
> range
- autoScrollBorder
) {
1829 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1830 inc
= qMin(inc
, maxSpeed
);
1831 inc
= qMin(inc
, oldInc
+ incLimiter
);
1839 KItemListCreatorBase::~KItemListCreatorBase()
1841 qDeleteAll(m_recycleableWidgets
);
1842 qDeleteAll(m_createdWidgets
);
1845 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1847 m_createdWidgets
.insert(widget
);
1850 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1852 Q_ASSERT(m_createdWidgets
.contains(widget
));
1853 m_createdWidgets
.remove(widget
);
1855 if (m_recycleableWidgets
.count() < 100) {
1856 m_recycleableWidgets
.append(widget
);
1857 widget
->setVisible(false);
1863 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1865 if (m_recycleableWidgets
.isEmpty()) {
1869 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1870 m_createdWidgets
.insert(widget
);
1874 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1878 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1880 widget
->setParentItem(0);
1881 widget
->setOpacity(1.0);
1882 pushRecycleableWidget(widget
);
1885 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1889 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1891 header
->setOpacity(1.0);
1892 pushRecycleableWidget(header
);
1895 #include "kitemlistview.moc"