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 onScrollOrientationChanged(orientation
, previousOrientation
);
123 emit
scrollOrientationChanged(orientation
, previousOrientation
);
126 Qt::Orientation
KItemListView::scrollOrientation() const
128 return m_layouter
->scrollOrientation();
131 void KItemListView::setItemSize(const QSizeF
& itemSize
)
133 const QSizeF previousSize
= m_itemSize
;
134 if (itemSize
== previousSize
) {
138 m_itemSize
= itemSize
;
140 const bool emptySize
= itemSize
.isEmpty();
142 updateVisibleRolesSizes();
144 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
145 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
147 m_layouter
->setItemSize(itemSize
);
151 m_sizeHintResolver
->clearCache();
153 onItemSizeChanged(itemSize
, previousSize
);
156 QSizeF
KItemListView::itemSize() const
161 void KItemListView::setScrollOffset(qreal offset
)
167 const qreal previousOffset
= m_layouter
->scrollOffset();
168 if (offset
== previousOffset
) {
172 m_layouter
->setScrollOffset(offset
);
173 m_animation
->setScrollOffset(offset
);
174 if (!m_layoutTimer
->isActive()) {
175 doLayout(NoAnimation
, 0, 0);
178 onScrollOffsetChanged(offset
, previousOffset
);
181 qreal
KItemListView::scrollOffset() const
183 return m_layouter
->scrollOffset();
186 qreal
KItemListView::maximumScrollOffset() const
188 return m_layouter
->maximumScrollOffset();
191 void KItemListView::setItemOffset(qreal offset
)
193 m_layouter
->setItemOffset(offset
);
195 m_header
->setPos(-offset
, 0);
197 if (!m_layoutTimer
->isActive()) {
198 doLayout(NoAnimation
, 0, 0);
203 qreal
KItemListView::itemOffset() const
205 return m_layouter
->itemOffset();
208 qreal
KItemListView::maximumItemOffset() const
210 return m_layouter
->maximumItemOffset();
213 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
215 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
216 m_visibleRoles
= roles
;
218 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
219 while (it
.hasNext()) {
221 KItemListWidget
* widget
= it
.value();
222 widget
->setVisibleRoles(roles
);
223 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
226 m_sizeHintResolver
->clearCache();
227 m_layouter
->markAsDirty();
230 m_header
->setVisibleRoles(roles
);
231 m_header
->setVisibleRolesWidths(headerRolesWidths());
232 m_useHeaderWidths
= false;
235 updateVisibleRolesSizes();
238 onVisibleRolesChanged(roles
, previousRoles
);
241 QList
<QByteArray
> KItemListView::visibleRoles() const
243 return m_visibleRoles
;
246 void KItemListView::setAutoScroll(bool enabled
)
248 if (enabled
&& !m_autoScrollTimer
) {
249 m_autoScrollTimer
= new QTimer(this);
250 m_autoScrollTimer
->setSingleShot(false);
251 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
252 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
253 } else if (!enabled
&& m_autoScrollTimer
) {
254 delete m_autoScrollTimer
;
255 m_autoScrollTimer
= 0;
260 bool KItemListView::autoScroll() const
262 return m_autoScrollTimer
!= 0;
265 KItemListController
* KItemListView::controller() const
270 KItemModelBase
* KItemListView::model() const
275 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
277 m_widgetCreator
= widgetCreator
;
280 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
282 return m_widgetCreator
;
285 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
287 m_groupHeaderCreator
= groupHeaderCreator
;
290 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
292 return m_groupHeaderCreator
;
295 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
297 const KItemListStyleOption previousOption
= m_styleOption
;
298 m_styleOption
= option
;
300 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
301 while (it
.hasNext()) {
303 it
.value()->setStyleOption(option
);
306 m_sizeHintResolver
->clearCache();
308 onStyleOptionChanged(option
, previousOption
);
311 const KItemListStyleOption
& KItemListView::styleOption() const
313 return m_styleOption
;
316 void KItemListView::setGeometry(const QRectF
& rect
)
318 QGraphicsWidget::setGeometry(rect
);
324 if (m_model
->count() > 0) {
325 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
327 m_layouter
->setSize(rect
.size());
330 if (!m_layoutTimer
->isActive()) {
331 m_layoutTimer
->start();
334 // Changing the geometry does not require to do an expensive
335 // update of the visible-roles sizes, only the stretched sizes
336 // need to be adjusted to the new size.
337 updateStretchedVisibleRolesSizes();
340 int KItemListView::itemAt(const QPointF
& pos
) const
342 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
343 while (it
.hasNext()) {
346 const KItemListWidget
* widget
= it
.value();
347 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
348 if (widget
->contains(mappedPos
)) {
356 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
363 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
365 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
367 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
368 if (!expansionToggleRect
.isEmpty()) {
369 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
370 return expansionToggleRect
.contains(mappedPos
);
376 int KItemListView::firstVisibleIndex() const
378 return m_layouter
->firstVisibleIndex();
381 int KItemListView::lastVisibleIndex() const
383 return m_layouter
->lastVisibleIndex();
386 QSizeF
KItemListView::itemSizeHint(int index
) const
392 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
394 Q_UNUSED(itemRanges
);
395 return QHash
<QByteArray
, QSizeF
>();
398 QRectF
KItemListView::itemRect(int index
) const
400 return m_layouter
->itemRect(index
);
403 int KItemListView::itemsPerOffset() const
405 return m_layouter
->itemsPerOffset();
408 void KItemListView::beginTransaction()
410 ++m_activeTransactions
;
411 if (m_activeTransactions
== 1) {
412 onTransactionBegin();
416 void KItemListView::endTransaction()
418 --m_activeTransactions
;
419 if (m_activeTransactions
< 0) {
420 m_activeTransactions
= 0;
421 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
424 if (m_activeTransactions
== 0) {
430 bool KItemListView::isTransactionActive() const
432 return m_activeTransactions
> 0;
436 void KItemListView::setHeaderShown(bool show
)
439 if (show
&& !m_header
) {
440 m_header
= new KItemListHeader(this);
441 m_header
->setPos(0, 0);
442 m_header
->setModel(m_model
);
443 m_header
->setVisibleRoles(m_visibleRoles
);
444 m_header
->setVisibleRolesWidths(headerRolesWidths());
445 m_header
->setZValue(1);
447 m_useHeaderWidths
= false;
449 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
450 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
452 m_layouter
->setHeaderHeight(m_header
->size().height());
453 } else if (!show
&& m_header
) {
456 m_useHeaderWidths
= false;
457 m_layouter
->setHeaderHeight(0);
461 bool KItemListView::isHeaderShown() const
463 return m_header
!= 0;
466 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
472 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
474 QGraphicsWidget::paint(painter
, option
, widget
);
476 if (m_rubberBand
->isActive()) {
477 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
478 m_rubberBand
->endPosition()).normalized();
480 const QPointF topLeft
= rubberBandRect
.topLeft();
481 if (scrollOrientation() == Qt::Vertical
) {
482 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
484 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
487 QStyleOptionRubberBand opt
;
488 opt
.initFrom(widget
);
489 opt
.shape
= QRubberBand::Rectangle
;
491 opt
.rect
= rubberBandRect
.toRect();
492 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
496 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
501 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
503 Q_UNUSED(changedRoles
);
507 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
513 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
519 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
525 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
531 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
537 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
543 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
549 void KItemListView::onTransactionBegin()
553 void KItemListView::onTransactionEnd()
557 bool KItemListView::event(QEvent
* event
)
559 // Forward all events to the controller and handle them there
560 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
564 return QGraphicsWidget::event(event
);
567 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
569 m_mousePos
= transform().map(event
->pos());
573 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
575 QGraphicsWidget::mouseMoveEvent(event
);
577 m_mousePos
= transform().map(event
->pos());
578 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
579 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
583 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
585 event
->setAccepted(true);
589 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
591 QGraphicsWidget::dragMoveEvent(event
);
593 m_mousePos
= transform().map(event
->pos());
594 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
595 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
599 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
601 QGraphicsWidget::dragLeaveEvent(event
);
602 setAutoScroll(false);
605 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
607 QGraphicsWidget::dropEvent(event
);
608 setAutoScroll(false);
611 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
613 return m_visibleItems
.values();
616 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent
* event
)
618 QGraphicsWidget::resizeEvent(event
);
619 if (m_itemSize
.isEmpty() && m_useHeaderWidths
) {
620 QSizeF dynamicItemSize
= m_layouter
->itemSize();
621 const QSizeF newSize
= event
->newSize();
623 if (m_itemSize
.width() < 0) {
624 const qreal requiredWidth
= visibleRolesSizesWidthSum();
625 if (newSize
.width() > requiredWidth
) {
626 dynamicItemSize
.setWidth(newSize
.width());
628 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
629 m_header
->resize(headerWidth
, m_header
->size().height());
632 if (m_itemSize
.height() < 0) {
633 const qreal requiredHeight
= visibleRolesSizesHeightSum();
634 if (newSize
.height() > requiredHeight
) {
635 dynamicItemSize
.setHeight(newSize
.height());
637 // TODO: KItemListHeader is not prepared for vertical alignment
640 m_layouter
->setItemSize(dynamicItemSize
);
644 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
646 updateVisibleRolesSizes(itemRanges
);
648 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
649 if (hasMultipleRanges
) {
653 int previouslyInsertedCount
= 0;
654 foreach (const KItemRange
& range
, itemRanges
) {
655 // range.index is related to the model before anything has been inserted.
656 // As in each loop the current item-range gets inserted the index must
657 // be increased by the already previously inserted items.
658 const int index
= range
.index
+ previouslyInsertedCount
;
659 const int count
= range
.count
;
660 if (index
< 0 || count
<= 0) {
661 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
664 previouslyInsertedCount
+= count
;
666 m_sizeHintResolver
->itemsInserted(index
, count
);
668 // Determine which visible items must be moved
669 QList
<int> itemsToMove
;
670 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
671 while (it
.hasNext()) {
673 const int visibleItemIndex
= it
.key();
674 if (visibleItemIndex
>= index
) {
675 itemsToMove
.append(visibleItemIndex
);
679 // Update the indexes of all KItemListWidget instances that are located
680 // after the inserted items. It is important to adjust the indexes in the order
681 // from the highest index to the lowest index to prevent overlaps when setting the new index.
683 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
684 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
686 setWidgetIndex(widget
, widget
->index() + count
);
689 m_layouter
->markAsDirty();
690 if (m_model
->count() == count
&& maximumScrollOffset() > size().height()) {
691 kDebug() << "Scrollbar required, skipping layout";
692 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
693 QSizeF layouterSize
= m_layouter
->size();
694 if (scrollOrientation() == Qt::Vertical
) {
695 layouterSize
.rwidth() -= scrollBarExtent
;
697 layouterSize
.rheight() -= scrollBarExtent
;
699 m_layouter
->setSize(layouterSize
);
702 if (!hasMultipleRanges
) {
703 doLayout(Animation
, index
, count
);
709 m_controller
->selectionManager()->itemsInserted(itemRanges
);
712 if (hasMultipleRanges
) {
717 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
719 updateVisibleRolesSizes();
721 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
722 if (hasMultipleRanges
) {
726 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
727 const KItemRange
& range
= itemRanges
.at(i
);
728 const int index
= range
.index
;
729 const int count
= range
.count
;
730 if (index
< 0 || count
<= 0) {
731 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
735 m_sizeHintResolver
->itemsRemoved(index
, count
);
737 const int firstRemovedIndex
= index
;
738 const int lastRemovedIndex
= index
+ count
- 1;
739 const int lastIndex
= m_model
->count() + count
- 1;
741 // Remove all KItemListWidget instances that got deleted
742 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
743 KItemListWidget
* widget
= m_visibleItems
.value(i
);
748 m_animation
->stop(widget
);
749 // Stopping the animation might lead to recycling the widget if
750 // it is invisible (see slotAnimationFinished()).
751 // Check again whether it is still visible:
752 if (!m_visibleItems
.contains(i
)) {
756 if (m_model
->count() == 0) {
757 // For performance reasons no animation is done when all items have
759 recycleWidget(widget
);
761 // Animate the removing of the items. Special case: When removing an item there
762 // is no valid model index available anymore. For the
763 // remove-animation the item gets removed from m_visibleItems but the widget
764 // will stay alive until the animation has been finished and will
765 // be recycled (deleted) in KItemListView::slotAnimationFinished().
766 m_visibleItems
.remove(i
);
767 widget
->setIndex(-1);
768 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
772 // Update the indexes of all KItemListWidget instances that are located
773 // after the deleted items
774 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
775 KItemListWidget
* widget
= m_visibleItems
.value(i
);
777 const int newIndex
= i
- count
;
778 setWidgetIndex(widget
, newIndex
);
782 m_layouter
->markAsDirty();
783 if (!hasMultipleRanges
) {
784 doLayout(Animation
, index
, -count
);
790 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
793 if (hasMultipleRanges
) {
798 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
800 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
801 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
803 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
804 KItemListWidget
* widget
= m_visibleItems
.value(index
);
806 updateWidgetProperties(widget
, index
);
811 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
815 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
816 const QSet
<QByteArray
>& roles
)
818 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
819 if (updateSizeHints
) {
820 updateVisibleRolesSizes(itemRanges
);
823 foreach (const KItemRange
& itemRange
, itemRanges
) {
824 const int index
= itemRange
.index
;
825 const int count
= itemRange
.count
;
827 if (updateSizeHints
) {
828 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
829 m_layouter
->markAsDirty();
830 if (!m_layoutTimer
->isActive()) {
831 m_layoutTimer
->start();
835 // Apply the changed roles to the visible item-widgets
836 const int lastIndex
= index
+ count
- 1;
837 for (int i
= index
; i
<= lastIndex
; ++i
) {
838 KItemListWidget
* widget
= m_visibleItems
.value(i
);
840 widget
->setData(m_model
->data(i
), roles
);
847 void KItemListView::slotGroupedSortingChanged(bool current
)
851 // Apply the height of the header to the layouter
852 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
853 m_styleOption
.margin
* 2;
854 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
856 // Assure that headers from already visible items get created
857 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
858 while (it
.hasNext()) {
860 KItemListWidget
* widget
= it
.value();
861 updateGroupHeaderForWidget(widget
);
864 // Clear all visible headers
865 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
866 while (it
.hasNext()) {
868 recycleGroupHeaderForWidget(it
.key());
870 Q_ASSERT(m_visibleGroups
.isEmpty());
873 m_layouter
->markAsDirty();
877 void KItemListView::slotCurrentChanged(int current
, int previous
)
881 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
882 if (previousWidget
) {
883 Q_ASSERT(previousWidget
->isCurrent());
884 previousWidget
->setCurrent(false);
887 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
889 Q_ASSERT(!currentWidget
->isCurrent());
890 currentWidget
->setCurrent(true);
893 const QRectF viewGeometry
= geometry();
894 const QRectF currentRect
= itemRect(current
);
896 if (!viewGeometry
.contains(currentRect
)) {
897 // Make sure that the new current item is fully visible in the view.
898 qreal newOffset
= scrollOffset();
899 if (currentRect
.top() < viewGeometry
.top()) {
900 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
901 newOffset
+= currentRect
.top() - viewGeometry
.top();
902 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
903 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
904 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
905 } else if (currentRect
.left() < viewGeometry
.left()) {
906 if (scrollOrientation() == Qt::Horizontal
) {
907 newOffset
+= currentRect
.left() - viewGeometry
.left();
909 } else if ((currentRect
.right() > viewGeometry
.right())) {
910 if (scrollOrientation() == Qt::Horizontal
) {
911 newOffset
+= currentRect
.right() - viewGeometry
.right();
915 if (newOffset
!= scrollOffset()) {
916 emit
scrollTo(newOffset
);
921 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
925 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
926 while (it
.hasNext()) {
928 const int index
= it
.key();
929 KItemListWidget
* widget
= it
.value();
930 widget
->setSelected(current
.contains(index
));
934 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
935 KItemListViewAnimation::AnimationType type
)
937 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
938 Q_ASSERT(itemListWidget
);
941 case KItemListViewAnimation::DeleteAnimation
: {
942 // As we recycle the widget in this case it is important to assure that no
943 // other animation has been started. This is a convention in KItemListView and
944 // not a requirement defined by KItemListViewAnimation.
945 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
947 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
948 // by m_visibleWidgets and must be deleted manually after the animation has
950 recycleGroupHeaderForWidget(itemListWidget
);
951 m_widgetCreator
->recycle(itemListWidget
);
955 case KItemListViewAnimation::CreateAnimation
:
956 case KItemListViewAnimation::MovingAnimation
:
957 case KItemListViewAnimation::ResizeAnimation
: {
958 const int index
= itemListWidget
->index();
959 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
960 (index
> m_layouter
->lastVisibleIndex());
961 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
962 recycleWidget(itemListWidget
);
971 void KItemListView::slotLayoutTimerFinished()
973 m_layouter
->setSize(geometry().size());
974 doLayout(Animation
, 0, 0);
977 void KItemListView::slotRubberBandPosChanged()
982 void KItemListView::slotRubberBandActivationChanged(bool active
)
985 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
986 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
987 m_skipAutoScrollForRubberBand
= true;
989 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
990 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
991 m_skipAutoScrollForRubberBand
= false;
997 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1001 Q_UNUSED(previousWidth
);
1003 m_useHeaderWidths
= true;
1005 if (m_visibleRolesSizes
.contains(role
)) {
1006 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1007 roleSize
.setWidth(currentWidth
);
1008 m_visibleRolesSizes
.insert(role
, roleSize
);
1009 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1011 // Apply the new size to the layouter
1012 QSizeF dynamicItemSize
= m_itemSize
;
1013 if (dynamicItemSize
.width() < 0) {
1014 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1015 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1017 if (dynamicItemSize
.height() < 0) {
1018 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1019 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1022 m_layouter
->setItemSize(dynamicItemSize
);
1024 // Update the role sizes for all visible widgets
1025 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1026 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1033 void KItemListView::triggerAutoScrolling()
1035 if (!m_autoScrollTimer
) {
1040 int visibleSize
= 0;
1041 if (scrollOrientation() == Qt::Vertical
) {
1042 pos
= m_mousePos
.y();
1043 visibleSize
= size().height();
1045 pos
= m_mousePos
.x();
1046 visibleSize
= size().width();
1049 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1050 m_autoScrollIncrement
= 0;
1053 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1054 if (m_autoScrollIncrement
== 0) {
1055 // The mouse position is not above an autoscroll margin (the autoscroll timer
1056 // will be restarted in mouseMoveEvent())
1057 m_autoScrollTimer
->stop();
1061 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1062 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1063 // if the direction of the rubberband is similar to the autoscroll direction. This
1064 // prevents that starting to create a rubberband within the autoscroll margins starts
1065 // an autoscrolling.
1067 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1068 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1069 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1070 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1071 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1072 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1073 // been moved up although the autoscroll direction might be down)
1074 m_autoScrollTimer
->stop();
1079 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1080 // the autoscrolling may not get skipped anymore until a new rubberband is created
1081 m_skipAutoScrollForRubberBand
= false;
1083 setScrollOffset(scrollOffset() + m_autoScrollIncrement
);
1085 // Trigger the autoscroll timer which will periodically call
1086 // triggerAutoScrolling()
1087 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1090 void KItemListView::setController(KItemListController
* controller
)
1092 if (m_controller
!= controller
) {
1093 KItemListController
* previous
= m_controller
;
1095 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1096 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1097 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1100 m_controller
= controller
;
1103 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1104 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1105 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1108 onControllerChanged(controller
, previous
);
1112 void KItemListView::setModel(KItemModelBase
* model
)
1114 if (m_model
== model
) {
1118 KItemModelBase
* previous
= m_model
;
1121 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1122 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1123 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1124 this, SLOT(slotItemsInserted(KItemRangeList
)));
1125 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1126 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1127 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1128 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1129 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1130 this, SLOT(slotGroupedSortingChanged(bool)));
1134 m_layouter
->setModel(model
);
1135 m_grouped
= model
->groupedSorting();
1138 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1139 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1140 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1141 this, SLOT(slotItemsInserted(KItemRangeList
)));
1142 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1143 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1144 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1145 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1146 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1147 this, SLOT(slotGroupedSortingChanged(bool)));
1150 onModelChanged(model
, previous
);
1153 KItemListRubberBand
* KItemListView::rubberBand() const
1155 return m_rubberBand
;
1158 void KItemListView::updateLayout()
1160 doLayout(Animation
, 0, 0);
1164 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1166 if (m_layoutTimer
->isActive()) {
1167 kDebug() << "Stopping layout timer, synchronous layout requested";
1168 m_layoutTimer
->stop();
1171 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
1175 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1176 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1177 if (firstVisibleIndex
< 0) {
1178 emitOffsetChanges();
1182 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1183 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1184 // is still shown if the maximum offset got decreased.
1185 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1186 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1187 if (scrollOffset() > maxOffsetToShowFullRange
) {
1188 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1191 // Determine all items that are completely invisible and might be
1192 // reused for items that just got (at least partly) visible.
1193 // Items that do e.g. an animated moving of their position are not
1194 // marked as invisible: This assures that a scrolling inside the view
1195 // can be done without breaking an animation.
1196 QList
<int> reusableItems
;
1197 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1198 while (it
.hasNext()) {
1200 KItemListWidget
* widget
= it
.value();
1201 const int index
= widget
->index();
1202 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1203 if (invisible
&& !m_animation
->isStarted(widget
)) {
1204 widget
->setVisible(false);
1205 reusableItems
.append(index
);
1209 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1210 // instances from invisible items are reused. If no reusable items are
1211 // found then new KItemListWidget instances get created.
1212 const bool animate
= (hint
== Animation
);
1213 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1214 bool applyNewPos
= true;
1215 bool wasHidden
= false;
1217 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1218 const QPointF newPos
= itemBounds
.topLeft();
1219 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1222 if (!reusableItems
.isEmpty()) {
1223 // Reuse a KItemListWidget instance from an invisible item
1224 const int oldIndex
= reusableItems
.takeLast();
1225 widget
= m_visibleItems
.value(oldIndex
);
1226 setWidgetIndex(widget
, i
);
1228 // No reusable KItemListWidget instance is available, create a new one
1229 widget
= createWidget(i
);
1231 widget
->resize(itemBounds
.size());
1233 if (animate
&& changedCount
< 0) {
1234 // Items have been deleted, move the created item to the
1235 // imaginary old position.
1236 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1237 if (itemRect
.isEmpty()) {
1238 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1239 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1240 widget
->setPos(invisibleOldPos
);
1242 widget
->setPos(itemRect
.topLeft());
1244 applyNewPos
= false;
1246 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1247 applyNewPos
= false;
1251 const bool itemsRemoved
= (changedCount
< 0);
1252 const bool itemsInserted
= (changedCount
> 0);
1254 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1255 // The item is located after the removed items. Animate the moving of the position.
1256 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1257 applyNewPos
= false;
1258 } else if (itemsInserted
&& i
>= changedIndex
) {
1259 // The item is located after the first inserted item
1260 if (i
<= changedIndex
+ changedCount
- 1) {
1261 // The item is an inserted item. Animate the appearing of the item.
1262 // For performance reasons no animation is done when changedCount is equal
1263 // to all available items.
1264 if (changedCount
< m_model
->count()) {
1265 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1267 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1268 // The item was already there before, so animate the moving of the position.
1269 // No moving animation is done if the item is animated by a create animation: This
1270 // prevents a "move animation mess" when inserting several ranges in parallel.
1271 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1272 applyNewPos
= false;
1274 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1275 // The size of the view might have been changed. Animate the moving of the position.
1276 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1277 applyNewPos
= false;
1282 widget
->setPos(newPos
);
1285 Q_ASSERT(widget
->index() == i
);
1286 widget
->setVisible(true);
1288 if (widget
->size() != itemBounds
.size()) {
1289 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1293 // Delete invisible KItemListWidget instances that have not been reused
1294 foreach (int index
, reusableItems
) {
1295 recycleWidget(m_visibleItems
.value(index
));
1299 // Update the layout of all visible group headers
1300 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1301 while (it
.hasNext()) {
1303 updateGroupHeaderLayout(it
.key());
1307 emitOffsetChanges();
1310 void KItemListView::emitOffsetChanges()
1312 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1313 if (m_oldScrollOffset
!= newScrollOffset
) {
1314 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1315 m_oldScrollOffset
= newScrollOffset
;
1318 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1319 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1320 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1321 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1324 const qreal newItemOffset
= m_layouter
->itemOffset();
1325 if (m_oldItemOffset
!= newItemOffset
) {
1326 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1327 m_oldItemOffset
= newItemOffset
;
1330 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1331 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1332 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1333 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1337 KItemListWidget
* KItemListView::createWidget(int index
)
1339 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1340 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1342 updateWidgetProperties(widget
, index
);
1343 m_visibleItems
.insert(index
, widget
);
1346 updateGroupHeaderForWidget(widget
);
1349 initializeItemListWidget(widget
);
1353 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1356 recycleGroupHeaderForWidget(widget
);
1359 m_visibleItems
.remove(widget
->index());
1360 m_widgetCreator
->recycle(widget
);
1363 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1365 const int oldIndex
= widget
->index();
1366 m_visibleItems
.remove(oldIndex
);
1367 updateWidgetProperties(widget
, index
);
1368 m_visibleItems
.insert(index
, widget
);
1371 updateGroupHeaderForWidget(widget
);
1374 initializeItemListWidget(widget
);
1377 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1379 // Calculate the first visible index and last visible index for the current size
1380 const int currentFirst
= m_layouter
->firstVisibleIndex();
1381 const int currentLast
= m_layouter
->lastVisibleIndex();
1383 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1385 // Calculate the first visible index and last visible index for the new size
1386 setLayouterSize(size
, sizeType
);
1387 const int newFirst
= m_layouter
->firstVisibleIndex();
1388 const int newLast
= m_layouter
->lastVisibleIndex();
1390 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1391 // At least one index has been changed. Assure that widgets for all possible
1392 // visible items get created so that a move-animation can be started later.
1393 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1394 int minFirst
= qMin(newFirst
, currentFirst
);
1395 const int maxLast
= qMax(newLast
, currentLast
);
1397 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1398 // Increasing the size might result in a smaller KItemListView::offset().
1399 // Decrease the first visible index in a way that at least the maximum
1400 // visible items are shown.
1401 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1404 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1405 // The creating of widgets is quite expensive. Assure that never more
1406 // than 50 % of the maximum visible items get created for the animations.
1410 setLayouterSize(currentSize
, sizeType
);
1411 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1412 if (!m_visibleItems
.contains(i
)) {
1413 KItemListWidget
* widget
= createWidget(i
);
1414 const QPointF pos
= m_layouter
->itemRect(i
).topLeft();
1415 widget
->setPos(pos
);
1418 setLayouterSize(size
, sizeType
);
1422 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1425 case LayouterSize
: m_layouter
->setSize(size
); break;
1426 case ItemSize
: m_layouter
->setItemSize(size
); break;
1431 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1433 widget
->setVisibleRoles(m_visibleRoles
);
1434 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1435 widget
->setStyleOption(m_styleOption
);
1437 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1438 widget
->setCurrent(index
== selectionManager
->currentItem());
1439 widget
->setSelected(selectionManager
->isSelected(index
));
1440 widget
->setHovered(false);
1441 widget
->setAlternatingBackgroundColors(false);
1442 widget
->setIndex(index
);
1443 widget
->setData(m_model
->data(index
));
1446 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1448 const int index
= widget
->index();
1449 if (!m_layouter
->isFirstGroupItem(index
)) {
1450 // The widget does not represent the first item of a group
1451 // and hence requires no header
1452 recycleGroupHeaderForWidget(widget
);
1456 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1458 header
= m_groupHeaderCreator
->create(this);
1459 header
->setParentItem(widget
);
1460 m_visibleGroups
.insert(widget
, header
);
1462 Q_ASSERT(header
->parentItem() == widget
);
1464 // Determine the shown data for the header by doing a binary
1465 // search in the groups-list
1466 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1468 int max
= groups
.count() - 1;
1471 mid
= (min
+ max
) / 2;
1472 if (index
> groups
.at(mid
).first
) {
1477 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1479 header
->setData(groups
.at(mid
).second
);
1480 header
->setRole(model()->sortRole());
1485 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1487 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1490 const int index
= widget
->index();
1491 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1492 const QRectF itemRect
= m_layouter
->itemRect(index
);
1494 // The group-header is a child of the itemlist widget. Translate the
1495 // group header position to the relative position.
1496 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1497 - groupHeaderRect
.height());
1498 header
->setPos(groupHeaderPos
);
1499 header
->resize(groupHeaderRect
.size());
1502 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1504 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1506 header
->setParentItem(0);
1507 m_groupHeaderCreator
->recycle(header
);
1508 m_visibleGroups
.remove(widget
);
1512 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1514 QHash
<QByteArray
, qreal
> rolesWidths
;
1516 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1517 while (it
.hasNext()) {
1519 rolesWidths
.insert(it
.key(), it
.value().width());
1525 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1527 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1531 const int itemCount
= m_model
->count();
1532 int rangesItemCount
= 0;
1533 foreach (const KItemRange
& range
, itemRanges
) {
1534 rangesItemCount
+= range
.count
;
1537 if (itemCount
== rangesItemCount
) {
1538 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1540 // Assure the the sizes are not smaller than the minimum defined by the header
1541 // TODO: Currently only implemented for a top-aligned header
1542 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1543 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1544 while (it
.hasNext()) {
1546 const QSizeF
& size
= it
.value();
1547 if (size
.width() < minHeaderRoleWidth
) {
1548 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1549 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1554 // Only a sub range of the roles need to be determined.
1555 // The chances are good that the sizes of the sub ranges
1556 // already fit into the available sizes and hence no
1557 // expensive update might be required.
1558 bool updateRequired
= false;
1560 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1561 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1562 while (it
.hasNext()) {
1564 const QByteArray
& role
= it
.key();
1565 const QSizeF
& updatedSize
= it
.value();
1566 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1567 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1568 m_visibleRolesSizes
.insert(role
, updatedSize
);
1569 updateRequired
= true;
1573 if (!updateRequired
) {
1574 // All the updated sizes are smaller than the current sizes and no change
1575 // of the stretched roles-widths is required
1580 updateStretchedVisibleRolesSizes();
1583 void KItemListView::updateVisibleRolesSizes()
1585 const int itemCount
= m_model
->count();
1586 if (itemCount
> 0) {
1587 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1591 void KItemListView::updateStretchedVisibleRolesSizes()
1593 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1597 // Calculate the maximum size of an item by considering the
1598 // visible role sizes and apply them to the layouter. If the
1599 // size does not use the available view-size it the size of the
1600 // first role will get stretched.
1601 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1602 const QByteArray role
= visibleRoles().first();
1603 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1605 QSizeF dynamicItemSize
= m_itemSize
;
1607 if (dynamicItemSize
.width() <= 0) {
1608 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1609 const qreal availableWidth
= size().width();
1610 if (requiredWidth
< availableWidth
) {
1611 // Stretch the first role to use the whole width for the item
1612 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1613 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1615 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1618 if (dynamicItemSize
.height() <= 0) {
1619 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1620 const qreal availableHeight
= size().height();
1621 if (requiredHeight
< availableHeight
) {
1622 // Stretch the first role to use the whole height for the item
1623 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1624 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1626 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1629 m_layouter
->setItemSize(dynamicItemSize
);
1632 m_header
->setVisibleRolesWidths(headerRolesWidths());
1633 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1636 // Update the role sizes for all visible widgets
1637 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1638 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1642 qreal
KItemListView::visibleRolesSizesWidthSum() const
1645 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1646 while (it
.hasNext()) {
1648 widthSum
+= it
.value().width();
1653 qreal
KItemListView::visibleRolesSizesHeightSum() const
1655 qreal heightSum
= 0;
1656 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1657 while (it
.hasNext()) {
1659 heightSum
+= it
.value().height();
1664 QRectF
KItemListView::headerBoundaries() const
1666 return m_header
? m_header
->geometry() : QRectF();
1669 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1673 const int minSpeed
= 4;
1674 const int maxSpeed
= 128;
1675 const int speedLimiter
= 96;
1676 const int autoScrollBorder
= 64;
1678 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1679 // This assures that the autoscrolling speed grows gradually.
1680 const int incLimiter
= 1;
1682 if (pos
< autoScrollBorder
) {
1683 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1684 inc
= qMax(inc
, -maxSpeed
);
1685 inc
= qMax(inc
, oldInc
- incLimiter
);
1686 } else if (pos
> range
- autoScrollBorder
) {
1687 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1688 inc
= qMin(inc
, maxSpeed
);
1689 inc
= qMin(inc
, oldInc
+ incLimiter
);
1697 KItemListCreatorBase::~KItemListCreatorBase()
1699 qDeleteAll(m_recycleableWidgets
);
1700 qDeleteAll(m_createdWidgets
);
1703 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1705 m_createdWidgets
.insert(widget
);
1708 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1710 Q_ASSERT(m_createdWidgets
.contains(widget
));
1711 m_createdWidgets
.remove(widget
);
1713 if (m_recycleableWidgets
.count() < 100) {
1714 m_recycleableWidgets
.append(widget
);
1715 widget
->setVisible(false);
1721 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1723 if (m_recycleableWidgets
.isEmpty()) {
1727 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1728 m_createdWidgets
.insert(widget
);
1732 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1736 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1738 widget
->setParentItem(0);
1739 widget
->setOpacity(1.0);
1740 pushRecycleableWidget(widget
);
1743 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1747 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1749 header
->setOpacity(1.0);
1750 pushRecycleableWidget(header
);
1753 #include "kitemlistview.moc"