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
);
130 doLayout(Animation
, 0, 0);
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();
162 doLayout(Animation
, 0, 0);
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
);
184 if (!m_layoutTimer
->isActive()) {
185 doLayout(NoAnimation
, 0, 0);
187 onScrollOffsetChanged(offset
, previousOffset
);
190 qreal
KItemListView::scrollOffset() const
192 return m_layouter
->scrollOffset();
195 qreal
KItemListView::maximumScrollOffset() const
197 return m_layouter
->maximumScrollOffset();
200 void KItemListView::setItemOffset(qreal offset
)
202 m_layouter
->setItemOffset(offset
);
204 m_header
->setPos(-offset
, 0);
206 if (!m_layoutTimer
->isActive()) {
207 doLayout(NoAnimation
, 0, 0);
211 qreal
KItemListView::itemOffset() const
213 return m_layouter
->itemOffset();
216 qreal
KItemListView::maximumItemOffset() const
218 return m_layouter
->maximumItemOffset();
221 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
223 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
224 m_visibleRoles
= roles
;
226 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
227 while (it
.hasNext()) {
229 KItemListWidget
* widget
= it
.value();
230 widget
->setVisibleRoles(roles
);
231 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
234 m_sizeHintResolver
->clearCache();
235 m_layouter
->markAsDirty();
238 m_header
->setVisibleRoles(roles
);
239 m_header
->setVisibleRolesWidths(headerRolesWidths());
240 m_useHeaderWidths
= false;
243 updateVisibleRolesSizes();
244 doLayout(Animation
, 0, 0);
246 onVisibleRolesChanged(roles
, previousRoles
);
249 QList
<QByteArray
> KItemListView::visibleRoles() const
251 return m_visibleRoles
;
254 void KItemListView::setAutoScroll(bool enabled
)
256 if (enabled
&& !m_autoScrollTimer
) {
257 m_autoScrollTimer
= new QTimer(this);
258 m_autoScrollTimer
->setSingleShot(false);
259 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
260 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
261 } else if (!enabled
&& m_autoScrollTimer
) {
262 delete m_autoScrollTimer
;
263 m_autoScrollTimer
= 0;
268 bool KItemListView::autoScroll() const
270 return m_autoScrollTimer
!= 0;
273 void KItemListView::setEnabledSelectionToggles(bool enabled
)
275 if (m_enabledSelectionToggles
!= enabled
) {
276 m_enabledSelectionToggles
= enabled
;
278 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
279 while (it
.hasNext()) {
281 it
.value()->setEnabledSelectionToggle(enabled
);
286 bool KItemListView::enabledSelectionToggles() const
288 return m_enabledSelectionToggles
;
291 KItemListController
* KItemListView::controller() const
296 KItemModelBase
* KItemListView::model() const
301 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
303 m_widgetCreator
= widgetCreator
;
306 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
308 return m_widgetCreator
;
311 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
313 m_groupHeaderCreator
= groupHeaderCreator
;
316 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
318 return m_groupHeaderCreator
;
321 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
323 const KItemListStyleOption previousOption
= m_styleOption
;
324 m_styleOption
= option
;
326 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
327 while (it
.hasNext()) {
329 it
.value()->setStyleOption(option
);
332 m_sizeHintResolver
->clearCache();
333 doLayout(Animation
, 0, 0);
334 onStyleOptionChanged(option
, previousOption
);
337 const KItemListStyleOption
& KItemListView::styleOption() const
339 return m_styleOption
;
342 void KItemListView::setGeometry(const QRectF
& rect
)
344 QGraphicsWidget::setGeometry(rect
);
350 if (m_model
->count() > 0) {
351 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
353 m_layouter
->setSize(rect
.size());
356 if (!m_layoutTimer
->isActive()) {
357 m_layoutTimer
->start();
360 // Changing the geometry does not require to do an expensive
361 // update of the visible-roles sizes, only the stretched sizes
362 // need to be adjusted to the new size.
363 updateStretchedVisibleRolesSizes();
366 int KItemListView::itemAt(const QPointF
& pos
) const
368 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
369 while (it
.hasNext()) {
372 const KItemListWidget
* widget
= it
.value();
373 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
374 if (widget
->contains(mappedPos
)) {
382 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
384 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
386 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
387 if (!selectionToggleRect
.isEmpty()) {
388 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
389 return selectionToggleRect
.contains(mappedPos
);
395 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
397 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
399 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
400 if (!expansionToggleRect
.isEmpty()) {
401 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
402 return expansionToggleRect
.contains(mappedPos
);
408 int KItemListView::firstVisibleIndex() const
410 return m_layouter
->firstVisibleIndex();
413 int KItemListView::lastVisibleIndex() const
415 return m_layouter
->lastVisibleIndex();
418 QSizeF
KItemListView::itemSizeHint(int index
) const
424 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
426 Q_UNUSED(itemRanges
);
427 return QHash
<QByteArray
, QSizeF
>();
430 QRectF
KItemListView::itemRect(int index
) const
432 return m_layouter
->itemRect(index
);
435 int KItemListView::itemsPerOffset() const
437 return m_layouter
->itemsPerOffset();
440 void KItemListView::beginTransaction()
442 ++m_activeTransactions
;
443 if (m_activeTransactions
== 1) {
444 onTransactionBegin();
448 void KItemListView::endTransaction()
450 --m_activeTransactions
;
451 if (m_activeTransactions
< 0) {
452 m_activeTransactions
= 0;
453 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
456 if (m_activeTransactions
== 0) {
458 doLayout(Animation
, 0, 0);
462 bool KItemListView::isTransactionActive() const
464 return m_activeTransactions
> 0;
468 void KItemListView::setHeaderShown(bool show
)
471 if (show
&& !m_header
) {
472 m_header
= new KItemListHeader(this);
473 m_header
->setPos(0, 0);
474 m_header
->setModel(m_model
);
475 m_header
->setVisibleRoles(m_visibleRoles
);
476 m_header
->setVisibleRolesWidths(headerRolesWidths());
477 m_header
->setZValue(1);
479 m_useHeaderWidths
= false;
481 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
482 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
484 m_layouter
->setHeaderHeight(m_header
->size().height());
485 } else if (!show
&& m_header
) {
488 m_useHeaderWidths
= false;
489 m_layouter
->setHeaderHeight(0);
493 bool KItemListView::isHeaderShown() const
495 return m_header
!= 0;
498 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
504 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
506 QGraphicsWidget::paint(painter
, option
, widget
);
508 if (m_rubberBand
->isActive()) {
509 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
510 m_rubberBand
->endPosition()).normalized();
512 const QPointF topLeft
= rubberBandRect
.topLeft();
513 if (scrollOrientation() == Qt::Vertical
) {
514 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
516 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
519 QStyleOptionRubberBand opt
;
520 opt
.initFrom(widget
);
521 opt
.shape
= QRubberBand::Rectangle
;
523 opt
.rect
= rubberBandRect
.toRect();
524 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
528 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
533 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
535 Q_UNUSED(changedRoles
);
539 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
545 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
551 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
557 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
563 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
569 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
575 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
581 void KItemListView::onTransactionBegin()
585 void KItemListView::onTransactionEnd()
589 bool KItemListView::event(QEvent
* event
)
591 // Forward all events to the controller and handle them there
592 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
596 return QGraphicsWidget::event(event
);
599 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
601 m_mousePos
= transform().map(event
->pos());
605 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
607 QGraphicsWidget::mouseMoveEvent(event
);
609 m_mousePos
= transform().map(event
->pos());
610 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
611 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
615 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
617 event
->setAccepted(true);
621 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
623 QGraphicsWidget::dragMoveEvent(event
);
625 m_mousePos
= transform().map(event
->pos());
626 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
627 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
631 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
633 QGraphicsWidget::dragLeaveEvent(event
);
634 setAutoScroll(false);
637 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
639 QGraphicsWidget::dropEvent(event
);
640 setAutoScroll(false);
643 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
645 return m_visibleItems
.values();
648 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
650 QGraphicsWidget::resizeEvent(event
);
651 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
652 QSizeF dynamicItemSize
= m_layouter
->itemSize();
653 const QSizeF newSize
= event
->newSize();
655 if (m_itemSize
.width() < 0) {
656 const qreal requiredWidth
= visibleRolesSizesWidthSum();
657 if (newSize
.width() > requiredWidth
) {
658 dynamicItemSize
.setWidth(newSize
.width());
660 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
661 m_header
->resize(headerWidth
, m_header
->size().height());
664 if (m_itemSize
.height() < 0) {
665 const qreal requiredHeight
= visibleRolesSizesHeightSum();
666 if (newSize
.height() > requiredHeight
) {
667 dynamicItemSize
.setHeight(newSize
.height());
669 // TODO: KItemListHeader is not prepared for vertical alignment
672 m_layouter
->setItemSize(dynamicItemSize
);
676 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
678 updateVisibleRolesSizes(itemRanges
);
680 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
681 if (hasMultipleRanges
) {
685 int previouslyInsertedCount
= 0;
686 foreach (const KItemRange
& range
, itemRanges
) {
687 // range.index is related to the model before anything has been inserted.
688 // As in each loop the current item-range gets inserted the index must
689 // be increased by the already previously inserted items.
690 const int index
= range
.index
+ previouslyInsertedCount
;
691 const int count
= range
.count
;
692 if (index
< 0 || count
<= 0) {
693 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
696 previouslyInsertedCount
+= count
;
698 m_sizeHintResolver
->itemsInserted(index
, count
);
700 // Determine which visible items must be moved
701 QList
<int> itemsToMove
;
702 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
703 while (it
.hasNext()) {
705 const int visibleItemIndex
= it
.key();
706 if (visibleItemIndex
>= index
) {
707 itemsToMove
.append(visibleItemIndex
);
711 // Update the indexes of all KItemListWidget instances that are located
712 // after the inserted items. It is important to adjust the indexes in the order
713 // from the highest index to the lowest index to prevent overlaps when setting the new index.
715 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
716 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
718 setWidgetIndex(widget
, widget
->index() + count
);
721 m_layouter
->markAsDirty();
722 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
723 kDebug() << "Scrollbar required, skipping layout";
724 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
725 QSizeF layouterSize
= m_layouter
->size();
726 if (scrollOrientation() == Qt::Vertical
) {
727 layouterSize
.rwidth() -= scrollBarExtent
;
729 layouterSize
.rheight() -= scrollBarExtent
;
731 m_layouter
->setSize(layouterSize
);
734 if (!hasMultipleRanges
) {
735 doLayout(Animation
, index
, count
);
740 m_controller
->selectionManager()->itemsInserted(itemRanges
);
743 if (hasMultipleRanges
) {
748 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
750 updateVisibleRolesSizes();
752 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
753 if (hasMultipleRanges
) {
757 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
758 const KItemRange
& range
= itemRanges
.at(i
);
759 const int index
= range
.index
;
760 const int count
= range
.count
;
761 if (index
< 0 || count
<= 0) {
762 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
766 m_sizeHintResolver
->itemsRemoved(index
, count
);
768 const int firstRemovedIndex
= index
;
769 const int lastRemovedIndex
= index
+ count
- 1;
770 const int lastIndex
= m_model
->count() + count
- 1;
772 // Remove all KItemListWidget instances that got deleted
773 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
774 KItemListWidget
* widget
= m_visibleItems
.value(i
);
779 m_animation
->stop(widget
);
780 // Stopping the animation might lead to recycling the widget if
781 // it is invisible (see slotAnimationFinished()).
782 // Check again whether it is still visible:
783 if (!m_visibleItems
.contains(i
)) {
787 if (m_model
->count() == 0) {
788 // For performance reasons no animation is done when all items have
790 recycleWidget(widget
);
792 // Animate the removing of the items. Special case: When removing an item there
793 // is no valid model index available anymore. For the
794 // remove-animation the item gets removed from m_visibleItems but the widget
795 // will stay alive until the animation has been finished and will
796 // be recycled (deleted) in KItemListView::slotAnimationFinished().
797 m_visibleItems
.remove(i
);
798 widget
->setIndex(-1);
799 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
803 // Update the indexes of all KItemListWidget instances that are located
804 // after the deleted items
805 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
806 KItemListWidget
* widget
= m_visibleItems
.value(i
);
808 const int newIndex
= i
- count
;
809 setWidgetIndex(widget
, newIndex
);
813 m_layouter
->markAsDirty();
814 if (!hasMultipleRanges
) {
815 doLayout(Animation
, index
, -count
);
820 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
823 if (hasMultipleRanges
) {
828 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
830 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
831 m_layouter
->markAsDirty();
834 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
837 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
838 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
840 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
841 KItemListWidget
* widget
= m_visibleItems
.value(index
);
843 updateWidgetProperties(widget
, index
);
845 updateGroupHeaderForWidget(widget
);
847 initializeItemListWidget(widget
);
851 doLayout(NoAnimation
, 0, 0);
854 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
855 const QSet
<QByteArray
>& roles
)
857 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
858 if (updateSizeHints
) {
859 updateVisibleRolesSizes(itemRanges
);
862 foreach (const KItemRange
& itemRange
, itemRanges
) {
863 const int index
= itemRange
.index
;
864 const int count
= itemRange
.count
;
866 if (updateSizeHints
) {
867 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
868 m_layouter
->markAsDirty();
870 if (!m_layoutTimer
->isActive()) {
871 m_layoutTimer
->start();
875 // Apply the changed roles to the visible item-widgets
876 const int lastIndex
= index
+ count
- 1;
877 for (int i
= index
; i
<= lastIndex
; ++i
) {
878 KItemListWidget
* widget
= m_visibleItems
.value(i
);
880 widget
->setData(m_model
->data(i
), roles
);
884 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
885 // The sort-role has been changed which might result
886 // in modified group headers
887 updateVisibleGroupHeaders();
888 doLayout(NoAnimation
, 0, 0);
893 void KItemListView::slotGroupedSortingChanged(bool current
)
896 m_layouter
->markAsDirty();
899 // Apply the height of the header to the layouter
900 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
901 m_styleOption
.margin
* 2;
902 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
904 updateVisibleGroupHeaders();
906 // Clear all visible headers
907 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
908 while (it
.hasNext()) {
910 recycleGroupHeaderForWidget(it
.key());
912 Q_ASSERT(m_visibleGroups
.isEmpty());
915 doLayout(Animation
, 0, 0);
918 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
923 updateVisibleGroupHeaders();
924 doLayout(Animation
, 0, 0);
928 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
933 updateVisibleGroupHeaders();
934 doLayout(Animation
, 0, 0);
938 void KItemListView::slotCurrentChanged(int current
, int previous
)
942 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
943 if (previousWidget
) {
944 Q_ASSERT(previousWidget
->isCurrent());
945 previousWidget
->setCurrent(false);
948 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
950 Q_ASSERT(!currentWidget
->isCurrent());
951 currentWidget
->setCurrent(true);
954 const QRectF viewGeometry
= geometry();
955 const QRectF currentRect
= itemRect(current
);
957 if (!viewGeometry
.contains(currentRect
)) {
958 // Make sure that the new current item is fully visible in the view.
959 qreal newOffset
= scrollOffset();
960 if (currentRect
.top() < viewGeometry
.top()) {
961 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
962 newOffset
+= currentRect
.top() - viewGeometry
.top();
963 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
964 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
965 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
966 } else if (currentRect
.left() < viewGeometry
.left()) {
967 if (scrollOrientation() == Qt::Horizontal
) {
968 newOffset
+= currentRect
.left() - viewGeometry
.left();
970 } else if ((currentRect
.right() > viewGeometry
.right())) {
971 if (scrollOrientation() == Qt::Horizontal
) {
972 newOffset
+= currentRect
.right() - viewGeometry
.right();
976 if (newOffset
!= scrollOffset()) {
977 emit
scrollTo(newOffset
);
982 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
986 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
987 while (it
.hasNext()) {
989 const int index
= it
.key();
990 KItemListWidget
* widget
= it
.value();
991 widget
->setSelected(current
.contains(index
));
995 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
996 KItemListViewAnimation::AnimationType type
)
998 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
999 Q_ASSERT(itemListWidget
);
1002 case KItemListViewAnimation::DeleteAnimation
: {
1003 // As we recycle the widget in this case it is important to assure that no
1004 // other animation has been started. This is a convention in KItemListView and
1005 // not a requirement defined by KItemListViewAnimation.
1006 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1008 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1009 // by m_visibleWidgets and must be deleted manually after the animation has
1011 recycleGroupHeaderForWidget(itemListWidget
);
1012 m_widgetCreator
->recycle(itemListWidget
);
1016 case KItemListViewAnimation::CreateAnimation
:
1017 case KItemListViewAnimation::MovingAnimation
:
1018 case KItemListViewAnimation::ResizeAnimation
: {
1019 const int index
= itemListWidget
->index();
1020 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1021 (index
> m_layouter
->lastVisibleIndex());
1022 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1023 recycleWidget(itemListWidget
);
1032 void KItemListView::slotLayoutTimerFinished()
1034 m_layouter
->setSize(geometry().size());
1035 doLayout(Animation
, 0, 0);
1038 void KItemListView::slotRubberBandPosChanged()
1043 void KItemListView::slotRubberBandActivationChanged(bool active
)
1046 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1047 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1048 m_skipAutoScrollForRubberBand
= true;
1050 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1051 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1052 m_skipAutoScrollForRubberBand
= false;
1058 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1060 qreal previousWidth
)
1062 Q_UNUSED(previousWidth
);
1064 m_useHeaderWidths
= true;
1066 if (m_visibleRolesSizes
.contains(role
)) {
1067 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1068 roleSize
.setWidth(currentWidth
);
1069 m_visibleRolesSizes
.insert(role
, roleSize
);
1070 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1072 // Apply the new size to the layouter
1073 QSizeF dynamicItemSize
= m_itemSize
;
1074 if (dynamicItemSize
.width() < 0) {
1075 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1076 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1078 if (dynamicItemSize
.height() < 0) {
1079 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1080 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1083 m_layouter
->setItemSize(dynamicItemSize
);
1085 // Update the role sizes for all visible widgets
1086 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1087 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1090 doLayout(Animation
, 0, 0);
1094 void KItemListView::triggerAutoScrolling()
1096 if (!m_autoScrollTimer
) {
1101 int visibleSize
= 0;
1102 if (scrollOrientation() == Qt::Vertical
) {
1103 pos
= m_mousePos
.y();
1104 visibleSize
= size().height();
1106 pos
= m_mousePos
.x();
1107 visibleSize
= size().width();
1110 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1111 m_autoScrollIncrement
= 0;
1114 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1115 if (m_autoScrollIncrement
== 0) {
1116 // The mouse position is not above an autoscroll margin (the autoscroll timer
1117 // will be restarted in mouseMoveEvent())
1118 m_autoScrollTimer
->stop();
1122 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1123 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1124 // if the direction of the rubberband is similar to the autoscroll direction. This
1125 // prevents that starting to create a rubberband within the autoscroll margins starts
1126 // an autoscrolling.
1128 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1129 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1130 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1131 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1132 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1133 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1134 // been moved up although the autoscroll direction might be down)
1135 m_autoScrollTimer
->stop();
1140 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1141 // the autoscrolling may not get skipped anymore until a new rubberband is created
1142 m_skipAutoScrollForRubberBand
= false;
1144 setScrollOffset(scrollOffset() + m_autoScrollIncrement
);
1146 // Trigger the autoscroll timer which will periodically call
1147 // triggerAutoScrolling()
1148 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1151 void KItemListView::setController(KItemListController
* controller
)
1153 if (m_controller
!= controller
) {
1154 KItemListController
* previous
= m_controller
;
1156 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1157 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1158 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1161 m_controller
= controller
;
1164 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1165 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1166 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1169 onControllerChanged(controller
, previous
);
1173 void KItemListView::setModel(KItemModelBase
* model
)
1175 if (m_model
== model
) {
1179 KItemModelBase
* previous
= m_model
;
1182 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1183 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1184 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1185 this, SLOT(slotItemsInserted(KItemRangeList
)));
1186 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1187 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1188 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1189 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1190 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1191 this, SLOT(slotGroupedSortingChanged(bool)));
1192 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1193 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1194 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1195 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1199 m_layouter
->setModel(model
);
1200 m_grouped
= model
->groupedSorting();
1203 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1204 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1205 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1206 this, SLOT(slotItemsInserted(KItemRangeList
)));
1207 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1208 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1209 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1210 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1211 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1212 this, SLOT(slotGroupedSortingChanged(bool)));
1213 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1214 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1215 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1216 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1219 onModelChanged(model
, previous
);
1222 KItemListRubberBand
* KItemListView::rubberBand() const
1224 return m_rubberBand
;
1227 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1229 if (m_layoutTimer
->isActive()) {
1230 kDebug() << "Stopping layout timer, synchronous layout requested";
1231 m_layoutTimer
->stop();
1234 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
1238 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1239 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1240 if (firstVisibleIndex
< 0) {
1241 emitOffsetChanges();
1245 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1246 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1247 // is still shown if the maximum offset got decreased.
1248 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1249 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1250 if (scrollOffset() > maxOffsetToShowFullRange
) {
1251 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1254 // Determine all items that are completely invisible and might be
1255 // reused for items that just got (at least partly) visible.
1256 // Items that do e.g. an animated moving of their position are not
1257 // marked as invisible: This assures that a scrolling inside the view
1258 // can be done without breaking an animation.
1259 QList
<int> reusableItems
;
1260 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1261 while (it
.hasNext()) {
1263 KItemListWidget
* widget
= it
.value();
1264 const int index
= widget
->index();
1265 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1266 if (invisible
&& !m_animation
->isStarted(widget
)) {
1267 widget
->setVisible(false);
1268 reusableItems
.append(index
);
1271 recycleGroupHeaderForWidget(widget
);
1276 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1277 // instances from invisible items are reused. If no reusable items are
1278 // found then new KItemListWidget instances get created.
1279 const bool animate
= (hint
== Animation
);
1280 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1281 bool applyNewPos
= true;
1282 bool wasHidden
= false;
1284 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1285 const QPointF newPos
= itemBounds
.topLeft();
1286 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1289 if (!reusableItems
.isEmpty()) {
1290 // Reuse a KItemListWidget instance from an invisible item
1291 const int oldIndex
= reusableItems
.takeLast();
1292 widget
= m_visibleItems
.value(oldIndex
);
1293 setWidgetIndex(widget
, i
);
1296 updateGroupHeaderForWidget(widget
);
1299 // No reusable KItemListWidget instance is available, create a new one
1300 widget
= createWidget(i
);
1302 widget
->resize(itemBounds
.size());
1304 if (animate
&& changedCount
< 0) {
1305 // Items have been deleted, move the created item to the
1306 // imaginary old position.
1307 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1308 if (itemRect
.isEmpty()) {
1309 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1310 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1311 widget
->setPos(invisibleOldPos
);
1313 widget
->setPos(itemRect
.topLeft());
1315 applyNewPos
= false;
1317 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1318 applyNewPos
= false;
1322 const bool itemsRemoved
= (changedCount
< 0);
1323 const bool itemsInserted
= (changedCount
> 0);
1325 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1326 // The item is located after the removed items. Animate the moving of the position.
1327 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1328 applyNewPos
= false;
1329 } else if (itemsInserted
&& i
>= changedIndex
) {
1330 // The item is located after the first inserted item
1331 if (i
<= changedIndex
+ changedCount
- 1) {
1332 // The item is an inserted item. Animate the appearing of the item.
1333 // For performance reasons no animation is done when changedCount is equal
1334 // to all available items.
1335 if (changedCount
< m_model
->count()) {
1336 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1338 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1339 // The item was already there before, so animate the moving of the position.
1340 // No moving animation is done if the item is animated by a create animation: This
1341 // prevents a "move animation mess" when inserting several ranges in parallel.
1342 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1343 applyNewPos
= false;
1345 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1346 // The size of the view might have been changed. Animate the moving of the position.
1347 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1348 applyNewPos
= false;
1353 widget
->setPos(newPos
);
1356 Q_ASSERT(widget
->index() == i
);
1357 widget
->setVisible(true);
1359 if (widget
->size() != itemBounds
.size()) {
1361 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1363 widget
->resize(itemBounds
.size());
1368 // Delete invisible KItemListWidget instances that have not been reused
1369 foreach (int index
, reusableItems
) {
1370 recycleWidget(m_visibleItems
.value(index
));
1374 // Update the layout of all visible group headers
1375 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1376 while (it
.hasNext()) {
1378 updateGroupHeaderLayout(it
.key());
1382 emitOffsetChanges();
1385 void KItemListView::emitOffsetChanges()
1387 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1388 if (m_oldScrollOffset
!= newScrollOffset
) {
1389 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1390 m_oldScrollOffset
= newScrollOffset
;
1393 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1394 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1395 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1396 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1399 const qreal newItemOffset
= m_layouter
->itemOffset();
1400 if (m_oldItemOffset
!= newItemOffset
) {
1401 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1402 m_oldItemOffset
= newItemOffset
;
1405 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1406 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1407 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1408 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1412 KItemListWidget
* KItemListView::createWidget(int index
)
1414 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1415 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1417 updateWidgetProperties(widget
, index
);
1418 m_visibleItems
.insert(index
, widget
);
1421 updateGroupHeaderForWidget(widget
);
1424 initializeItemListWidget(widget
);
1428 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1431 recycleGroupHeaderForWidget(widget
);
1434 m_visibleItems
.remove(widget
->index());
1435 m_widgetCreator
->recycle(widget
);
1438 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1440 const int oldIndex
= widget
->index();
1441 m_visibleItems
.remove(oldIndex
);
1442 updateWidgetProperties(widget
, index
);
1443 m_visibleItems
.insert(index
, widget
);
1445 initializeItemListWidget(widget
);
1448 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1450 // Calculate the first visible index and last visible index for the current size
1451 const int currentFirst
= m_layouter
->firstVisibleIndex();
1452 const int currentLast
= m_layouter
->lastVisibleIndex();
1454 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1456 // Calculate the first visible index and last visible index for the new size
1457 setLayouterSize(size
, sizeType
);
1458 const int newFirst
= m_layouter
->firstVisibleIndex();
1459 const int newLast
= m_layouter
->lastVisibleIndex();
1461 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1462 // At least one index has been changed. Assure that widgets for all possible
1463 // visible items get created so that a move-animation can be started later.
1464 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1465 int minFirst
= qMin(newFirst
, currentFirst
);
1466 const int maxLast
= qMax(newLast
, currentLast
);
1468 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1469 // Increasing the size might result in a smaller KItemListView::offset().
1470 // Decrease the first visible index in a way that at least the maximum
1471 // visible items are shown.
1472 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1475 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1476 // The creating of widgets is quite expensive. Assure that never more
1477 // than 50 % of the maximum visible items get created for the animations.
1481 setLayouterSize(currentSize
, sizeType
);
1482 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1483 if (!m_visibleItems
.contains(i
)) {
1484 KItemListWidget
* widget
= createWidget(i
);
1485 const QRectF itemRect
= m_layouter
->itemRect(i
);
1486 widget
->setPos(itemRect
.topLeft());
1487 widget
->resize(itemRect
.size());
1490 setLayouterSize(size
, sizeType
);
1494 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1497 case LayouterSize
: m_layouter
->setSize(size
); break;
1498 case ItemSize
: m_layouter
->setItemSize(size
); break;
1503 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1505 widget
->setVisibleRoles(m_visibleRoles
);
1506 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1507 widget
->setStyleOption(m_styleOption
);
1509 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1510 widget
->setCurrent(index
== selectionManager
->currentItem());
1511 widget
->setSelected(selectionManager
->isSelected(index
));
1512 widget
->setHovered(false);
1513 widget
->setAlternatingBackgroundColors(false);
1514 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1515 widget
->setIndex(index
);
1516 widget
->setData(m_model
->data(index
));
1519 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1521 Q_ASSERT(m_grouped
);
1523 const int index
= widget
->index();
1524 if (!m_layouter
->isFirstGroupItem(index
)) {
1525 // The widget does not represent the first item of a group
1526 // and hence requires no header
1527 recycleGroupHeaderForWidget(widget
);
1531 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1532 if (groups
.isEmpty()) {
1536 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1538 header
= m_groupHeaderCreator
->create(this);
1539 header
->setParentItem(widget
);
1540 m_visibleGroups
.insert(widget
, header
);
1542 Q_ASSERT(header
->parentItem() == widget
);
1544 // Determine the shown data for the header by doing a binary
1545 // search in the groups-list
1547 int max
= groups
.count() - 1;
1550 mid
= (min
+ max
) / 2;
1551 if (index
> groups
.at(mid
).first
) {
1556 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1558 header
->setData(groups
.at(mid
).second
);
1559 header
->setRole(model()->sortRole());
1560 header
->setStyleOption(m_styleOption
);
1561 header
->setScrollOrientation(scrollOrientation());
1566 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1568 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1571 const int index
= widget
->index();
1572 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1573 const QRectF itemRect
= m_layouter
->itemRect(index
);
1575 // The group-header is a child of the itemlist widget. Translate the
1576 // group header position to the relative position.
1577 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1578 - groupHeaderRect
.height());
1579 header
->setPos(groupHeaderPos
);
1580 header
->resize(groupHeaderRect
.size());
1583 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1585 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1587 header
->setParentItem(0);
1588 m_groupHeaderCreator
->recycle(header
);
1589 m_visibleGroups
.remove(widget
);
1593 void KItemListView::updateVisibleGroupHeaders()
1595 Q_ASSERT(m_grouped
);
1596 m_layouter
->markAsDirty();
1598 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1599 while (it
.hasNext()) {
1601 updateGroupHeaderForWidget(it
.value());
1605 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1607 QHash
<QByteArray
, qreal
> rolesWidths
;
1609 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1610 while (it
.hasNext()) {
1612 rolesWidths
.insert(it
.key(), it
.value().width());
1618 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1620 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1624 const int itemCount
= m_model
->count();
1625 int rangesItemCount
= 0;
1626 foreach (const KItemRange
& range
, itemRanges
) {
1627 rangesItemCount
+= range
.count
;
1630 if (itemCount
== rangesItemCount
) {
1631 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1633 // Assure the the sizes are not smaller than the minimum defined by the header
1634 // TODO: Currently only implemented for a top-aligned header
1635 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1636 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1637 while (it
.hasNext()) {
1639 const QSizeF
& size
= it
.value();
1640 if (size
.width() < minHeaderRoleWidth
) {
1641 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1642 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1647 // Only a sub range of the roles need to be determined.
1648 // The chances are good that the sizes of the sub ranges
1649 // already fit into the available sizes and hence no
1650 // expensive update might be required.
1651 bool updateRequired
= false;
1653 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1654 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1655 while (it
.hasNext()) {
1657 const QByteArray
& role
= it
.key();
1658 const QSizeF
& updatedSize
= it
.value();
1659 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1660 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1661 m_visibleRolesSizes
.insert(role
, updatedSize
);
1662 updateRequired
= true;
1666 if (!updateRequired
) {
1667 // All the updated sizes are smaller than the current sizes and no change
1668 // of the stretched roles-widths is required
1673 updateStretchedVisibleRolesSizes();
1676 void KItemListView::updateVisibleRolesSizes()
1678 const int itemCount
= m_model
->count();
1679 if (itemCount
> 0) {
1680 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1684 void KItemListView::updateStretchedVisibleRolesSizes()
1686 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1690 // Calculate the maximum size of an item by considering the
1691 // visible role sizes and apply them to the layouter. If the
1692 // size does not use the available view-size it the size of the
1693 // first role will get stretched.
1694 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1695 const QByteArray role
= visibleRoles().first();
1696 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1698 QSizeF dynamicItemSize
= m_itemSize
;
1700 if (dynamicItemSize
.width() <= 0) {
1701 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1702 const qreal availableWidth
= size().width();
1703 if (requiredWidth
< availableWidth
) {
1704 // Stretch the first role to use the whole width for the item
1705 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1706 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1708 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1711 if (dynamicItemSize
.height() <= 0) {
1712 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1713 const qreal availableHeight
= size().height();
1714 if (requiredHeight
< availableHeight
) {
1715 // Stretch the first role to use the whole height for the item
1716 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1717 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1719 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1722 m_layouter
->setItemSize(dynamicItemSize
);
1725 m_header
->setVisibleRolesWidths(headerRolesWidths());
1726 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1729 // Update the role sizes for all visible widgets
1730 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1731 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1735 qreal
KItemListView::visibleRolesSizesWidthSum() const
1738 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1739 while (it
.hasNext()) {
1741 widthSum
+= it
.value().width();
1746 qreal
KItemListView::visibleRolesSizesHeightSum() const
1748 qreal heightSum
= 0;
1749 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1750 while (it
.hasNext()) {
1752 heightSum
+= it
.value().height();
1757 QRectF
KItemListView::headerBoundaries() const
1759 return m_header
? m_header
->geometry() : QRectF();
1762 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1766 const int minSpeed
= 4;
1767 const int maxSpeed
= 128;
1768 const int speedLimiter
= 96;
1769 const int autoScrollBorder
= 64;
1771 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1772 // This assures that the autoscrolling speed grows gradually.
1773 const int incLimiter
= 1;
1775 if (pos
< autoScrollBorder
) {
1776 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1777 inc
= qMax(inc
, -maxSpeed
);
1778 inc
= qMax(inc
, oldInc
- incLimiter
);
1779 } else if (pos
> range
- autoScrollBorder
) {
1780 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1781 inc
= qMin(inc
, maxSpeed
);
1782 inc
= qMin(inc
, oldInc
+ incLimiter
);
1790 KItemListCreatorBase::~KItemListCreatorBase()
1792 qDeleteAll(m_recycleableWidgets
);
1793 qDeleteAll(m_createdWidgets
);
1796 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1798 m_createdWidgets
.insert(widget
);
1801 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1803 Q_ASSERT(m_createdWidgets
.contains(widget
));
1804 m_createdWidgets
.remove(widget
);
1806 if (m_recycleableWidgets
.count() < 100) {
1807 m_recycleableWidgets
.append(widget
);
1808 widget
->setVisible(false);
1814 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1816 if (m_recycleableWidgets
.isEmpty()) {
1820 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1821 m_createdWidgets
.insert(widget
);
1825 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1829 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1831 widget
->setParentItem(0);
1832 widget
->setOpacity(1.0);
1833 pushRecycleableWidget(widget
);
1836 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1840 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1842 header
->setOpacity(1.0);
1843 pushRecycleableWidget(header
);
1846 #include "kitemlistview.moc"