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 if (itemSize
.isEmpty()) {
151 updateVisibleRolesSizes();
153 m_layouter
->setItemSize(itemSize
);
156 m_sizeHintResolver
->clearCache();
158 onItemSizeChanged(itemSize
, previousSize
);
161 QSizeF
KItemListView::itemSize() const
166 void KItemListView::setScrollOffset(qreal offset
)
172 const qreal previousOffset
= m_layouter
->scrollOffset();
173 if (offset
== previousOffset
) {
177 m_layouter
->setScrollOffset(offset
);
178 m_animation
->setScrollOffset(offset
);
180 // Don't check whether the m_layoutTimer is active: Changing the
181 // scroll offset must always trigger a synchronous layout, otherwise
182 // the smooth-scrolling might get jerky.
183 doLayout(NoAnimation
);
184 onScrollOffsetChanged(offset
, previousOffset
);
187 qreal
KItemListView::scrollOffset() const
189 return m_layouter
->scrollOffset();
192 qreal
KItemListView::maximumScrollOffset() const
194 return m_layouter
->maximumScrollOffset();
197 void KItemListView::setItemOffset(qreal offset
)
199 if (m_layouter
->itemOffset() == offset
) {
203 m_layouter
->setItemOffset(offset
);
205 m_header
->setPos(-offset
, 0);
208 // Don't check whether the m_layoutTimer is active: Changing the
209 // item offset must always trigger a synchronous layout, otherwise
210 // the smooth-scrolling might get jerky.
211 doLayout(NoAnimation
);
214 qreal
KItemListView::itemOffset() const
216 return m_layouter
->itemOffset();
219 qreal
KItemListView::maximumItemOffset() const
221 return m_layouter
->maximumItemOffset();
224 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
226 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
227 m_visibleRoles
= roles
;
229 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
230 while (it
.hasNext()) {
232 KItemListWidget
* widget
= it
.value();
233 widget
->setVisibleRoles(roles
);
234 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
237 m_sizeHintResolver
->clearCache();
238 m_layouter
->markAsDirty();
241 m_header
->setVisibleRoles(roles
);
242 m_header
->setVisibleRolesWidths(headerRolesWidths());
243 m_useHeaderWidths
= false;
246 updateVisibleRolesSizes();
249 onVisibleRolesChanged(roles
, previousRoles
);
252 QList
<QByteArray
> KItemListView::visibleRoles() const
254 return m_visibleRoles
;
257 void KItemListView::setAutoScroll(bool enabled
)
259 if (enabled
&& !m_autoScrollTimer
) {
260 m_autoScrollTimer
= new QTimer(this);
261 m_autoScrollTimer
->setSingleShot(false);
262 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
263 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
264 } else if (!enabled
&& m_autoScrollTimer
) {
265 delete m_autoScrollTimer
;
266 m_autoScrollTimer
= 0;
271 bool KItemListView::autoScroll() const
273 return m_autoScrollTimer
!= 0;
276 void KItemListView::setEnabledSelectionToggles(bool enabled
)
278 if (m_enabledSelectionToggles
!= enabled
) {
279 m_enabledSelectionToggles
= enabled
;
281 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
282 while (it
.hasNext()) {
284 it
.value()->setEnabledSelectionToggle(enabled
);
289 bool KItemListView::enabledSelectionToggles() const
291 return m_enabledSelectionToggles
;
294 KItemListController
* KItemListView::controller() const
299 KItemModelBase
* KItemListView::model() const
304 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
306 m_widgetCreator
= widgetCreator
;
309 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
311 return m_widgetCreator
;
314 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
316 m_groupHeaderCreator
= groupHeaderCreator
;
319 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
321 return m_groupHeaderCreator
;
324 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
326 const KItemListStyleOption previousOption
= m_styleOption
;
327 m_styleOption
= option
;
329 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
330 while (it
.hasNext()) {
332 it
.value()->setStyleOption(option
);
335 m_sizeHintResolver
->clearCache();
337 onStyleOptionChanged(option
, previousOption
);
340 const KItemListStyleOption
& KItemListView::styleOption() const
342 return m_styleOption
;
345 void KItemListView::setGeometry(const QRectF
& rect
)
347 QGraphicsWidget::setGeometry(rect
);
353 const QSizeF newSize
= rect
.size();
354 if (m_itemSize
.isEmpty()) {
355 // The item size is dynamic:
356 // Changing the geometry does not require to do an expensive
357 // update of the visible-roles sizes, only the stretched sizes
358 // need to be adjusted to the new size.
359 updateStretchedVisibleRolesSizes();
361 if (m_useHeaderWidths
) {
362 QSizeF dynamicItemSize
= m_layouter
->itemSize();
364 if (m_itemSize
.width() < 0) {
365 const qreal requiredWidth
= visibleRolesSizesWidthSum();
366 if (newSize
.width() > requiredWidth
) {
367 dynamicItemSize
.setWidth(newSize
.width());
369 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
370 m_header
->resize(headerWidth
, m_header
->size().height());
373 if (m_itemSize
.height() < 0) {
374 const qreal requiredHeight
= visibleRolesSizesHeightSum();
375 if (newSize
.height() > requiredHeight
) {
376 dynamicItemSize
.setHeight(newSize
.height());
378 // TODO: KItemListHeader is not prepared for vertical alignment
381 m_layouter
->setItemSize(dynamicItemSize
);
384 // Triggering a synchronous layout is fine from a performance point of view,
385 // as with dynamic item sizes no moving animation must be done.
386 m_layouter
->setSize(newSize
);
389 // The item size is not dynamic and most probably the geometry change results
390 // in animated position changes of the items. Trigger an asynchronous relayout
391 // with m_layoutTimer to prevent performance bottlenecks.
392 m_layouter
->setSize(newSize
);
393 if (!m_layoutTimer
->isActive()) {
394 m_layoutTimer
->start();
399 int KItemListView::itemAt(const QPointF
& pos
) const
401 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
402 while (it
.hasNext()) {
405 const KItemListWidget
* widget
= it
.value();
406 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
407 if (widget
->contains(mappedPos
)) {
415 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
417 if (!m_enabledSelectionToggles
) {
421 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
423 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
424 if (!selectionToggleRect
.isEmpty()) {
425 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
426 return selectionToggleRect
.contains(mappedPos
);
432 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
434 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
436 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
437 if (!expansionToggleRect
.isEmpty()) {
438 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
439 return expansionToggleRect
.contains(mappedPos
);
445 int KItemListView::firstVisibleIndex() const
447 return m_layouter
->firstVisibleIndex();
450 int KItemListView::lastVisibleIndex() const
452 return m_layouter
->lastVisibleIndex();
455 QSizeF
KItemListView::itemSizeHint(int index
) const
461 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
463 Q_UNUSED(itemRanges
);
464 return QHash
<QByteArray
, QSizeF
>();
467 bool KItemListView::supportsItemExpanding() const
472 QRectF
KItemListView::itemRect(int index
) const
474 return m_layouter
->itemRect(index
);
477 QRectF
KItemListView::itemContextRect(int index
) const
481 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
483 contextRect
= widget
->iconRect() | widget
->textRect();
484 contextRect
.translate(itemRect(index
).topLeft());
490 void KItemListView::scrollToItem(int index
)
492 QRectF viewGeometry
= geometry();
494 const qreal headerHeight
= m_header
->size().height();
495 viewGeometry
.adjust(0, headerHeight
, 0, 0);
497 const QRectF currentRect
= itemRect(index
);
499 if (!viewGeometry
.contains(currentRect
)) {
500 qreal newOffset
= scrollOffset();
501 if (scrollOrientation() == Qt::Vertical
) {
502 if (currentRect
.top() < viewGeometry
.top()) {
503 newOffset
+= currentRect
.top() - viewGeometry
.top();
504 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
505 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
508 if (currentRect
.left() < viewGeometry
.left()) {
509 newOffset
+= currentRect
.left() - viewGeometry
.left();
510 } else if (currentRect
.right() > viewGeometry
.right()) {
511 newOffset
+= currentRect
.right() - viewGeometry
.right();
515 if (newOffset
!= scrollOffset()) {
516 emit
scrollTo(newOffset
);
521 void KItemListView::beginTransaction()
523 ++m_activeTransactions
;
524 if (m_activeTransactions
== 1) {
525 onTransactionBegin();
529 void KItemListView::endTransaction()
531 --m_activeTransactions
;
532 if (m_activeTransactions
< 0) {
533 m_activeTransactions
= 0;
534 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
537 if (m_activeTransactions
== 0) {
543 bool KItemListView::isTransactionActive() const
545 return m_activeTransactions
> 0;
549 void KItemListView::setHeaderShown(bool show
)
552 if (show
&& !m_header
) {
553 m_header
= new KItemListHeader(this);
554 m_header
->setPos(0, 0);
555 m_header
->setModel(m_model
);
556 m_header
->setVisibleRoles(m_visibleRoles
);
557 m_header
->setVisibleRolesWidths(headerRolesWidths());
558 m_header
->setZValue(1);
560 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
561 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
562 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
563 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
564 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
565 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
567 m_useHeaderWidths
= false;
569 m_layouter
->setHeaderHeight(m_header
->size().height());
570 } else if (!show
&& m_header
) {
573 m_useHeaderWidths
= false;
574 m_layouter
->setHeaderHeight(0);
578 bool KItemListView::isHeaderShown() const
580 return m_header
!= 0;
583 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
589 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
591 QGraphicsWidget::paint(painter
, option
, widget
);
593 if (m_rubberBand
->isActive()) {
594 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
595 m_rubberBand
->endPosition()).normalized();
597 const QPointF topLeft
= rubberBandRect
.topLeft();
598 if (scrollOrientation() == Qt::Vertical
) {
599 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
601 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
604 QStyleOptionRubberBand opt
;
605 opt
.initFrom(widget
);
606 opt
.shape
= QRubberBand::Rectangle
;
608 opt
.rect
= rubberBandRect
.toRect();
609 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
613 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
618 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
620 Q_UNUSED(changedRoles
);
624 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
630 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
636 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
642 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
648 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
654 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
660 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
666 void KItemListView::onTransactionBegin()
670 void KItemListView::onTransactionEnd()
674 bool KItemListView::event(QEvent
* event
)
676 // Forward all events to the controller and handle them there
677 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
681 return QGraphicsWidget::event(event
);
684 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
686 m_mousePos
= transform().map(event
->pos());
690 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
692 QGraphicsWidget::mouseMoveEvent(event
);
694 m_mousePos
= transform().map(event
->pos());
695 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
696 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
700 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
702 event
->setAccepted(true);
706 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
708 QGraphicsWidget::dragMoveEvent(event
);
710 m_mousePos
= transform().map(event
->pos());
711 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
712 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
716 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
718 QGraphicsWidget::dragLeaveEvent(event
);
719 setAutoScroll(false);
722 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
724 QGraphicsWidget::dropEvent(event
);
725 setAutoScroll(false);
728 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
730 return m_visibleItems
.values();
733 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
735 updateVisibleRolesSizes(itemRanges
);
737 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
738 if (hasMultipleRanges
) {
742 int previouslyInsertedCount
= 0;
743 foreach (const KItemRange
& range
, itemRanges
) {
744 // range.index is related to the model before anything has been inserted.
745 // As in each loop the current item-range gets inserted the index must
746 // be increased by the already previously inserted items.
747 const int index
= range
.index
+ previouslyInsertedCount
;
748 const int count
= range
.count
;
749 if (index
< 0 || count
<= 0) {
750 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
753 previouslyInsertedCount
+= count
;
755 m_sizeHintResolver
->itemsInserted(index
, count
);
757 // Determine which visible items must be moved
758 QList
<int> itemsToMove
;
759 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
760 while (it
.hasNext()) {
762 const int visibleItemIndex
= it
.key();
763 if (visibleItemIndex
>= index
) {
764 itemsToMove
.append(visibleItemIndex
);
768 // Update the indexes of all KItemListWidget instances that are located
769 // after the inserted items. It is important to adjust the indexes in the order
770 // from the highest index to the lowest index to prevent overlaps when setting the new index.
772 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
773 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
775 setWidgetIndex(widget
, widget
->index() + count
);
778 m_layouter
->markAsDirty();
779 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
780 // Check whether a scrollbar is required to show the inserted items. In this case
781 // the size of the layouter will be decreased before calling doLayout(): This prevents
782 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
783 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
784 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
785 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
786 if (decreaseLayouterSize
) {
787 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
788 QSizeF layouterSize
= m_layouter
->size();
789 if (verticalScrollOrientation
) {
790 layouterSize
.rwidth() -= scrollBarExtent
;
792 layouterSize
.rheight() -= scrollBarExtent
;
794 m_layouter
->setSize(layouterSize
);
798 if (!hasMultipleRanges
) {
799 doLayout(Animation
, index
, count
);
804 m_controller
->selectionManager()->itemsInserted(itemRanges
);
807 if (hasMultipleRanges
) {
812 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
814 updateVisibleRolesSizes();
816 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
817 if (hasMultipleRanges
) {
821 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
822 const KItemRange
& range
= itemRanges
.at(i
);
823 const int index
= range
.index
;
824 const int count
= range
.count
;
825 if (index
< 0 || count
<= 0) {
826 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
830 m_sizeHintResolver
->itemsRemoved(index
, count
);
832 const int firstRemovedIndex
= index
;
833 const int lastRemovedIndex
= index
+ count
- 1;
834 const int lastIndex
= m_model
->count() + count
- 1;
836 // Remove all KItemListWidget instances that got deleted
837 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
838 KItemListWidget
* widget
= m_visibleItems
.value(i
);
843 m_animation
->stop(widget
);
844 // Stopping the animation might lead to recycling the widget if
845 // it is invisible (see slotAnimationFinished()).
846 // Check again whether it is still visible:
847 if (!m_visibleItems
.contains(i
)) {
851 if (m_model
->count() == 0) {
852 // For performance reasons no animation is done when all items have
854 recycleWidget(widget
);
856 // Animate the removing of the items. Special case: When removing an item there
857 // is no valid model index available anymore. For the
858 // remove-animation the item gets removed from m_visibleItems but the widget
859 // will stay alive until the animation has been finished and will
860 // be recycled (deleted) in KItemListView::slotAnimationFinished().
861 m_visibleItems
.remove(i
);
862 widget
->setIndex(-1);
863 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
867 // Update the indexes of all KItemListWidget instances that are located
868 // after the deleted items
869 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
870 KItemListWidget
* widget
= m_visibleItems
.value(i
);
872 const int newIndex
= i
- count
;
873 setWidgetIndex(widget
, newIndex
);
877 m_layouter
->markAsDirty();
878 if (!hasMultipleRanges
) {
879 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
880 // assumes an updated geometry. If items are removed during an active transaction,
881 // the transaction will be temporary deactivated so that doLayout() triggers a
882 // geometry update if necessary.
883 const int activeTransactions
= m_activeTransactions
;
884 m_activeTransactions
= 0;
885 doLayout(Animation
, index
, -count
);
886 m_activeTransactions
= activeTransactions
;
891 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
894 if (hasMultipleRanges
) {
899 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
901 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
902 m_layouter
->markAsDirty();
905 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
908 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
909 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
911 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
912 KItemListWidget
* widget
= m_visibleItems
.value(index
);
914 updateWidgetProperties(widget
, index
);
916 updateGroupHeaderForWidget(widget
);
918 initializeItemListWidget(widget
);
922 doLayout(NoAnimation
);
925 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
926 const QSet
<QByteArray
>& roles
)
928 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
929 if (updateSizeHints
) {
930 updateVisibleRolesSizes(itemRanges
);
933 foreach (const KItemRange
& itemRange
, itemRanges
) {
934 const int index
= itemRange
.index
;
935 const int count
= itemRange
.count
;
937 if (updateSizeHints
) {
938 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
939 m_layouter
->markAsDirty();
941 if (!m_layoutTimer
->isActive()) {
942 m_layoutTimer
->start();
946 // Apply the changed roles to the visible item-widgets
947 const int lastIndex
= index
+ count
- 1;
948 for (int i
= index
; i
<= lastIndex
; ++i
) {
949 KItemListWidget
* widget
= m_visibleItems
.value(i
);
951 widget
->setData(m_model
->data(i
), roles
);
955 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
956 // The sort-role has been changed which might result
957 // in modified group headers
958 updateVisibleGroupHeaders();
959 doLayout(NoAnimation
);
964 void KItemListView::slotGroupedSortingChanged(bool current
)
967 m_layouter
->markAsDirty();
970 // Apply the height of the header to the layouter
971 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
972 m_styleOption
.margin
* 2;
973 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
975 updateVisibleGroupHeaders();
977 // Clear all visible headers
978 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
979 while (it
.hasNext()) {
981 recycleGroupHeaderForWidget(it
.key());
983 Q_ASSERT(m_visibleGroups
.isEmpty());
989 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
994 updateVisibleGroupHeaders();
999 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1004 updateVisibleGroupHeaders();
1005 doLayout(Animation
);
1009 void KItemListView::slotCurrentChanged(int current
, int previous
)
1013 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1014 if (previousWidget
) {
1015 Q_ASSERT(previousWidget
->isCurrent());
1016 previousWidget
->setCurrent(false);
1019 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1020 if (currentWidget
) {
1021 Q_ASSERT(!currentWidget
->isCurrent());
1022 currentWidget
->setCurrent(true);
1026 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1030 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1031 while (it
.hasNext()) {
1033 const int index
= it
.key();
1034 KItemListWidget
* widget
= it
.value();
1035 widget
->setSelected(current
.contains(index
));
1039 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1040 KItemListViewAnimation::AnimationType type
)
1042 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1043 Q_ASSERT(itemListWidget
);
1046 case KItemListViewAnimation::DeleteAnimation
: {
1047 // As we recycle the widget in this case it is important to assure that no
1048 // other animation has been started. This is a convention in KItemListView and
1049 // not a requirement defined by KItemListViewAnimation.
1050 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1052 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1053 // by m_visibleWidgets and must be deleted manually after the animation has
1055 recycleGroupHeaderForWidget(itemListWidget
);
1056 m_widgetCreator
->recycle(itemListWidget
);
1060 case KItemListViewAnimation::CreateAnimation
:
1061 case KItemListViewAnimation::MovingAnimation
:
1062 case KItemListViewAnimation::ResizeAnimation
: {
1063 const int index
= itemListWidget
->index();
1064 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1065 (index
> m_layouter
->lastVisibleIndex());
1066 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1067 recycleWidget(itemListWidget
);
1076 void KItemListView::slotLayoutTimerFinished()
1078 m_layouter
->setSize(geometry().size());
1079 doLayout(Animation
);
1082 void KItemListView::slotRubberBandPosChanged()
1087 void KItemListView::slotRubberBandActivationChanged(bool active
)
1090 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1091 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1092 m_skipAutoScrollForRubberBand
= true;
1094 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1095 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1096 m_skipAutoScrollForRubberBand
= false;
1102 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1104 qreal previousWidth
)
1106 Q_UNUSED(previousWidth
);
1108 m_useHeaderWidths
= true;
1110 if (m_visibleRolesSizes
.contains(role
)) {
1111 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1112 roleSize
.setWidth(currentWidth
);
1113 m_visibleRolesSizes
.insert(role
, roleSize
);
1114 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1116 // Apply the new size to the layouter
1117 QSizeF dynamicItemSize
= m_itemSize
;
1118 if (dynamicItemSize
.width() < 0) {
1119 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1120 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1122 if (dynamicItemSize
.height() < 0) {
1123 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1124 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1127 m_layouter
->setItemSize(dynamicItemSize
);
1129 // Update the role sizes for all visible widgets
1130 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1131 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1134 doLayout(Animation
);
1138 void KItemListView::triggerAutoScrolling()
1140 if (!m_autoScrollTimer
) {
1145 int visibleSize
= 0;
1146 if (scrollOrientation() == Qt::Vertical
) {
1147 pos
= m_mousePos
.y();
1148 visibleSize
= size().height();
1150 pos
= m_mousePos
.x();
1151 visibleSize
= size().width();
1154 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1155 m_autoScrollIncrement
= 0;
1158 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1159 if (m_autoScrollIncrement
== 0) {
1160 // The mouse position is not above an autoscroll margin (the autoscroll timer
1161 // will be restarted in mouseMoveEvent())
1162 m_autoScrollTimer
->stop();
1166 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1167 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1168 // if the direction of the rubberband is similar to the autoscroll direction. This
1169 // prevents that starting to create a rubberband within the autoscroll margins starts
1170 // an autoscrolling.
1172 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1173 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1174 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1175 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1176 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1177 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1178 // been moved up although the autoscroll direction might be down)
1179 m_autoScrollTimer
->stop();
1184 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1185 // the autoscrolling may not get skipped anymore until a new rubberband is created
1186 m_skipAutoScrollForRubberBand
= false;
1188 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1189 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1190 setScrollOffset(newScrollOffset
);
1192 // Trigger the autoscroll timer which will periodically call
1193 // triggerAutoScrolling()
1194 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1197 void KItemListView::setController(KItemListController
* controller
)
1199 if (m_controller
!= controller
) {
1200 KItemListController
* previous
= m_controller
;
1202 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1203 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1204 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1207 m_controller
= controller
;
1210 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1211 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1212 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1215 onControllerChanged(controller
, previous
);
1219 void KItemListView::setModel(KItemModelBase
* model
)
1221 if (m_model
== model
) {
1225 KItemModelBase
* previous
= m_model
;
1228 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1229 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1230 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1231 this, SLOT(slotItemsInserted(KItemRangeList
)));
1232 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1233 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1234 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1235 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1236 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1237 this, SLOT(slotGroupedSortingChanged(bool)));
1238 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1239 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1240 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1241 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1245 m_layouter
->setModel(model
);
1246 m_grouped
= model
->groupedSorting();
1249 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1250 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1251 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1252 this, SLOT(slotItemsInserted(KItemRangeList
)));
1253 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1254 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1255 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1256 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1257 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1258 this, SLOT(slotGroupedSortingChanged(bool)));
1259 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1260 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1261 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1262 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1265 onModelChanged(model
, previous
);
1268 KItemListRubberBand
* KItemListView::rubberBand() const
1270 return m_rubberBand
;
1273 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1275 if (m_layoutTimer
->isActive()) {
1276 m_layoutTimer
->stop();
1279 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1283 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1284 if (firstVisibleIndex
< 0) {
1285 emitOffsetChanges();
1289 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1290 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1291 // is still shown if the maximum offset got decreased.
1292 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1293 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1294 if (scrollOffset() > maxOffsetToShowFullRange
) {
1295 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1296 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1299 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1301 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
);
1303 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1304 // instances from invisible items are reused. If no reusable items are
1305 // found then new KItemListWidget instances get created.
1306 const bool animate
= (hint
== Animation
);
1307 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1308 bool applyNewPos
= true;
1309 bool wasHidden
= false;
1311 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1312 const QPointF newPos
= itemBounds
.topLeft();
1313 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1316 if (!reusableItems
.isEmpty()) {
1317 // Reuse a KItemListWidget instance from an invisible item
1318 const int oldIndex
= reusableItems
.takeLast();
1319 widget
= m_visibleItems
.value(oldIndex
);
1320 setWidgetIndex(widget
, i
);
1323 updateGroupHeaderForWidget(widget
);
1326 // No reusable KItemListWidget instance is available, create a new one
1327 widget
= createWidget(i
);
1329 widget
->resize(itemBounds
.size());
1331 if (animate
&& changedCount
< 0) {
1332 // Items have been deleted, move the created item to the
1333 // imaginary old position. They will get animated to the new position
1335 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1336 if (itemRect
.isEmpty()) {
1337 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1338 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1339 widget
->setPos(invisibleOldPos
);
1341 widget
->setPos(itemRect
.topLeft());
1343 applyNewPos
= false;
1345 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1346 applyNewPos
= false;
1350 const bool itemsRemoved
= (changedCount
< 0);
1351 const bool itemsInserted
= (changedCount
> 0);
1352 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1353 // The item is located after the removed items. Animate the moving of the position.
1354 applyNewPos
= !moveWidget(widget
, itemBounds
);
1355 } else if (itemsInserted
&& i
>= changedIndex
) {
1356 // The item is located after the first inserted item
1357 if (i
<= changedIndex
+ changedCount
- 1) {
1358 // The item is an inserted item. Animate the appearing of the item.
1359 // For performance reasons no animation is done when changedCount is equal
1360 // to all available items.
1361 if (changedCount
< m_model
->count()) {
1362 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1364 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1365 // The item was already there before, so animate the moving of the position.
1366 // No moving animation is done if the item is animated by a create animation: This
1367 // prevents a "move animation mess" when inserting several ranges in parallel.
1368 applyNewPos
= !moveWidget(widget
, itemBounds
);
1370 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1371 // The size of the view might have been changed. Animate the moving of the position.
1372 applyNewPos
= !moveWidget(widget
, itemBounds
);
1377 widget
->setPos(newPos
);
1380 Q_ASSERT(widget
->index() == i
);
1381 widget
->setVisible(true);
1383 if (widget
->size() != itemBounds
.size()) {
1384 // Resize the widget for the item to the changed size.
1386 // If a dynamic item size is used then no animation is done in the direction
1387 // of the dynamic size.
1388 if (m_itemSize
.width() <= 0) {
1389 // The width is dynamic, apply the new width without animation.
1390 widget
->resize(itemBounds
.width(), widget
->size().height());
1391 } else if (m_itemSize
.height() <= 0) {
1392 // The height is dynamic, apply the new height without animation.
1393 widget
->resize(widget
->size().width(), itemBounds
.height());
1395 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1397 widget
->resize(itemBounds
.size());
1402 // Delete invisible KItemListWidget instances that have not been reused
1403 foreach (int index
, reusableItems
) {
1404 recycleWidget(m_visibleItems
.value(index
));
1408 // Update the layout of all visible group headers
1409 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1410 while (it
.hasNext()) {
1412 updateGroupHeaderLayout(it
.key());
1416 emitOffsetChanges();
1419 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
, int lastVisibleIndex
)
1421 // Determine all items that are completely invisible and might be
1422 // reused for items that just got (at least partly) visible.
1423 // Items that do e.g. an animated moving of their position are not
1424 // marked as invisible: This assures that a scrolling inside the view
1425 // can be done without breaking an animation.
1429 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1430 while (it
.hasNext()) {
1432 KItemListWidget
* widget
= it
.value();
1433 const int index
= widget
->index();
1434 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1435 if (invisible
&& !m_animation
->isStarted(widget
)) {
1436 widget
->setVisible(false);
1437 items
.append(index
);
1440 recycleGroupHeaderForWidget(widget
);
1448 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QRectF
& itemBounds
)
1450 const QPointF oldPos
= widget
->pos();
1451 const QPointF newPos
= itemBounds
.topLeft();
1452 if (oldPos
== newPos
) {
1456 bool startMovingAnim
= m_itemSize
.isEmpty();
1457 if (!startMovingAnim
) {
1458 // When having a grid the moving-animation should only be started, if it is done within
1459 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1460 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1461 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1464 if (widget
->size() != itemBounds
.size()) {
1465 // The item-size has been increased or decreased
1466 const bool zoomOut
= (widget
->size().width() >= itemBounds
.size().width()) &&
1467 (widget
->size().height() >= itemBounds
.size().height());
1468 zoomDiff
= zoomOut
? -1 : +1;
1471 const qreal xMax
= m_itemSize
.width();
1472 const qreal yMax
= m_itemSize
.height();
1473 qreal xDiff
= oldPos
.x() - newPos
.x();
1474 qreal yDiff
= oldPos
.y() - newPos
.y();
1475 if (scrollOrientation() == Qt::Vertical
) {
1476 if (zoomDiff
!= 0) {
1477 // Skip moving animations that changed the row
1478 startMovingAnim
= (zoomDiff
> 0 && xDiff
< xMax
) ||
1479 (zoomDiff
< 0 && -xDiff
< xMax
);
1481 xDiff
= qAbs(xDiff
);
1482 yDiff
= qAbs(yDiff
);
1483 startMovingAnim
= (xDiff
> yDiff
&& yDiff
< yMax
);
1486 if (zoomDiff
!= 0) {
1487 // Skip moving animations that changed the column
1488 startMovingAnim
= (zoomDiff
> 0 && yDiff
< yMax
) ||
1489 (zoomDiff
< 0 && -yDiff
< yMax
);
1491 xDiff
= qAbs(xDiff
);
1492 yDiff
= qAbs(yDiff
);
1493 startMovingAnim
= (yDiff
> xDiff
&& xDiff
< xMax
);
1498 if (startMovingAnim
) {
1499 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1503 m_animation
->stop(widget
);
1504 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1508 void KItemListView::emitOffsetChanges()
1510 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1511 if (m_oldScrollOffset
!= newScrollOffset
) {
1512 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1513 m_oldScrollOffset
= newScrollOffset
;
1516 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1517 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1518 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1519 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1522 const qreal newItemOffset
= m_layouter
->itemOffset();
1523 if (m_oldItemOffset
!= newItemOffset
) {
1524 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1525 m_oldItemOffset
= newItemOffset
;
1528 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1529 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1530 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1531 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1535 KItemListWidget
* KItemListView::createWidget(int index
)
1537 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1538 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1540 updateWidgetProperties(widget
, index
);
1541 m_visibleItems
.insert(index
, widget
);
1544 updateGroupHeaderForWidget(widget
);
1547 initializeItemListWidget(widget
);
1551 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1554 recycleGroupHeaderForWidget(widget
);
1557 m_visibleItems
.remove(widget
->index());
1558 m_widgetCreator
->recycle(widget
);
1561 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1563 const int oldIndex
= widget
->index();
1564 m_visibleItems
.remove(oldIndex
);
1565 updateWidgetProperties(widget
, index
);
1566 m_visibleItems
.insert(index
, widget
);
1568 initializeItemListWidget(widget
);
1571 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1574 case LayouterSize
: m_layouter
->setSize(size
); break;
1575 case ItemSize
: m_layouter
->setItemSize(size
); break;
1580 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1582 widget
->setVisibleRoles(m_visibleRoles
);
1583 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1584 widget
->setStyleOption(m_styleOption
);
1586 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1587 widget
->setCurrent(index
== selectionManager
->currentItem());
1588 widget
->setSelected(selectionManager
->isSelected(index
));
1589 widget
->setHovered(false);
1590 widget
->setAlternatingBackgroundColors(false);
1591 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1592 widget
->setIndex(index
);
1593 widget
->setData(m_model
->data(index
));
1596 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1598 Q_ASSERT(m_grouped
);
1600 const int index
= widget
->index();
1601 if (!m_layouter
->isFirstGroupItem(index
)) {
1602 // The widget does not represent the first item of a group
1603 // and hence requires no header
1604 recycleGroupHeaderForWidget(widget
);
1608 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1609 if (groups
.isEmpty()) {
1613 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1615 header
= m_groupHeaderCreator
->create(this);
1616 header
->setParentItem(widget
);
1617 m_visibleGroups
.insert(widget
, header
);
1619 Q_ASSERT(header
->parentItem() == widget
);
1621 // Determine the shown data for the header by doing a binary
1622 // search in the groups-list
1624 int max
= groups
.count() - 1;
1627 mid
= (min
+ max
) / 2;
1628 if (index
> groups
.at(mid
).first
) {
1633 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1635 header
->setData(groups
.at(mid
).second
);
1636 header
->setRole(model()->sortRole());
1637 header
->setStyleOption(m_styleOption
);
1638 header
->setScrollOrientation(scrollOrientation());
1643 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1645 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1648 const int index
= widget
->index();
1649 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1650 const QRectF itemRect
= m_layouter
->itemRect(index
);
1652 // The group-header is a child of the itemlist widget. Translate the
1653 // group header position to the relative position.
1654 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1655 - groupHeaderRect
.height());
1656 header
->setPos(groupHeaderPos
);
1657 header
->resize(groupHeaderRect
.size());
1660 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1662 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1664 header
->setParentItem(0);
1665 m_groupHeaderCreator
->recycle(header
);
1666 m_visibleGroups
.remove(widget
);
1670 void KItemListView::updateVisibleGroupHeaders()
1672 Q_ASSERT(m_grouped
);
1673 m_layouter
->markAsDirty();
1675 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1676 while (it
.hasNext()) {
1678 updateGroupHeaderForWidget(it
.value());
1682 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1684 QHash
<QByteArray
, qreal
> rolesWidths
;
1686 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1687 while (it
.hasNext()) {
1689 rolesWidths
.insert(it
.key(), it
.value().width());
1695 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1697 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1701 const int itemCount
= m_model
->count();
1702 int rangesItemCount
= 0;
1703 foreach (const KItemRange
& range
, itemRanges
) {
1704 rangesItemCount
+= range
.count
;
1707 if (itemCount
== rangesItemCount
) {
1708 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1710 // Assure the the sizes are not smaller than the minimum defined by the header
1711 // TODO: Currently only implemented for a top-aligned header
1712 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1713 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1714 while (it
.hasNext()) {
1716 const QSizeF
& size
= it
.value();
1717 if (size
.width() < minHeaderRoleWidth
) {
1718 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1719 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1724 // Only a sub range of the roles need to be determined.
1725 // The chances are good that the sizes of the sub ranges
1726 // already fit into the available sizes and hence no
1727 // expensive update might be required.
1728 bool updateRequired
= false;
1730 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1731 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1732 while (it
.hasNext()) {
1734 const QByteArray
& role
= it
.key();
1735 const QSizeF
& updatedSize
= it
.value();
1736 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1737 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1738 m_visibleRolesSizes
.insert(role
, updatedSize
);
1739 updateRequired
= true;
1743 if (!updateRequired
) {
1744 // All the updated sizes are smaller than the current sizes and no change
1745 // of the stretched roles-widths is required
1750 updateStretchedVisibleRolesSizes();
1753 void KItemListView::updateVisibleRolesSizes()
1759 const int itemCount
= m_model
->count();
1760 if (itemCount
> 0) {
1761 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1765 void KItemListView::updateStretchedVisibleRolesSizes()
1767 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1771 // Calculate the maximum size of an item by considering the
1772 // visible role sizes and apply them to the layouter. If the
1773 // size does not use the available view-size it the size of the
1774 // first role will get stretched.
1775 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1776 const QByteArray role
= m_visibleRoles
.first();
1777 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1779 QSizeF dynamicItemSize
= m_itemSize
;
1781 if (dynamicItemSize
.width() <= 0) {
1782 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1783 const qreal availableWidth
= size().width();
1784 if (requiredWidth
< availableWidth
) {
1785 // Stretch the first role to use the whole width for the item
1786 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1787 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1789 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1792 if (dynamicItemSize
.height() <= 0) {
1793 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1794 const qreal availableHeight
= size().height();
1795 if (requiredHeight
< availableHeight
) {
1796 // Stretch the first role to use the whole height for the item
1797 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1798 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1800 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1803 m_layouter
->setItemSize(dynamicItemSize
);
1806 m_header
->setVisibleRolesWidths(headerRolesWidths());
1807 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1810 // Update the role sizes for all visible widgets
1811 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1812 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1816 qreal
KItemListView::visibleRolesSizesWidthSum() const
1819 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1820 while (it
.hasNext()) {
1822 widthSum
+= it
.value().width();
1827 qreal
KItemListView::visibleRolesSizesHeightSum() const
1829 qreal heightSum
= 0;
1830 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1831 while (it
.hasNext()) {
1833 heightSum
+= it
.value().height();
1838 QRectF
KItemListView::headerBoundaries() const
1840 return m_header
? m_header
->geometry() : QRectF();
1843 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1847 const int minSpeed
= 4;
1848 const int maxSpeed
= 128;
1849 const int speedLimiter
= 96;
1850 const int autoScrollBorder
= 64;
1852 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1853 // This assures that the autoscrolling speed grows gradually.
1854 const int incLimiter
= 1;
1856 if (pos
< autoScrollBorder
) {
1857 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1858 inc
= qMax(inc
, -maxSpeed
);
1859 inc
= qMax(inc
, oldInc
- incLimiter
);
1860 } else if (pos
> range
- autoScrollBorder
) {
1861 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1862 inc
= qMin(inc
, maxSpeed
);
1863 inc
= qMin(inc
, oldInc
+ incLimiter
);
1871 KItemListCreatorBase::~KItemListCreatorBase()
1873 qDeleteAll(m_recycleableWidgets
);
1874 qDeleteAll(m_createdWidgets
);
1877 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1879 m_createdWidgets
.insert(widget
);
1882 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1884 Q_ASSERT(m_createdWidgets
.contains(widget
));
1885 m_createdWidgets
.remove(widget
);
1887 if (m_recycleableWidgets
.count() < 100) {
1888 m_recycleableWidgets
.append(widget
);
1889 widget
->setVisible(false);
1895 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1897 if (m_recycleableWidgets
.isEmpty()) {
1901 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1902 m_createdWidgets
.insert(widget
);
1906 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1910 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1912 widget
->setParentItem(0);
1913 widget
->setOpacity(1.0);
1914 pushRecycleableWidget(widget
);
1917 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1921 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1923 header
->setOpacity(1.0);
1924 pushRecycleableWidget(header
);
1927 #include "kitemlistview.moc"