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 bool KItemListView::supportsItemExpanding() const
435 QRectF
KItemListView::itemRect(int index
) const
437 return m_layouter
->itemRect(index
);
440 QRectF
KItemListView::itemContextRect(int index
) const
444 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
446 contextRect
= widget
->iconRect() | widget
->textRect();
447 contextRect
.translate(itemRect(index
).topLeft());
453 void KItemListView::scrollToItem(int index
)
455 const QRectF viewGeometry
= geometry();
456 const QRectF currentRect
= itemRect(index
);
458 if (!viewGeometry
.contains(currentRect
)) {
459 qreal newOffset
= scrollOffset();
460 if (currentRect
.top() < viewGeometry
.top()) {
461 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
462 newOffset
+= currentRect
.top() - viewGeometry
.top();
463 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
464 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
465 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
466 } else if (currentRect
.left() < viewGeometry
.left()) {
467 if (scrollOrientation() == Qt::Horizontal
) {
468 newOffset
+= currentRect
.left() - viewGeometry
.left();
470 } else if ((currentRect
.right() > viewGeometry
.right())) {
471 if (scrollOrientation() == Qt::Horizontal
) {
472 newOffset
+= currentRect
.right() - viewGeometry
.right();
476 if (newOffset
!= scrollOffset()) {
477 emit
scrollTo(newOffset
);
482 int KItemListView::itemsPerOffset() const
484 return m_layouter
->itemsPerOffset();
487 void KItemListView::beginTransaction()
489 ++m_activeTransactions
;
490 if (m_activeTransactions
== 1) {
491 onTransactionBegin();
495 void KItemListView::endTransaction()
497 --m_activeTransactions
;
498 if (m_activeTransactions
< 0) {
499 m_activeTransactions
= 0;
500 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
503 if (m_activeTransactions
== 0) {
505 doLayout(Animation
, 0, 0);
509 bool KItemListView::isTransactionActive() const
511 return m_activeTransactions
> 0;
515 void KItemListView::setHeaderShown(bool show
)
518 if (show
&& !m_header
) {
519 m_header
= new KItemListHeader(this);
520 m_header
->setPos(0, 0);
521 m_header
->setModel(m_model
);
522 m_header
->setVisibleRoles(m_visibleRoles
);
523 m_header
->setVisibleRolesWidths(headerRolesWidths());
524 m_header
->setZValue(1);
526 m_useHeaderWidths
= false;
528 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
529 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
531 m_layouter
->setHeaderHeight(m_header
->size().height());
532 } else if (!show
&& m_header
) {
535 m_useHeaderWidths
= false;
536 m_layouter
->setHeaderHeight(0);
540 bool KItemListView::isHeaderShown() const
542 return m_header
!= 0;
545 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
551 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
553 QGraphicsWidget::paint(painter
, option
, widget
);
555 if (m_rubberBand
->isActive()) {
556 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
557 m_rubberBand
->endPosition()).normalized();
559 const QPointF topLeft
= rubberBandRect
.topLeft();
560 if (scrollOrientation() == Qt::Vertical
) {
561 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
563 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
566 QStyleOptionRubberBand opt
;
567 opt
.initFrom(widget
);
568 opt
.shape
= QRubberBand::Rectangle
;
570 opt
.rect
= rubberBandRect
.toRect();
571 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
575 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
580 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
582 Q_UNUSED(changedRoles
);
586 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
592 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
598 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
604 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
610 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
616 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
622 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
628 void KItemListView::onTransactionBegin()
632 void KItemListView::onTransactionEnd()
636 bool KItemListView::event(QEvent
* event
)
638 // Forward all events to the controller and handle them there
639 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
643 return QGraphicsWidget::event(event
);
646 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
648 m_mousePos
= transform().map(event
->pos());
652 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
654 QGraphicsWidget::mouseMoveEvent(event
);
656 m_mousePos
= transform().map(event
->pos());
657 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
658 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
662 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
664 event
->setAccepted(true);
668 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
670 QGraphicsWidget::dragMoveEvent(event
);
672 m_mousePos
= transform().map(event
->pos());
673 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
674 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
678 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
680 QGraphicsWidget::dragLeaveEvent(event
);
681 setAutoScroll(false);
684 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
686 QGraphicsWidget::dropEvent(event
);
687 setAutoScroll(false);
690 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
692 return m_visibleItems
.values();
695 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
697 QGraphicsWidget::resizeEvent(event
);
698 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
699 QSizeF dynamicItemSize
= m_layouter
->itemSize();
700 const QSizeF newSize
= event
->newSize();
702 if (m_itemSize
.width() < 0) {
703 const qreal requiredWidth
= visibleRolesSizesWidthSum();
704 if (newSize
.width() > requiredWidth
) {
705 dynamicItemSize
.setWidth(newSize
.width());
707 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
708 m_header
->resize(headerWidth
, m_header
->size().height());
711 if (m_itemSize
.height() < 0) {
712 const qreal requiredHeight
= visibleRolesSizesHeightSum();
713 if (newSize
.height() > requiredHeight
) {
714 dynamicItemSize
.setHeight(newSize
.height());
716 // TODO: KItemListHeader is not prepared for vertical alignment
719 m_layouter
->setItemSize(dynamicItemSize
);
723 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
725 updateVisibleRolesSizes(itemRanges
);
727 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
728 if (hasMultipleRanges
) {
732 int previouslyInsertedCount
= 0;
733 foreach (const KItemRange
& range
, itemRanges
) {
734 // range.index is related to the model before anything has been inserted.
735 // As in each loop the current item-range gets inserted the index must
736 // be increased by the already previously inserted items.
737 const int index
= range
.index
+ previouslyInsertedCount
;
738 const int count
= range
.count
;
739 if (index
< 0 || count
<= 0) {
740 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
743 previouslyInsertedCount
+= count
;
745 m_sizeHintResolver
->itemsInserted(index
, count
);
747 // Determine which visible items must be moved
748 QList
<int> itemsToMove
;
749 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
750 while (it
.hasNext()) {
752 const int visibleItemIndex
= it
.key();
753 if (visibleItemIndex
>= index
) {
754 itemsToMove
.append(visibleItemIndex
);
758 // Update the indexes of all KItemListWidget instances that are located
759 // after the inserted items. It is important to adjust the indexes in the order
760 // from the highest index to the lowest index to prevent overlaps when setting the new index.
762 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
763 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
765 setWidgetIndex(widget
, widget
->index() + count
);
768 m_layouter
->markAsDirty();
769 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
770 kDebug() << "Scrollbar required, skipping layout";
771 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
772 QSizeF layouterSize
= m_layouter
->size();
773 if (scrollOrientation() == Qt::Vertical
) {
774 layouterSize
.rwidth() -= scrollBarExtent
;
776 layouterSize
.rheight() -= scrollBarExtent
;
778 m_layouter
->setSize(layouterSize
);
781 if (!hasMultipleRanges
) {
782 doLayout(Animation
, index
, count
);
787 m_controller
->selectionManager()->itemsInserted(itemRanges
);
790 if (hasMultipleRanges
) {
795 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
797 updateVisibleRolesSizes();
799 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
800 if (hasMultipleRanges
) {
804 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
805 const KItemRange
& range
= itemRanges
.at(i
);
806 const int index
= range
.index
;
807 const int count
= range
.count
;
808 if (index
< 0 || count
<= 0) {
809 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
813 m_sizeHintResolver
->itemsRemoved(index
, count
);
815 const int firstRemovedIndex
= index
;
816 const int lastRemovedIndex
= index
+ count
- 1;
817 const int lastIndex
= m_model
->count() + count
- 1;
819 // Remove all KItemListWidget instances that got deleted
820 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
821 KItemListWidget
* widget
= m_visibleItems
.value(i
);
826 m_animation
->stop(widget
);
827 // Stopping the animation might lead to recycling the widget if
828 // it is invisible (see slotAnimationFinished()).
829 // Check again whether it is still visible:
830 if (!m_visibleItems
.contains(i
)) {
834 if (m_model
->count() == 0) {
835 // For performance reasons no animation is done when all items have
837 recycleWidget(widget
);
839 // Animate the removing of the items. Special case: When removing an item there
840 // is no valid model index available anymore. For the
841 // remove-animation the item gets removed from m_visibleItems but the widget
842 // will stay alive until the animation has been finished and will
843 // be recycled (deleted) in KItemListView::slotAnimationFinished().
844 m_visibleItems
.remove(i
);
845 widget
->setIndex(-1);
846 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
850 // Update the indexes of all KItemListWidget instances that are located
851 // after the deleted items
852 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
853 KItemListWidget
* widget
= m_visibleItems
.value(i
);
855 const int newIndex
= i
- count
;
856 setWidgetIndex(widget
, newIndex
);
860 m_layouter
->markAsDirty();
861 if (!hasMultipleRanges
) {
862 doLayout(Animation
, index
, -count
);
867 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
870 if (hasMultipleRanges
) {
875 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
877 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
878 m_layouter
->markAsDirty();
881 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
884 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
885 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
887 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
888 KItemListWidget
* widget
= m_visibleItems
.value(index
);
890 updateWidgetProperties(widget
, index
);
892 updateGroupHeaderForWidget(widget
);
894 initializeItemListWidget(widget
);
898 doLayout(NoAnimation
, 0, 0);
901 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
902 const QSet
<QByteArray
>& roles
)
904 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
905 if (updateSizeHints
) {
906 updateVisibleRolesSizes(itemRanges
);
909 foreach (const KItemRange
& itemRange
, itemRanges
) {
910 const int index
= itemRange
.index
;
911 const int count
= itemRange
.count
;
913 if (updateSizeHints
) {
914 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
915 m_layouter
->markAsDirty();
917 if (!m_layoutTimer
->isActive()) {
918 m_layoutTimer
->start();
922 // Apply the changed roles to the visible item-widgets
923 const int lastIndex
= index
+ count
- 1;
924 for (int i
= index
; i
<= lastIndex
; ++i
) {
925 KItemListWidget
* widget
= m_visibleItems
.value(i
);
927 widget
->setData(m_model
->data(i
), roles
);
931 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
932 // The sort-role has been changed which might result
933 // in modified group headers
934 updateVisibleGroupHeaders();
935 doLayout(NoAnimation
, 0, 0);
940 void KItemListView::slotGroupedSortingChanged(bool current
)
943 m_layouter
->markAsDirty();
946 // Apply the height of the header to the layouter
947 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
948 m_styleOption
.margin
* 2;
949 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
951 updateVisibleGroupHeaders();
953 // Clear all visible headers
954 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
955 while (it
.hasNext()) {
957 recycleGroupHeaderForWidget(it
.key());
959 Q_ASSERT(m_visibleGroups
.isEmpty());
962 doLayout(Animation
, 0, 0);
965 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
970 updateVisibleGroupHeaders();
971 doLayout(Animation
, 0, 0);
975 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
980 updateVisibleGroupHeaders();
981 doLayout(Animation
, 0, 0);
985 void KItemListView::slotCurrentChanged(int current
, int previous
)
989 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
990 if (previousWidget
) {
991 Q_ASSERT(previousWidget
->isCurrent());
992 previousWidget
->setCurrent(false);
995 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
997 Q_ASSERT(!currentWidget
->isCurrent());
998 currentWidget
->setCurrent(true);
1002 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1006 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1007 while (it
.hasNext()) {
1009 const int index
= it
.key();
1010 KItemListWidget
* widget
= it
.value();
1011 widget
->setSelected(current
.contains(index
));
1015 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1016 KItemListViewAnimation::AnimationType type
)
1018 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1019 Q_ASSERT(itemListWidget
);
1022 case KItemListViewAnimation::DeleteAnimation
: {
1023 // As we recycle the widget in this case it is important to assure that no
1024 // other animation has been started. This is a convention in KItemListView and
1025 // not a requirement defined by KItemListViewAnimation.
1026 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1028 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1029 // by m_visibleWidgets and must be deleted manually after the animation has
1031 recycleGroupHeaderForWidget(itemListWidget
);
1032 m_widgetCreator
->recycle(itemListWidget
);
1036 case KItemListViewAnimation::CreateAnimation
:
1037 case KItemListViewAnimation::MovingAnimation
:
1038 case KItemListViewAnimation::ResizeAnimation
: {
1039 const int index
= itemListWidget
->index();
1040 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1041 (index
> m_layouter
->lastVisibleIndex());
1042 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1043 recycleWidget(itemListWidget
);
1052 void KItemListView::slotLayoutTimerFinished()
1054 m_layouter
->setSize(geometry().size());
1055 doLayout(Animation
, 0, 0);
1058 void KItemListView::slotRubberBandPosChanged()
1063 void KItemListView::slotRubberBandActivationChanged(bool active
)
1066 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1067 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1068 m_skipAutoScrollForRubberBand
= true;
1070 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1071 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1072 m_skipAutoScrollForRubberBand
= false;
1078 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1080 qreal previousWidth
)
1082 Q_UNUSED(previousWidth
);
1084 m_useHeaderWidths
= true;
1086 if (m_visibleRolesSizes
.contains(role
)) {
1087 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1088 roleSize
.setWidth(currentWidth
);
1089 m_visibleRolesSizes
.insert(role
, roleSize
);
1090 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1092 // Apply the new size to the layouter
1093 QSizeF dynamicItemSize
= m_itemSize
;
1094 if (dynamicItemSize
.width() < 0) {
1095 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1096 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1098 if (dynamicItemSize
.height() < 0) {
1099 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1100 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1103 m_layouter
->setItemSize(dynamicItemSize
);
1105 // Update the role sizes for all visible widgets
1106 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1107 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1110 doLayout(Animation
, 0, 0);
1114 void KItemListView::triggerAutoScrolling()
1116 if (!m_autoScrollTimer
) {
1121 int visibleSize
= 0;
1122 if (scrollOrientation() == Qt::Vertical
) {
1123 pos
= m_mousePos
.y();
1124 visibleSize
= size().height();
1126 pos
= m_mousePos
.x();
1127 visibleSize
= size().width();
1130 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1131 m_autoScrollIncrement
= 0;
1134 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1135 if (m_autoScrollIncrement
== 0) {
1136 // The mouse position is not above an autoscroll margin (the autoscroll timer
1137 // will be restarted in mouseMoveEvent())
1138 m_autoScrollTimer
->stop();
1142 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1143 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1144 // if the direction of the rubberband is similar to the autoscroll direction. This
1145 // prevents that starting to create a rubberband within the autoscroll margins starts
1146 // an autoscrolling.
1148 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1149 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1150 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1151 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1152 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1153 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1154 // been moved up although the autoscroll direction might be down)
1155 m_autoScrollTimer
->stop();
1160 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1161 // the autoscrolling may not get skipped anymore until a new rubberband is created
1162 m_skipAutoScrollForRubberBand
= false;
1164 setScrollOffset(scrollOffset() + m_autoScrollIncrement
);
1166 // Trigger the autoscroll timer which will periodically call
1167 // triggerAutoScrolling()
1168 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1171 void KItemListView::setController(KItemListController
* controller
)
1173 if (m_controller
!= controller
) {
1174 KItemListController
* previous
= m_controller
;
1176 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1177 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1178 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1181 m_controller
= controller
;
1184 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1185 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1186 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1189 onControllerChanged(controller
, previous
);
1193 void KItemListView::setModel(KItemModelBase
* model
)
1195 if (m_model
== model
) {
1199 KItemModelBase
* previous
= m_model
;
1202 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1203 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1204 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1205 this, SLOT(slotItemsInserted(KItemRangeList
)));
1206 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1207 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1208 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1209 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1210 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1211 this, SLOT(slotGroupedSortingChanged(bool)));
1212 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1213 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1214 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1215 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1219 m_layouter
->setModel(model
);
1220 m_grouped
= model
->groupedSorting();
1223 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1224 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1225 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1226 this, SLOT(slotItemsInserted(KItemRangeList
)));
1227 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1228 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1229 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1230 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1231 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1232 this, SLOT(slotGroupedSortingChanged(bool)));
1233 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1234 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1235 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1236 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1239 onModelChanged(model
, previous
);
1242 KItemListRubberBand
* KItemListView::rubberBand() const
1244 return m_rubberBand
;
1247 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1249 if (m_layoutTimer
->isActive()) {
1250 kDebug() << "Stopping layout timer, synchronous layout requested";
1251 m_layoutTimer
->stop();
1254 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1258 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1259 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1260 if (firstVisibleIndex
< 0) {
1261 emitOffsetChanges();
1265 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1266 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1267 // is still shown if the maximum offset got decreased.
1268 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1269 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1270 if (scrollOffset() > maxOffsetToShowFullRange
) {
1271 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1274 // Determine all items that are completely invisible and might be
1275 // reused for items that just got (at least partly) visible.
1276 // Items that do e.g. an animated moving of their position are not
1277 // marked as invisible: This assures that a scrolling inside the view
1278 // can be done without breaking an animation.
1279 QList
<int> reusableItems
;
1280 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1281 while (it
.hasNext()) {
1283 KItemListWidget
* widget
= it
.value();
1284 const int index
= widget
->index();
1285 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1286 if (invisible
&& !m_animation
->isStarted(widget
)) {
1287 widget
->setVisible(false);
1288 reusableItems
.append(index
);
1291 recycleGroupHeaderForWidget(widget
);
1296 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1297 // instances from invisible items are reused. If no reusable items are
1298 // found then new KItemListWidget instances get created.
1299 const bool animate
= (hint
== Animation
);
1300 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1301 bool applyNewPos
= true;
1302 bool wasHidden
= false;
1304 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1305 const QPointF newPos
= itemBounds
.topLeft();
1306 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1309 if (!reusableItems
.isEmpty()) {
1310 // Reuse a KItemListWidget instance from an invisible item
1311 const int oldIndex
= reusableItems
.takeLast();
1312 widget
= m_visibleItems
.value(oldIndex
);
1313 setWidgetIndex(widget
, i
);
1316 updateGroupHeaderForWidget(widget
);
1319 // No reusable KItemListWidget instance is available, create a new one
1320 widget
= createWidget(i
);
1322 widget
->resize(itemBounds
.size());
1324 if (animate
&& changedCount
< 0) {
1325 // Items have been deleted, move the created item to the
1326 // imaginary old position.
1327 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1328 if (itemRect
.isEmpty()) {
1329 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1330 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1331 widget
->setPos(invisibleOldPos
);
1333 widget
->setPos(itemRect
.topLeft());
1335 applyNewPos
= false;
1337 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1338 applyNewPos
= false;
1342 const bool itemsRemoved
= (changedCount
< 0);
1343 const bool itemsInserted
= (changedCount
> 0);
1345 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1346 // The item is located after the removed items. Animate the moving of the position.
1347 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1348 applyNewPos
= false;
1349 } else if (itemsInserted
&& i
>= changedIndex
) {
1350 // The item is located after the first inserted item
1351 if (i
<= changedIndex
+ changedCount
- 1) {
1352 // The item is an inserted item. Animate the appearing of the item.
1353 // For performance reasons no animation is done when changedCount is equal
1354 // to all available items.
1355 if (changedCount
< m_model
->count()) {
1356 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1358 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1359 // The item was already there before, so animate the moving of the position.
1360 // No moving animation is done if the item is animated by a create animation: This
1361 // prevents a "move animation mess" when inserting several ranges in parallel.
1362 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1363 applyNewPos
= false;
1365 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1366 // The size of the view might have been changed. Animate the moving of the position.
1367 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1368 applyNewPos
= false;
1373 widget
->setPos(newPos
);
1376 Q_ASSERT(widget
->index() == i
);
1377 widget
->setVisible(true);
1379 if (widget
->size() != itemBounds
.size()) {
1381 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1383 widget
->resize(itemBounds
.size());
1388 // Delete invisible KItemListWidget instances that have not been reused
1389 foreach (int index
, reusableItems
) {
1390 recycleWidget(m_visibleItems
.value(index
));
1394 // Update the layout of all visible group headers
1395 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1396 while (it
.hasNext()) {
1398 updateGroupHeaderLayout(it
.key());
1402 emitOffsetChanges();
1405 void KItemListView::emitOffsetChanges()
1407 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1408 if (m_oldScrollOffset
!= newScrollOffset
) {
1409 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1410 m_oldScrollOffset
= newScrollOffset
;
1413 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1414 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1415 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1416 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1419 const qreal newItemOffset
= m_layouter
->itemOffset();
1420 if (m_oldItemOffset
!= newItemOffset
) {
1421 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1422 m_oldItemOffset
= newItemOffset
;
1425 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1426 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1427 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1428 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1432 KItemListWidget
* KItemListView::createWidget(int index
)
1434 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1435 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1437 updateWidgetProperties(widget
, index
);
1438 m_visibleItems
.insert(index
, widget
);
1441 updateGroupHeaderForWidget(widget
);
1444 initializeItemListWidget(widget
);
1448 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1451 recycleGroupHeaderForWidget(widget
);
1454 m_visibleItems
.remove(widget
->index());
1455 m_widgetCreator
->recycle(widget
);
1458 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1460 const int oldIndex
= widget
->index();
1461 m_visibleItems
.remove(oldIndex
);
1462 updateWidgetProperties(widget
, index
);
1463 m_visibleItems
.insert(index
, widget
);
1465 initializeItemListWidget(widget
);
1468 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1470 // Calculate the first visible index and last visible index for the current size
1471 const int currentFirst
= m_layouter
->firstVisibleIndex();
1472 const int currentLast
= m_layouter
->lastVisibleIndex();
1474 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1476 // Calculate the first visible index and last visible index for the new size
1477 setLayouterSize(size
, sizeType
);
1478 const int newFirst
= m_layouter
->firstVisibleIndex();
1479 const int newLast
= m_layouter
->lastVisibleIndex();
1481 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1482 // At least one index has been changed. Assure that widgets for all possible
1483 // visible items get created so that a move-animation can be started later.
1484 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1485 int minFirst
= qMin(newFirst
, currentFirst
);
1486 const int maxLast
= qMax(newLast
, currentLast
);
1488 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1489 // Increasing the size might result in a smaller KItemListView::offset().
1490 // Decrease the first visible index in a way that at least the maximum
1491 // visible items are shown.
1492 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1495 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1496 // The creating of widgets is quite expensive. Assure that never more
1497 // than 50 % of the maximum visible items get created for the animations.
1501 setLayouterSize(currentSize
, sizeType
);
1502 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1503 if (!m_visibleItems
.contains(i
)) {
1504 KItemListWidget
* widget
= createWidget(i
);
1505 const QRectF itemRect
= m_layouter
->itemRect(i
);
1506 widget
->setPos(itemRect
.topLeft());
1507 widget
->resize(itemRect
.size());
1510 setLayouterSize(size
, sizeType
);
1514 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1517 case LayouterSize
: m_layouter
->setSize(size
); break;
1518 case ItemSize
: m_layouter
->setItemSize(size
); break;
1523 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1525 widget
->setVisibleRoles(m_visibleRoles
);
1526 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1527 widget
->setStyleOption(m_styleOption
);
1529 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1530 widget
->setCurrent(index
== selectionManager
->currentItem());
1531 widget
->setSelected(selectionManager
->isSelected(index
));
1532 widget
->setHovered(false);
1533 widget
->setAlternatingBackgroundColors(false);
1534 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1535 widget
->setIndex(index
);
1536 widget
->setData(m_model
->data(index
));
1539 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1541 Q_ASSERT(m_grouped
);
1543 const int index
= widget
->index();
1544 if (!m_layouter
->isFirstGroupItem(index
)) {
1545 // The widget does not represent the first item of a group
1546 // and hence requires no header
1547 recycleGroupHeaderForWidget(widget
);
1551 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1552 if (groups
.isEmpty()) {
1556 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1558 header
= m_groupHeaderCreator
->create(this);
1559 header
->setParentItem(widget
);
1560 m_visibleGroups
.insert(widget
, header
);
1562 Q_ASSERT(header
->parentItem() == widget
);
1564 // Determine the shown data for the header by doing a binary
1565 // search in the groups-list
1567 int max
= groups
.count() - 1;
1570 mid
= (min
+ max
) / 2;
1571 if (index
> groups
.at(mid
).first
) {
1576 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1578 header
->setData(groups
.at(mid
).second
);
1579 header
->setRole(model()->sortRole());
1580 header
->setStyleOption(m_styleOption
);
1581 header
->setScrollOrientation(scrollOrientation());
1586 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1588 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1591 const int index
= widget
->index();
1592 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1593 const QRectF itemRect
= m_layouter
->itemRect(index
);
1595 // The group-header is a child of the itemlist widget. Translate the
1596 // group header position to the relative position.
1597 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1598 - groupHeaderRect
.height());
1599 header
->setPos(groupHeaderPos
);
1600 header
->resize(groupHeaderRect
.size());
1603 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1605 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1607 header
->setParentItem(0);
1608 m_groupHeaderCreator
->recycle(header
);
1609 m_visibleGroups
.remove(widget
);
1613 void KItemListView::updateVisibleGroupHeaders()
1615 Q_ASSERT(m_grouped
);
1616 m_layouter
->markAsDirty();
1618 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1619 while (it
.hasNext()) {
1621 updateGroupHeaderForWidget(it
.value());
1625 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1627 QHash
<QByteArray
, qreal
> rolesWidths
;
1629 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1630 while (it
.hasNext()) {
1632 rolesWidths
.insert(it
.key(), it
.value().width());
1638 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1640 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1644 const int itemCount
= m_model
->count();
1645 int rangesItemCount
= 0;
1646 foreach (const KItemRange
& range
, itemRanges
) {
1647 rangesItemCount
+= range
.count
;
1650 if (itemCount
== rangesItemCount
) {
1651 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1653 // Assure the the sizes are not smaller than the minimum defined by the header
1654 // TODO: Currently only implemented for a top-aligned header
1655 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1656 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1657 while (it
.hasNext()) {
1659 const QSizeF
& size
= it
.value();
1660 if (size
.width() < minHeaderRoleWidth
) {
1661 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1662 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1667 // Only a sub range of the roles need to be determined.
1668 // The chances are good that the sizes of the sub ranges
1669 // already fit into the available sizes and hence no
1670 // expensive update might be required.
1671 bool updateRequired
= false;
1673 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1674 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1675 while (it
.hasNext()) {
1677 const QByteArray
& role
= it
.key();
1678 const QSizeF
& updatedSize
= it
.value();
1679 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1680 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1681 m_visibleRolesSizes
.insert(role
, updatedSize
);
1682 updateRequired
= true;
1686 if (!updateRequired
) {
1687 // All the updated sizes are smaller than the current sizes and no change
1688 // of the stretched roles-widths is required
1693 updateStretchedVisibleRolesSizes();
1696 void KItemListView::updateVisibleRolesSizes()
1702 const int itemCount
= m_model
->count();
1703 if (itemCount
> 0) {
1704 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1708 void KItemListView::updateStretchedVisibleRolesSizes()
1710 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1714 // Calculate the maximum size of an item by considering the
1715 // visible role sizes and apply them to the layouter. If the
1716 // size does not use the available view-size it the size of the
1717 // first role will get stretched.
1718 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1719 const QByteArray role
= m_visibleRoles
.first();
1720 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1722 QSizeF dynamicItemSize
= m_itemSize
;
1724 if (dynamicItemSize
.width() <= 0) {
1725 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1726 const qreal availableWidth
= size().width();
1727 if (requiredWidth
< availableWidth
) {
1728 // Stretch the first role to use the whole width for the item
1729 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1730 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1732 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1735 if (dynamicItemSize
.height() <= 0) {
1736 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1737 const qreal availableHeight
= size().height();
1738 if (requiredHeight
< availableHeight
) {
1739 // Stretch the first role to use the whole height for the item
1740 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1741 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1743 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1746 m_layouter
->setItemSize(dynamicItemSize
);
1749 m_header
->setVisibleRolesWidths(headerRolesWidths());
1750 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1753 // Update the role sizes for all visible widgets
1754 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1755 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1759 qreal
KItemListView::visibleRolesSizesWidthSum() const
1762 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1763 while (it
.hasNext()) {
1765 widthSum
+= it
.value().width();
1770 qreal
KItemListView::visibleRolesSizesHeightSum() const
1772 qreal heightSum
= 0;
1773 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1774 while (it
.hasNext()) {
1776 heightSum
+= it
.value().height();
1781 QRectF
KItemListView::headerBoundaries() const
1783 return m_header
? m_header
->geometry() : QRectF();
1786 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1790 const int minSpeed
= 4;
1791 const int maxSpeed
= 128;
1792 const int speedLimiter
= 96;
1793 const int autoScrollBorder
= 64;
1795 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1796 // This assures that the autoscrolling speed grows gradually.
1797 const int incLimiter
= 1;
1799 if (pos
< autoScrollBorder
) {
1800 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1801 inc
= qMax(inc
, -maxSpeed
);
1802 inc
= qMax(inc
, oldInc
- incLimiter
);
1803 } else if (pos
> range
- autoScrollBorder
) {
1804 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1805 inc
= qMin(inc
, maxSpeed
);
1806 inc
= qMin(inc
, oldInc
+ incLimiter
);
1814 KItemListCreatorBase::~KItemListCreatorBase()
1816 qDeleteAll(m_recycleableWidgets
);
1817 qDeleteAll(m_createdWidgets
);
1820 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1822 m_createdWidgets
.insert(widget
);
1825 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1827 Q_ASSERT(m_createdWidgets
.contains(widget
));
1828 m_createdWidgets
.remove(widget
);
1830 if (m_recycleableWidgets
.count() < 100) {
1831 m_recycleableWidgets
.append(widget
);
1832 widget
->setVisible(false);
1838 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1840 if (m_recycleableWidgets
.isEmpty()) {
1844 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1845 m_createdWidgets
.insert(widget
);
1849 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1853 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1855 widget
->setParentItem(0);
1856 widget
->setOpacity(1.0);
1857 pushRecycleableWidget(widget
);
1860 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1864 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1866 header
->setOpacity(1.0);
1867 pushRecycleableWidget(header
);
1870 #include "kitemlistview.moc"