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
),
56 m_activeTransactions(0),
61 m_visibleRolesSizes(),
62 m_stretchedVisibleRolesSizes(),
64 m_groupHeaderCreator(0),
68 m_sizeHintResolver(0),
73 m_oldMaximumScrollOffset(0),
75 m_oldMaximumItemOffset(0),
76 m_skipAutoScrollForRubberBand(false),
79 m_autoScrollIncrement(0),
82 m_useHeaderWidths(false)
84 setAcceptHoverEvents(true);
86 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
88 m_layouter
= new KItemListViewLayouter(this);
89 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
91 m_animation
= new KItemListViewAnimation(this);
92 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
93 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
95 m_layoutTimer
= new QTimer(this);
96 m_layoutTimer
->setInterval(300);
97 m_layoutTimer
->setSingleShot(true);
98 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
100 m_rubberBand
= new KItemListRubberBand(this);
101 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
104 KItemListView::~KItemListView()
106 delete m_sizeHintResolver
;
107 m_sizeHintResolver
= 0;
110 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
112 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
113 if (orientation
== previousOrientation
) {
117 m_layouter
->setScrollOrientation(orientation
);
118 m_animation
->setScrollOrientation(orientation
);
119 m_sizeHintResolver
->clearCache();
122 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
123 while (it
.hasNext()) {
125 it
.value()->setScrollOrientation(orientation
);
129 doLayout(Animation
, 0, 0);
131 onScrollOrientationChanged(orientation
, previousOrientation
);
132 emit
scrollOrientationChanged(orientation
, previousOrientation
);
135 Qt::Orientation
KItemListView::scrollOrientation() const
137 return m_layouter
->scrollOrientation();
140 void KItemListView::setItemSize(const QSizeF
& itemSize
)
142 const QSizeF previousSize
= m_itemSize
;
143 if (itemSize
== previousSize
) {
147 m_itemSize
= itemSize
;
149 const bool emptySize
= itemSize
.isEmpty();
151 updateVisibleRolesSizes();
153 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
154 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
156 m_layouter
->setItemSize(itemSize
);
160 m_sizeHintResolver
->clearCache();
161 doLayout(Animation
, 0, 0);
162 onItemSizeChanged(itemSize
, previousSize
);
165 QSizeF
KItemListView::itemSize() const
170 void KItemListView::setScrollOffset(qreal offset
)
176 const qreal previousOffset
= m_layouter
->scrollOffset();
177 if (offset
== previousOffset
) {
181 m_layouter
->setScrollOffset(offset
);
182 m_animation
->setScrollOffset(offset
);
183 if (!m_layoutTimer
->isActive()) {
184 doLayout(NoAnimation
, 0, 0);
186 onScrollOffsetChanged(offset
, previousOffset
);
189 qreal
KItemListView::scrollOffset() const
191 return m_layouter
->scrollOffset();
194 qreal
KItemListView::maximumScrollOffset() const
196 return m_layouter
->maximumScrollOffset();
199 void KItemListView::setItemOffset(qreal offset
)
201 m_layouter
->setItemOffset(offset
);
203 m_header
->setPos(-offset
, 0);
205 if (!m_layoutTimer
->isActive()) {
206 doLayout(NoAnimation
, 0, 0);
210 qreal
KItemListView::itemOffset() const
212 return m_layouter
->itemOffset();
215 qreal
KItemListView::maximumItemOffset() const
217 return m_layouter
->maximumItemOffset();
220 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
222 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
223 m_visibleRoles
= roles
;
225 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
226 while (it
.hasNext()) {
228 KItemListWidget
* widget
= it
.value();
229 widget
->setVisibleRoles(roles
);
230 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
233 m_sizeHintResolver
->clearCache();
234 m_layouter
->markAsDirty();
237 m_header
->setVisibleRoles(roles
);
238 m_header
->setVisibleRolesWidths(headerRolesWidths());
239 m_useHeaderWidths
= false;
242 updateVisibleRolesSizes();
243 doLayout(Animation
, 0, 0);
245 onVisibleRolesChanged(roles
, previousRoles
);
248 QList
<QByteArray
> KItemListView::visibleRoles() const
250 return m_visibleRoles
;
253 void KItemListView::setAutoScroll(bool enabled
)
255 if (enabled
&& !m_autoScrollTimer
) {
256 m_autoScrollTimer
= new QTimer(this);
257 m_autoScrollTimer
->setSingleShot(false);
258 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
259 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
260 } else if (!enabled
&& m_autoScrollTimer
) {
261 delete m_autoScrollTimer
;
262 m_autoScrollTimer
= 0;
267 bool KItemListView::autoScroll() const
269 return m_autoScrollTimer
!= 0;
272 KItemListController
* KItemListView::controller() const
277 KItemModelBase
* KItemListView::model() const
282 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
284 m_widgetCreator
= widgetCreator
;
287 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
289 return m_widgetCreator
;
292 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
294 m_groupHeaderCreator
= groupHeaderCreator
;
297 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
299 return m_groupHeaderCreator
;
302 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
304 const KItemListStyleOption previousOption
= m_styleOption
;
305 m_styleOption
= option
;
307 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
308 while (it
.hasNext()) {
310 it
.value()->setStyleOption(option
);
313 m_sizeHintResolver
->clearCache();
314 doLayout(Animation
, 0, 0);
315 onStyleOptionChanged(option
, previousOption
);
318 const KItemListStyleOption
& KItemListView::styleOption() const
320 return m_styleOption
;
323 void KItemListView::setGeometry(const QRectF
& rect
)
325 QGraphicsWidget::setGeometry(rect
);
331 if (m_model
->count() > 0) {
332 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
334 m_layouter
->setSize(rect
.size());
337 if (!m_layoutTimer
->isActive()) {
338 m_layoutTimer
->start();
341 // Changing the geometry does not require to do an expensive
342 // update of the visible-roles sizes, only the stretched sizes
343 // need to be adjusted to the new size.
344 updateStretchedVisibleRolesSizes();
347 int KItemListView::itemAt(const QPointF
& pos
) const
349 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
350 while (it
.hasNext()) {
353 const KItemListWidget
* widget
= it
.value();
354 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
355 if (widget
->contains(mappedPos
)) {
363 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
370 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
372 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
374 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
375 if (!expansionToggleRect
.isEmpty()) {
376 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
377 return expansionToggleRect
.contains(mappedPos
);
383 int KItemListView::firstVisibleIndex() const
385 return m_layouter
->firstVisibleIndex();
388 int KItemListView::lastVisibleIndex() const
390 return m_layouter
->lastVisibleIndex();
393 QSizeF
KItemListView::itemSizeHint(int index
) const
399 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
401 Q_UNUSED(itemRanges
);
402 return QHash
<QByteArray
, QSizeF
>();
405 QRectF
KItemListView::itemRect(int index
) const
407 return m_layouter
->itemRect(index
);
410 int KItemListView::itemsPerOffset() const
412 return m_layouter
->itemsPerOffset();
415 void KItemListView::beginTransaction()
417 ++m_activeTransactions
;
418 if (m_activeTransactions
== 1) {
419 onTransactionBegin();
423 void KItemListView::endTransaction()
425 --m_activeTransactions
;
426 if (m_activeTransactions
< 0) {
427 m_activeTransactions
= 0;
428 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
431 if (m_activeTransactions
== 0) {
433 doLayout(Animation
, 0, 0);
437 bool KItemListView::isTransactionActive() const
439 return m_activeTransactions
> 0;
443 void KItemListView::setHeaderShown(bool show
)
446 if (show
&& !m_header
) {
447 m_header
= new KItemListHeader(this);
448 m_header
->setPos(0, 0);
449 m_header
->setModel(m_model
);
450 m_header
->setVisibleRoles(m_visibleRoles
);
451 m_header
->setVisibleRolesWidths(headerRolesWidths());
452 m_header
->setZValue(1);
454 m_useHeaderWidths
= false;
456 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
457 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
459 m_layouter
->setHeaderHeight(m_header
->size().height());
460 } else if (!show
&& m_header
) {
463 m_useHeaderWidths
= false;
464 m_layouter
->setHeaderHeight(0);
468 bool KItemListView::isHeaderShown() const
470 return m_header
!= 0;
473 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
479 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
481 QGraphicsWidget::paint(painter
, option
, widget
);
483 if (m_rubberBand
->isActive()) {
484 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
485 m_rubberBand
->endPosition()).normalized();
487 const QPointF topLeft
= rubberBandRect
.topLeft();
488 if (scrollOrientation() == Qt::Vertical
) {
489 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
491 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
494 QStyleOptionRubberBand opt
;
495 opt
.initFrom(widget
);
496 opt
.shape
= QRubberBand::Rectangle
;
498 opt
.rect
= rubberBandRect
.toRect();
499 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
503 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
508 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
510 Q_UNUSED(changedRoles
);
514 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
520 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
526 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
532 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
538 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
544 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
550 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
556 void KItemListView::onTransactionBegin()
560 void KItemListView::onTransactionEnd()
564 bool KItemListView::event(QEvent
* event
)
566 // Forward all events to the controller and handle them there
567 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
571 return QGraphicsWidget::event(event
);
574 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
576 m_mousePos
= transform().map(event
->pos());
580 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
582 QGraphicsWidget::mouseMoveEvent(event
);
584 m_mousePos
= transform().map(event
->pos());
585 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
586 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
590 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
592 event
->setAccepted(true);
596 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
598 QGraphicsWidget::dragMoveEvent(event
);
600 m_mousePos
= transform().map(event
->pos());
601 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
602 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
606 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
608 QGraphicsWidget::dragLeaveEvent(event
);
609 setAutoScroll(false);
612 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
614 QGraphicsWidget::dropEvent(event
);
615 setAutoScroll(false);
618 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
620 return m_visibleItems
.values();
623 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
625 QGraphicsWidget::resizeEvent(event
);
626 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
627 QSizeF dynamicItemSize
= m_layouter
->itemSize();
628 const QSizeF newSize
= event
->newSize();
630 if (m_itemSize
.width() < 0) {
631 const qreal requiredWidth
= visibleRolesSizesWidthSum();
632 if (newSize
.width() > requiredWidth
) {
633 dynamicItemSize
.setWidth(newSize
.width());
635 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
636 m_header
->resize(headerWidth
, m_header
->size().height());
639 if (m_itemSize
.height() < 0) {
640 const qreal requiredHeight
= visibleRolesSizesHeightSum();
641 if (newSize
.height() > requiredHeight
) {
642 dynamicItemSize
.setHeight(newSize
.height());
644 // TODO: KItemListHeader is not prepared for vertical alignment
647 m_layouter
->setItemSize(dynamicItemSize
);
651 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
653 updateVisibleRolesSizes(itemRanges
);
655 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
656 if (hasMultipleRanges
) {
660 int previouslyInsertedCount
= 0;
661 foreach (const KItemRange
& range
, itemRanges
) {
662 // range.index is related to the model before anything has been inserted.
663 // As in each loop the current item-range gets inserted the index must
664 // be increased by the already previously inserted items.
665 const int index
= range
.index
+ previouslyInsertedCount
;
666 const int count
= range
.count
;
667 if (index
< 0 || count
<= 0) {
668 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
671 previouslyInsertedCount
+= count
;
673 m_sizeHintResolver
->itemsInserted(index
, count
);
675 // Determine which visible items must be moved
676 QList
<int> itemsToMove
;
677 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
678 while (it
.hasNext()) {
680 const int visibleItemIndex
= it
.key();
681 if (visibleItemIndex
>= index
) {
682 itemsToMove
.append(visibleItemIndex
);
686 // Update the indexes of all KItemListWidget instances that are located
687 // after the inserted items. It is important to adjust the indexes in the order
688 // from the highest index to the lowest index to prevent overlaps when setting the new index.
690 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
691 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
693 setWidgetIndex(widget
, widget
->index() + count
);
696 m_layouter
->markAsDirty();
697 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
698 kDebug() << "Scrollbar required, skipping layout";
699 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
700 QSizeF layouterSize
= m_layouter
->size();
701 if (scrollOrientation() == Qt::Vertical
) {
702 layouterSize
.rwidth() -= scrollBarExtent
;
704 layouterSize
.rheight() -= scrollBarExtent
;
706 m_layouter
->setSize(layouterSize
);
709 if (!hasMultipleRanges
) {
710 doLayout(Animation
, index
, count
);
716 m_controller
->selectionManager()->itemsInserted(itemRanges
);
719 if (hasMultipleRanges
) {
724 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
726 updateVisibleRolesSizes();
728 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
729 if (hasMultipleRanges
) {
733 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
734 const KItemRange
& range
= itemRanges
.at(i
);
735 const int index
= range
.index
;
736 const int count
= range
.count
;
737 if (index
< 0 || count
<= 0) {
738 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
742 m_sizeHintResolver
->itemsRemoved(index
, count
);
744 const int firstRemovedIndex
= index
;
745 const int lastRemovedIndex
= index
+ count
- 1;
746 const int lastIndex
= m_model
->count() + count
- 1;
748 // Remove all KItemListWidget instances that got deleted
749 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
750 KItemListWidget
* widget
= m_visibleItems
.value(i
);
755 m_animation
->stop(widget
);
756 // Stopping the animation might lead to recycling the widget if
757 // it is invisible (see slotAnimationFinished()).
758 // Check again whether it is still visible:
759 if (!m_visibleItems
.contains(i
)) {
763 if (m_model
->count() == 0) {
764 // For performance reasons no animation is done when all items have
766 recycleWidget(widget
);
768 // Animate the removing of the items. Special case: When removing an item there
769 // is no valid model index available anymore. For the
770 // remove-animation the item gets removed from m_visibleItems but the widget
771 // will stay alive until the animation has been finished and will
772 // be recycled (deleted) in KItemListView::slotAnimationFinished().
773 m_visibleItems
.remove(i
);
774 widget
->setIndex(-1);
775 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
779 // Update the indexes of all KItemListWidget instances that are located
780 // after the deleted items
781 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
782 KItemListWidget
* widget
= m_visibleItems
.value(i
);
784 const int newIndex
= i
- count
;
785 setWidgetIndex(widget
, newIndex
);
789 m_layouter
->markAsDirty();
790 if (!hasMultipleRanges
) {
791 doLayout(Animation
, index
, -count
);
797 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
800 if (hasMultipleRanges
) {
805 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
807 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
808 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
810 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
811 KItemListWidget
* widget
= m_visibleItems
.value(index
);
813 updateWidgetProperties(widget
, index
);
818 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
822 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
823 const QSet
<QByteArray
>& roles
)
825 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
826 if (updateSizeHints
) {
827 updateVisibleRolesSizes(itemRanges
);
830 foreach (const KItemRange
& itemRange
, itemRanges
) {
831 const int index
= itemRange
.index
;
832 const int count
= itemRange
.count
;
834 if (updateSizeHints
) {
835 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
836 m_layouter
->markAsDirty();
838 if (!m_layoutTimer
->isActive()) {
839 m_layoutTimer
->start();
843 // Apply the changed roles to the visible item-widgets
844 const int lastIndex
= index
+ count
- 1;
845 for (int i
= index
; i
<= lastIndex
; ++i
) {
846 KItemListWidget
* widget
= m_visibleItems
.value(i
);
848 widget
->setData(m_model
->data(i
), roles
);
852 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
853 // The sort-role has been changed which might result
854 // in modified group headers
855 updateVisibleGroupHeaders();
856 doLayout(NoAnimation
, 0, 0);
857 if (!m_layoutTimer
->isActive()) {
858 m_layoutTimer
->start();
864 void KItemListView::slotGroupedSortingChanged(bool current
)
867 m_layouter
->markAsDirty();
870 // Apply the height of the header to the layouter
871 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
872 m_styleOption
.margin
* 2;
873 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
875 updateVisibleGroupHeaders();
877 // Clear all visible headers
878 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
879 while (it
.hasNext()) {
881 recycleGroupHeaderForWidget(it
.key());
883 Q_ASSERT(m_visibleGroups
.isEmpty());
886 doLayout(Animation
, 0, 0);
889 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
894 updateVisibleGroupHeaders();
895 doLayout(Animation
, 0, 0);
899 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
904 updateVisibleGroupHeaders();
905 doLayout(Animation
, 0, 0);
909 void KItemListView::slotCurrentChanged(int current
, int previous
)
913 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
914 if (previousWidget
) {
915 Q_ASSERT(previousWidget
->isCurrent());
916 previousWidget
->setCurrent(false);
919 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
921 Q_ASSERT(!currentWidget
->isCurrent());
922 currentWidget
->setCurrent(true);
925 const QRectF viewGeometry
= geometry();
926 const QRectF currentRect
= itemRect(current
);
928 if (!viewGeometry
.contains(currentRect
)) {
929 // Make sure that the new current item is fully visible in the view.
930 qreal newOffset
= scrollOffset();
931 if (currentRect
.top() < viewGeometry
.top()) {
932 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
933 newOffset
+= currentRect
.top() - viewGeometry
.top();
934 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
935 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
936 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
937 } else if (currentRect
.left() < viewGeometry
.left()) {
938 if (scrollOrientation() == Qt::Horizontal
) {
939 newOffset
+= currentRect
.left() - viewGeometry
.left();
941 } else if ((currentRect
.right() > viewGeometry
.right())) {
942 if (scrollOrientation() == Qt::Horizontal
) {
943 newOffset
+= currentRect
.right() - viewGeometry
.right();
947 if (newOffset
!= scrollOffset()) {
948 emit
scrollTo(newOffset
);
953 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
957 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
958 while (it
.hasNext()) {
960 const int index
= it
.key();
961 KItemListWidget
* widget
= it
.value();
962 widget
->setSelected(current
.contains(index
));
966 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
967 KItemListViewAnimation::AnimationType type
)
969 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
970 Q_ASSERT(itemListWidget
);
973 case KItemListViewAnimation::DeleteAnimation
: {
974 // As we recycle the widget in this case it is important to assure that no
975 // other animation has been started. This is a convention in KItemListView and
976 // not a requirement defined by KItemListViewAnimation.
977 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
979 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
980 // by m_visibleWidgets and must be deleted manually after the animation has
982 recycleGroupHeaderForWidget(itemListWidget
);
983 m_widgetCreator
->recycle(itemListWidget
);
987 case KItemListViewAnimation::CreateAnimation
:
988 case KItemListViewAnimation::MovingAnimation
:
989 case KItemListViewAnimation::ResizeAnimation
: {
990 const int index
= itemListWidget
->index();
991 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
992 (index
> m_layouter
->lastVisibleIndex());
993 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
994 recycleWidget(itemListWidget
);
1003 void KItemListView::slotLayoutTimerFinished()
1005 m_layouter
->setSize(geometry().size());
1006 doLayout(Animation
, 0, 0);
1009 void KItemListView::slotRubberBandPosChanged()
1014 void KItemListView::slotRubberBandActivationChanged(bool active
)
1017 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1018 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1019 m_skipAutoScrollForRubberBand
= true;
1021 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1022 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1023 m_skipAutoScrollForRubberBand
= false;
1029 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1031 qreal previousWidth
)
1033 Q_UNUSED(previousWidth
);
1035 m_useHeaderWidths
= true;
1037 if (m_visibleRolesSizes
.contains(role
)) {
1038 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1039 roleSize
.setWidth(currentWidth
);
1040 m_visibleRolesSizes
.insert(role
, roleSize
);
1041 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1043 // Apply the new size to the layouter
1044 QSizeF dynamicItemSize
= m_itemSize
;
1045 if (dynamicItemSize
.width() < 0) {
1046 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1047 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1049 if (dynamicItemSize
.height() < 0) {
1050 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1051 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1054 m_layouter
->setItemSize(dynamicItemSize
);
1056 // Update the role sizes for all visible widgets
1057 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1058 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1061 doLayout(Animation
, 0, 0);
1065 void KItemListView::triggerAutoScrolling()
1067 if (!m_autoScrollTimer
) {
1072 int visibleSize
= 0;
1073 if (scrollOrientation() == Qt::Vertical
) {
1074 pos
= m_mousePos
.y();
1075 visibleSize
= size().height();
1077 pos
= m_mousePos
.x();
1078 visibleSize
= size().width();
1081 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1082 m_autoScrollIncrement
= 0;
1085 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1086 if (m_autoScrollIncrement
== 0) {
1087 // The mouse position is not above an autoscroll margin (the autoscroll timer
1088 // will be restarted in mouseMoveEvent())
1089 m_autoScrollTimer
->stop();
1093 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1094 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1095 // if the direction of the rubberband is similar to the autoscroll direction. This
1096 // prevents that starting to create a rubberband within the autoscroll margins starts
1097 // an autoscrolling.
1099 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1100 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1101 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1102 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1103 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1104 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1105 // been moved up although the autoscroll direction might be down)
1106 m_autoScrollTimer
->stop();
1111 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1112 // the autoscrolling may not get skipped anymore until a new rubberband is created
1113 m_skipAutoScrollForRubberBand
= false;
1115 setScrollOffset(scrollOffset() + m_autoScrollIncrement
);
1117 // Trigger the autoscroll timer which will periodically call
1118 // triggerAutoScrolling()
1119 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1122 void KItemListView::setController(KItemListController
* controller
)
1124 if (m_controller
!= controller
) {
1125 KItemListController
* previous
= m_controller
;
1127 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1128 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1129 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1132 m_controller
= controller
;
1135 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1136 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1137 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1140 onControllerChanged(controller
, previous
);
1144 void KItemListView::setModel(KItemModelBase
* model
)
1146 if (m_model
== model
) {
1150 KItemModelBase
* previous
= m_model
;
1153 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1154 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1155 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1156 this, SLOT(slotItemsInserted(KItemRangeList
)));
1157 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1158 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1159 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1160 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1161 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1162 this, SLOT(slotGroupedSortingChanged(bool)));
1163 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1164 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1165 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1166 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1170 m_layouter
->setModel(model
);
1171 m_grouped
= model
->groupedSorting();
1174 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1175 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1176 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1177 this, SLOT(slotItemsInserted(KItemRangeList
)));
1178 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1179 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1180 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1181 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1182 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1183 this, SLOT(slotGroupedSortingChanged(bool)));
1184 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1185 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1186 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1187 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1190 onModelChanged(model
, previous
);
1193 KItemListRubberBand
* KItemListView::rubberBand() const
1195 return m_rubberBand
;
1198 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1200 if (m_layoutTimer
->isActive()) {
1201 kDebug() << "Stopping layout timer, synchronous layout requested";
1202 m_layoutTimer
->stop();
1205 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
1209 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1210 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1211 if (firstVisibleIndex
< 0) {
1212 emitOffsetChanges();
1216 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1217 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1218 // is still shown if the maximum offset got decreased.
1219 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1220 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1221 if (scrollOffset() > maxOffsetToShowFullRange
) {
1222 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1225 // Determine all items that are completely invisible and might be
1226 // reused for items that just got (at least partly) visible.
1227 // Items that do e.g. an animated moving of their position are not
1228 // marked as invisible: This assures that a scrolling inside the view
1229 // can be done without breaking an animation.
1230 QList
<int> reusableItems
;
1231 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1232 while (it
.hasNext()) {
1234 KItemListWidget
* widget
= it
.value();
1235 const int index
= widget
->index();
1236 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1237 if (invisible
&& !m_animation
->isStarted(widget
)) {
1238 widget
->setVisible(false);
1239 reusableItems
.append(index
);
1242 recycleGroupHeaderForWidget(widget
);
1247 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1248 // instances from invisible items are reused. If no reusable items are
1249 // found then new KItemListWidget instances get created.
1250 const bool animate
= (hint
== Animation
);
1251 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1252 bool applyNewPos
= true;
1253 bool wasHidden
= false;
1255 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1256 const QPointF newPos
= itemBounds
.topLeft();
1257 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1260 if (!reusableItems
.isEmpty()) {
1261 // Reuse a KItemListWidget instance from an invisible item
1262 const int oldIndex
= reusableItems
.takeLast();
1263 widget
= m_visibleItems
.value(oldIndex
);
1264 setWidgetIndex(widget
, i
);
1267 updateGroupHeaderForWidget(widget
);
1270 // No reusable KItemListWidget instance is available, create a new one
1271 widget
= createWidget(i
);
1273 widget
->resize(itemBounds
.size());
1275 if (animate
&& changedCount
< 0) {
1276 // Items have been deleted, move the created item to the
1277 // imaginary old position.
1278 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1279 if (itemRect
.isEmpty()) {
1280 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1281 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1282 widget
->setPos(invisibleOldPos
);
1284 widget
->setPos(itemRect
.topLeft());
1286 applyNewPos
= false;
1288 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1289 applyNewPos
= false;
1293 const bool itemsRemoved
= (changedCount
< 0);
1294 const bool itemsInserted
= (changedCount
> 0);
1296 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1297 // The item is located after the removed items. Animate the moving of the position.
1298 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1299 applyNewPos
= false;
1300 } else if (itemsInserted
&& i
>= changedIndex
) {
1301 // The item is located after the first inserted item
1302 if (i
<= changedIndex
+ changedCount
- 1) {
1303 // The item is an inserted item. Animate the appearing of the item.
1304 // For performance reasons no animation is done when changedCount is equal
1305 // to all available items.
1306 if (changedCount
< m_model
->count()) {
1307 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1309 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1310 // The item was already there before, so animate the moving of the position.
1311 // No moving animation is done if the item is animated by a create animation: This
1312 // prevents a "move animation mess" when inserting several ranges in parallel.
1313 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1314 applyNewPos
= false;
1316 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1317 // The size of the view might have been changed. Animate the moving of the position.
1318 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1319 applyNewPos
= false;
1324 widget
->setPos(newPos
);
1327 Q_ASSERT(widget
->index() == i
);
1328 widget
->setVisible(true);
1330 if (widget
->size() != itemBounds
.size()) {
1331 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1335 // Delete invisible KItemListWidget instances that have not been reused
1336 foreach (int index
, reusableItems
) {
1337 recycleWidget(m_visibleItems
.value(index
));
1341 // Update the layout of all visible group headers
1342 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1343 while (it
.hasNext()) {
1345 updateGroupHeaderLayout(it
.key());
1349 emitOffsetChanges();
1352 void KItemListView::emitOffsetChanges()
1354 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1355 if (m_oldScrollOffset
!= newScrollOffset
) {
1356 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1357 m_oldScrollOffset
= newScrollOffset
;
1360 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1361 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1362 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1363 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1366 const qreal newItemOffset
= m_layouter
->itemOffset();
1367 if (m_oldItemOffset
!= newItemOffset
) {
1368 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1369 m_oldItemOffset
= newItemOffset
;
1372 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1373 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1374 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1375 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1379 KItemListWidget
* KItemListView::createWidget(int index
)
1381 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1382 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1384 updateWidgetProperties(widget
, index
);
1385 m_visibleItems
.insert(index
, widget
);
1388 updateGroupHeaderForWidget(widget
);
1391 initializeItemListWidget(widget
);
1395 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1398 recycleGroupHeaderForWidget(widget
);
1401 m_visibleItems
.remove(widget
->index());
1402 m_widgetCreator
->recycle(widget
);
1405 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1407 const int oldIndex
= widget
->index();
1408 m_visibleItems
.remove(oldIndex
);
1409 updateWidgetProperties(widget
, index
);
1410 m_visibleItems
.insert(index
, widget
);
1412 initializeItemListWidget(widget
);
1415 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1417 // Calculate the first visible index and last visible index for the current size
1418 const int currentFirst
= m_layouter
->firstVisibleIndex();
1419 const int currentLast
= m_layouter
->lastVisibleIndex();
1421 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1423 // Calculate the first visible index and last visible index for the new size
1424 setLayouterSize(size
, sizeType
);
1425 const int newFirst
= m_layouter
->firstVisibleIndex();
1426 const int newLast
= m_layouter
->lastVisibleIndex();
1428 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1429 // At least one index has been changed. Assure that widgets for all possible
1430 // visible items get created so that a move-animation can be started later.
1431 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1432 int minFirst
= qMin(newFirst
, currentFirst
);
1433 const int maxLast
= qMax(newLast
, currentLast
);
1435 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1436 // Increasing the size might result in a smaller KItemListView::offset().
1437 // Decrease the first visible index in a way that at least the maximum
1438 // visible items are shown.
1439 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1442 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1443 // The creating of widgets is quite expensive. Assure that never more
1444 // than 50 % of the maximum visible items get created for the animations.
1448 setLayouterSize(currentSize
, sizeType
);
1449 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1450 if (!m_visibleItems
.contains(i
)) {
1451 KItemListWidget
* widget
= createWidget(i
);
1452 const QRectF itemRect
= m_layouter
->itemRect(i
);
1453 widget
->setPos(itemRect
.topLeft());
1454 widget
->resize(itemRect
.size());
1457 setLayouterSize(size
, sizeType
);
1461 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1464 case LayouterSize
: m_layouter
->setSize(size
); break;
1465 case ItemSize
: m_layouter
->setItemSize(size
); break;
1470 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1472 widget
->setVisibleRoles(m_visibleRoles
);
1473 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1474 widget
->setStyleOption(m_styleOption
);
1476 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1477 widget
->setCurrent(index
== selectionManager
->currentItem());
1478 widget
->setSelected(selectionManager
->isSelected(index
));
1479 widget
->setHovered(false);
1480 widget
->setAlternatingBackgroundColors(false);
1481 widget
->setIndex(index
);
1482 widget
->setData(m_model
->data(index
));
1485 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1487 const int index
= widget
->index();
1488 if (!m_layouter
->isFirstGroupItem(index
)) {
1489 // The widget does not represent the first item of a group
1490 // and hence requires no header
1491 recycleGroupHeaderForWidget(widget
);
1495 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1496 if (groups
.isEmpty()) {
1500 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1502 header
= m_groupHeaderCreator
->create(this);
1503 header
->setParentItem(widget
);
1504 m_visibleGroups
.insert(widget
, header
);
1506 Q_ASSERT(header
->parentItem() == widget
);
1508 // Determine the shown data for the header by doing a binary
1509 // search in the groups-list
1511 int max
= groups
.count() - 1;
1514 mid
= (min
+ max
) / 2;
1515 if (index
> groups
.at(mid
).first
) {
1520 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1522 header
->setData(groups
.at(mid
).second
);
1523 header
->setRole(model()->sortRole());
1524 header
->setStyleOption(m_styleOption
);
1525 header
->setScrollOrientation(scrollOrientation());
1530 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1532 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1535 const int index
= widget
->index();
1536 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1537 const QRectF itemRect
= m_layouter
->itemRect(index
);
1539 // The group-header is a child of the itemlist widget. Translate the
1540 // group header position to the relative position.
1541 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1542 - groupHeaderRect
.height());
1543 header
->setPos(groupHeaderPos
);
1544 header
->resize(groupHeaderRect
.size());
1547 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1549 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1551 header
->setParentItem(0);
1552 m_groupHeaderCreator
->recycle(header
);
1553 m_visibleGroups
.remove(widget
);
1557 void KItemListView::updateVisibleGroupHeaders()
1559 Q_ASSERT(m_grouped
);
1560 m_layouter
->markAsDirty();
1562 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1563 while (it
.hasNext()) {
1565 updateGroupHeaderForWidget(it
.value());
1569 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1571 QHash
<QByteArray
, qreal
> rolesWidths
;
1573 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1574 while (it
.hasNext()) {
1576 rolesWidths
.insert(it
.key(), it
.value().width());
1582 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1584 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1588 const int itemCount
= m_model
->count();
1589 int rangesItemCount
= 0;
1590 foreach (const KItemRange
& range
, itemRanges
) {
1591 rangesItemCount
+= range
.count
;
1594 if (itemCount
== rangesItemCount
) {
1595 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1597 // Assure the the sizes are not smaller than the minimum defined by the header
1598 // TODO: Currently only implemented for a top-aligned header
1599 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1600 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1601 while (it
.hasNext()) {
1603 const QSizeF
& size
= it
.value();
1604 if (size
.width() < minHeaderRoleWidth
) {
1605 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1606 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1611 // Only a sub range of the roles need to be determined.
1612 // The chances are good that the sizes of the sub ranges
1613 // already fit into the available sizes and hence no
1614 // expensive update might be required.
1615 bool updateRequired
= false;
1617 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1618 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1619 while (it
.hasNext()) {
1621 const QByteArray
& role
= it
.key();
1622 const QSizeF
& updatedSize
= it
.value();
1623 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1624 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1625 m_visibleRolesSizes
.insert(role
, updatedSize
);
1626 updateRequired
= true;
1630 if (!updateRequired
) {
1631 // All the updated sizes are smaller than the current sizes and no change
1632 // of the stretched roles-widths is required
1637 updateStretchedVisibleRolesSizes();
1640 void KItemListView::updateVisibleRolesSizes()
1642 const int itemCount
= m_model
->count();
1643 if (itemCount
> 0) {
1644 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1648 void KItemListView::updateStretchedVisibleRolesSizes()
1650 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1654 // Calculate the maximum size of an item by considering the
1655 // visible role sizes and apply them to the layouter. If the
1656 // size does not use the available view-size it the size of the
1657 // first role will get stretched.
1658 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1659 const QByteArray role
= visibleRoles().first();
1660 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1662 QSizeF dynamicItemSize
= m_itemSize
;
1664 if (dynamicItemSize
.width() <= 0) {
1665 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1666 const qreal availableWidth
= size().width();
1667 if (requiredWidth
< availableWidth
) {
1668 // Stretch the first role to use the whole width for the item
1669 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1670 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1672 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1675 if (dynamicItemSize
.height() <= 0) {
1676 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1677 const qreal availableHeight
= size().height();
1678 if (requiredHeight
< availableHeight
) {
1679 // Stretch the first role to use the whole height for the item
1680 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1681 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1683 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1686 m_layouter
->setItemSize(dynamicItemSize
);
1689 m_header
->setVisibleRolesWidths(headerRolesWidths());
1690 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1693 // Update the role sizes for all visible widgets
1694 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1695 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1699 qreal
KItemListView::visibleRolesSizesWidthSum() const
1702 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1703 while (it
.hasNext()) {
1705 widthSum
+= it
.value().width();
1710 qreal
KItemListView::visibleRolesSizesHeightSum() const
1712 qreal heightSum
= 0;
1713 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1714 while (it
.hasNext()) {
1716 heightSum
+= it
.value().height();
1721 QRectF
KItemListView::headerBoundaries() const
1723 return m_header
? m_header
->geometry() : QRectF();
1726 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1730 const int minSpeed
= 4;
1731 const int maxSpeed
= 128;
1732 const int speedLimiter
= 96;
1733 const int autoScrollBorder
= 64;
1735 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1736 // This assures that the autoscrolling speed grows gradually.
1737 const int incLimiter
= 1;
1739 if (pos
< autoScrollBorder
) {
1740 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1741 inc
= qMax(inc
, -maxSpeed
);
1742 inc
= qMax(inc
, oldInc
- incLimiter
);
1743 } else if (pos
> range
- autoScrollBorder
) {
1744 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1745 inc
= qMin(inc
, maxSpeed
);
1746 inc
= qMin(inc
, oldInc
+ incLimiter
);
1754 KItemListCreatorBase::~KItemListCreatorBase()
1756 qDeleteAll(m_recycleableWidgets
);
1757 qDeleteAll(m_createdWidgets
);
1760 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1762 m_createdWidgets
.insert(widget
);
1765 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1767 Q_ASSERT(m_createdWidgets
.contains(widget
));
1768 m_createdWidgets
.remove(widget
);
1770 if (m_recycleableWidgets
.count() < 100) {
1771 m_recycleableWidgets
.append(widget
);
1772 widget
->setVisible(false);
1778 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1780 if (m_recycleableWidgets
.isEmpty()) {
1784 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1785 m_createdWidgets
.insert(widget
);
1789 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1793 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1795 widget
->setParentItem(0);
1796 widget
->setOpacity(1.0);
1797 pushRecycleableWidget(widget
);
1800 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1804 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1806 header
->setOpacity(1.0);
1807 pushRecycleableWidget(header
);
1810 #include "kitemlistview.moc"