1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "kitemlistcontroller.h"
26 #include "kitemlistheader_p.h"
27 #include "kitemlistrubberband_p.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistsizehintresolver_p.h"
30 #include "kitemlistviewlayouter_p.h"
31 #include "kitemlistviewanimation_p.h"
32 #include "kitemlistwidget.h"
37 #include <QGraphicsSceneMouseEvent>
39 #include <QPropertyAnimation>
41 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
54 QGraphicsWidget(parent
),
55 m_enabledSelectionToggles(false),
57 m_activeTransactions(0),
62 m_visibleRolesSizes(),
63 m_stretchedVisibleRolesSizes(),
65 m_groupHeaderCreator(0),
69 m_sizeHintResolver(0),
74 m_oldMaximumScrollOffset(0),
76 m_oldMaximumItemOffset(0),
77 m_skipAutoScrollForRubberBand(false),
80 m_autoScrollIncrement(0),
83 m_useHeaderWidths(false)
85 setAcceptHoverEvents(true);
87 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
89 m_layouter
= new KItemListViewLayouter(this);
90 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
92 m_animation
= new KItemListViewAnimation(this);
93 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
94 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
96 m_layoutTimer
= new QTimer(this);
97 m_layoutTimer
->setInterval(300);
98 m_layoutTimer
->setSingleShot(true);
99 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
101 m_rubberBand
= new KItemListRubberBand(this);
102 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
105 KItemListView::~KItemListView()
107 delete m_sizeHintResolver
;
108 m_sizeHintResolver
= 0;
111 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
113 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
114 if (orientation
== previousOrientation
) {
118 m_layouter
->setScrollOrientation(orientation
);
119 m_animation
->setScrollOrientation(orientation
);
120 m_sizeHintResolver
->clearCache();
123 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
124 while (it
.hasNext()) {
126 it
.value()->setScrollOrientation(orientation
);
132 onScrollOrientationChanged(orientation
, previousOrientation
);
133 emit
scrollOrientationChanged(orientation
, previousOrientation
);
136 Qt::Orientation
KItemListView::scrollOrientation() const
138 return m_layouter
->scrollOrientation();
141 void KItemListView::setItemSize(const QSizeF
& itemSize
)
143 const QSizeF previousSize
= m_itemSize
;
144 if (itemSize
== previousSize
) {
148 m_itemSize
= itemSize
;
150 const bool emptySize
= itemSize
.isEmpty();
152 updateVisibleRolesSizes();
154 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
155 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
157 m_layouter
->setItemSize(itemSize
);
161 m_sizeHintResolver
->clearCache();
163 onItemSizeChanged(itemSize
, previousSize
);
166 QSizeF
KItemListView::itemSize() const
171 void KItemListView::setScrollOffset(qreal offset
)
177 const qreal previousOffset
= m_layouter
->scrollOffset();
178 if (offset
== previousOffset
) {
182 m_layouter
->setScrollOffset(offset
);
183 m_animation
->setScrollOffset(offset
);
185 // Don't check whether the m_layoutTimer is active: Changing the
186 // scroll offset must always trigger a synchronous layout, otherwise
187 // the smooth-scrolling might get jerky.
188 doLayout(NoAnimation
);
189 onScrollOffsetChanged(offset
, previousOffset
);
192 qreal
KItemListView::scrollOffset() const
194 return m_layouter
->scrollOffset();
197 qreal
KItemListView::maximumScrollOffset() const
199 return m_layouter
->maximumScrollOffset();
202 void KItemListView::setItemOffset(qreal offset
)
204 if (m_layouter
->itemOffset() == offset
) {
208 m_layouter
->setItemOffset(offset
);
210 m_header
->setPos(-offset
, 0);
213 // Don't check whether the m_layoutTimer is active: Changing the
214 // item offset must always trigger a synchronous layout, otherwise
215 // the smooth-scrolling might get jerky.
216 doLayout(NoAnimation
);
219 qreal
KItemListView::itemOffset() const
221 return m_layouter
->itemOffset();
224 qreal
KItemListView::maximumItemOffset() const
226 return m_layouter
->maximumItemOffset();
229 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
231 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
232 m_visibleRoles
= roles
;
234 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
235 while (it
.hasNext()) {
237 KItemListWidget
* widget
= it
.value();
238 widget
->setVisibleRoles(roles
);
239 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
242 m_sizeHintResolver
->clearCache();
243 m_layouter
->markAsDirty();
246 m_header
->setVisibleRoles(roles
);
247 m_header
->setVisibleRolesWidths(headerRolesWidths());
248 m_useHeaderWidths
= false;
251 updateVisibleRolesSizes();
254 onVisibleRolesChanged(roles
, previousRoles
);
257 QList
<QByteArray
> KItemListView::visibleRoles() const
259 return m_visibleRoles
;
262 void KItemListView::setAutoScroll(bool enabled
)
264 if (enabled
&& !m_autoScrollTimer
) {
265 m_autoScrollTimer
= new QTimer(this);
266 m_autoScrollTimer
->setSingleShot(false);
267 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
268 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
269 } else if (!enabled
&& m_autoScrollTimer
) {
270 delete m_autoScrollTimer
;
271 m_autoScrollTimer
= 0;
276 bool KItemListView::autoScroll() const
278 return m_autoScrollTimer
!= 0;
281 void KItemListView::setEnabledSelectionToggles(bool enabled
)
283 if (m_enabledSelectionToggles
!= enabled
) {
284 m_enabledSelectionToggles
= enabled
;
286 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
287 while (it
.hasNext()) {
289 it
.value()->setEnabledSelectionToggle(enabled
);
294 bool KItemListView::enabledSelectionToggles() const
296 return m_enabledSelectionToggles
;
299 KItemListController
* KItemListView::controller() const
304 KItemModelBase
* KItemListView::model() const
309 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
311 m_widgetCreator
= widgetCreator
;
314 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
316 return m_widgetCreator
;
319 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
321 m_groupHeaderCreator
= groupHeaderCreator
;
324 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
326 return m_groupHeaderCreator
;
329 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
331 const KItemListStyleOption previousOption
= m_styleOption
;
332 m_styleOption
= option
;
334 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
335 while (it
.hasNext()) {
337 it
.value()->setStyleOption(option
);
340 m_sizeHintResolver
->clearCache();
342 onStyleOptionChanged(option
, previousOption
);
345 const KItemListStyleOption
& KItemListView::styleOption() const
347 return m_styleOption
;
350 void KItemListView::setGeometry(const QRectF
& rect
)
352 QGraphicsWidget::setGeometry(rect
);
358 const QSizeF newSize
= rect
.size();
359 if (m_itemSize
.isEmpty()) {
360 // The item size is dynamic:
361 // Changing the geometry does not require to do an expensive
362 // update of the visible-roles sizes, only the stretched sizes
363 // need to be adjusted to the new size.
364 updateStretchedVisibleRolesSizes();
366 if (m_useHeaderWidths
) {
367 QSizeF dynamicItemSize
= m_layouter
->itemSize();
369 if (m_itemSize
.width() < 0) {
370 const qreal requiredWidth
= visibleRolesSizesWidthSum();
371 if (newSize
.width() > requiredWidth
) {
372 dynamicItemSize
.setWidth(newSize
.width());
374 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
375 m_header
->resize(headerWidth
, m_header
->size().height());
378 if (m_itemSize
.height() < 0) {
379 const qreal requiredHeight
= visibleRolesSizesHeightSum();
380 if (newSize
.height() > requiredHeight
) {
381 dynamicItemSize
.setHeight(newSize
.height());
383 // TODO: KItemListHeader is not prepared for vertical alignment
386 m_layouter
->setItemSize(dynamicItemSize
);
389 // Triggering a synchronous layout is fine from a performance point of view,
390 // as with dynamic item sizes no moving animation must be done.
391 m_layouter
->setSize(newSize
);
394 // The item size is not dynamic and most probably the geometry change results
395 // in animated position changes of the items. Trigger an asynchronous relayout
396 // with m_layoutTimer to prevent performance bottlenecks.
397 if (m_model
->count() > 0) {
398 prepareLayoutForIncreasedItemCount(newSize
, LayouterSize
);
400 m_layouter
->setSize(newSize
);
403 if (!m_layoutTimer
->isActive()) {
404 m_layoutTimer
->start();
409 int KItemListView::itemAt(const QPointF
& pos
) const
411 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
412 while (it
.hasNext()) {
415 const KItemListWidget
* widget
= it
.value();
416 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
417 if (widget
->contains(mappedPos
)) {
425 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
427 if (!m_enabledSelectionToggles
) {
431 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
433 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
434 if (!selectionToggleRect
.isEmpty()) {
435 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
436 return selectionToggleRect
.contains(mappedPos
);
442 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
444 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
446 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
447 if (!expansionToggleRect
.isEmpty()) {
448 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
449 return expansionToggleRect
.contains(mappedPos
);
455 int KItemListView::firstVisibleIndex() const
457 return m_layouter
->firstVisibleIndex();
460 int KItemListView::lastVisibleIndex() const
462 return m_layouter
->lastVisibleIndex();
465 QSizeF
KItemListView::itemSizeHint(int index
) const
471 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
473 Q_UNUSED(itemRanges
);
474 return QHash
<QByteArray
, QSizeF
>();
477 bool KItemListView::supportsItemExpanding() const
482 QRectF
KItemListView::itemRect(int index
) const
484 return m_layouter
->itemRect(index
);
487 QRectF
KItemListView::itemContextRect(int index
) const
491 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
493 contextRect
= widget
->iconRect() | widget
->textRect();
494 contextRect
.translate(itemRect(index
).topLeft());
500 void KItemListView::scrollToItem(int index
)
502 QRectF viewGeometry
= geometry();
504 const qreal headerHeight
= m_header
->size().height();
505 viewGeometry
.adjust(0, headerHeight
, 0, 0);
507 const QRectF currentRect
= itemRect(index
);
509 if (!viewGeometry
.contains(currentRect
)) {
510 qreal newOffset
= scrollOffset();
511 if (currentRect
.top() < viewGeometry
.top()) {
512 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
513 newOffset
+= currentRect
.top() - viewGeometry
.top();
514 } else if ((currentRect
.bottom() > viewGeometry
.bottom())) {
515 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
516 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
517 } else if (currentRect
.left() < viewGeometry
.left()) {
518 if (scrollOrientation() == Qt::Horizontal
) {
519 newOffset
+= currentRect
.left() - viewGeometry
.left();
521 } else if ((currentRect
.right() > viewGeometry
.right())) {
522 if (scrollOrientation() == Qt::Horizontal
) {
523 newOffset
+= currentRect
.right() - viewGeometry
.right();
527 if (newOffset
!= scrollOffset()) {
528 emit
scrollTo(newOffset
);
533 void KItemListView::beginTransaction()
535 ++m_activeTransactions
;
536 if (m_activeTransactions
== 1) {
537 onTransactionBegin();
541 void KItemListView::endTransaction()
543 --m_activeTransactions
;
544 if (m_activeTransactions
< 0) {
545 m_activeTransactions
= 0;
546 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
549 if (m_activeTransactions
== 0) {
555 bool KItemListView::isTransactionActive() const
557 return m_activeTransactions
> 0;
561 void KItemListView::setHeaderShown(bool show
)
564 if (show
&& !m_header
) {
565 m_header
= new KItemListHeader(this);
566 m_header
->setPos(0, 0);
567 m_header
->setModel(m_model
);
568 m_header
->setVisibleRoles(m_visibleRoles
);
569 m_header
->setVisibleRolesWidths(headerRolesWidths());
570 m_header
->setZValue(1);
572 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
573 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
574 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
575 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
576 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
577 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
579 m_useHeaderWidths
= false;
581 m_layouter
->setHeaderHeight(m_header
->size().height());
582 } else if (!show
&& m_header
) {
585 m_useHeaderWidths
= false;
586 m_layouter
->setHeaderHeight(0);
590 bool KItemListView::isHeaderShown() const
592 return m_header
!= 0;
595 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
601 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
603 QGraphicsWidget::paint(painter
, option
, widget
);
605 if (m_rubberBand
->isActive()) {
606 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
607 m_rubberBand
->endPosition()).normalized();
609 const QPointF topLeft
= rubberBandRect
.topLeft();
610 if (scrollOrientation() == Qt::Vertical
) {
611 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
613 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
616 QStyleOptionRubberBand opt
;
617 opt
.initFrom(widget
);
618 opt
.shape
= QRubberBand::Rectangle
;
620 opt
.rect
= rubberBandRect
.toRect();
621 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
625 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
630 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
632 Q_UNUSED(changedRoles
);
636 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
642 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
648 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
654 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
660 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
666 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
672 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
678 void KItemListView::onTransactionBegin()
682 void KItemListView::onTransactionEnd()
686 bool KItemListView::event(QEvent
* event
)
688 // Forward all events to the controller and handle them there
689 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
693 return QGraphicsWidget::event(event
);
696 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
698 m_mousePos
= transform().map(event
->pos());
702 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
704 QGraphicsWidget::mouseMoveEvent(event
);
706 m_mousePos
= transform().map(event
->pos());
707 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
708 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
712 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
714 event
->setAccepted(true);
718 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
720 QGraphicsWidget::dragMoveEvent(event
);
722 m_mousePos
= transform().map(event
->pos());
723 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
724 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
728 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
730 QGraphicsWidget::dragLeaveEvent(event
);
731 setAutoScroll(false);
734 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
736 QGraphicsWidget::dropEvent(event
);
737 setAutoScroll(false);
740 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
742 return m_visibleItems
.values();
745 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
747 updateVisibleRolesSizes(itemRanges
);
749 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
750 if (hasMultipleRanges
) {
754 int previouslyInsertedCount
= 0;
755 foreach (const KItemRange
& range
, itemRanges
) {
756 // range.index is related to the model before anything has been inserted.
757 // As in each loop the current item-range gets inserted the index must
758 // be increased by the already previously inserted items.
759 const int index
= range
.index
+ previouslyInsertedCount
;
760 const int count
= range
.count
;
761 if (index
< 0 || count
<= 0) {
762 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
765 previouslyInsertedCount
+= count
;
767 m_sizeHintResolver
->itemsInserted(index
, count
);
769 // Determine which visible items must be moved
770 QList
<int> itemsToMove
;
771 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
772 while (it
.hasNext()) {
774 const int visibleItemIndex
= it
.key();
775 if (visibleItemIndex
>= index
) {
776 itemsToMove
.append(visibleItemIndex
);
780 // Update the indexes of all KItemListWidget instances that are located
781 // after the inserted items. It is important to adjust the indexes in the order
782 // from the highest index to the lowest index to prevent overlaps when setting the new index.
784 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
785 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
787 setWidgetIndex(widget
, widget
->index() + count
);
790 m_layouter
->markAsDirty();
791 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
792 // Check whether a scrollbar is required to show the inserted items. In this case
793 // the size of the layouter will be decreased before calling doLayout(): This prevents
794 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
795 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
796 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
797 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
798 if (decreaseLayouterSize
) {
799 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
800 QSizeF layouterSize
= m_layouter
->size();
801 if (verticalScrollOrientation
) {
802 layouterSize
.rwidth() -= scrollBarExtent
;
804 layouterSize
.rheight() -= scrollBarExtent
;
806 m_layouter
->setSize(layouterSize
);
810 if (!hasMultipleRanges
) {
811 doLayout(Animation
, index
, count
);
816 m_controller
->selectionManager()->itemsInserted(itemRanges
);
819 if (hasMultipleRanges
) {
824 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
826 updateVisibleRolesSizes();
828 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
829 if (hasMultipleRanges
) {
833 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
834 const KItemRange
& range
= itemRanges
.at(i
);
835 const int index
= range
.index
;
836 const int count
= range
.count
;
837 if (index
< 0 || count
<= 0) {
838 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
842 m_sizeHintResolver
->itemsRemoved(index
, count
);
844 const int firstRemovedIndex
= index
;
845 const int lastRemovedIndex
= index
+ count
- 1;
846 const int lastIndex
= m_model
->count() + count
- 1;
848 // Remove all KItemListWidget instances that got deleted
849 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
850 KItemListWidget
* widget
= m_visibleItems
.value(i
);
855 m_animation
->stop(widget
);
856 // Stopping the animation might lead to recycling the widget if
857 // it is invisible (see slotAnimationFinished()).
858 // Check again whether it is still visible:
859 if (!m_visibleItems
.contains(i
)) {
863 if (m_model
->count() == 0) {
864 // For performance reasons no animation is done when all items have
866 recycleWidget(widget
);
868 // Animate the removing of the items. Special case: When removing an item there
869 // is no valid model index available anymore. For the
870 // remove-animation the item gets removed from m_visibleItems but the widget
871 // will stay alive until the animation has been finished and will
872 // be recycled (deleted) in KItemListView::slotAnimationFinished().
873 m_visibleItems
.remove(i
);
874 widget
->setIndex(-1);
875 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
879 // Update the indexes of all KItemListWidget instances that are located
880 // after the deleted items
881 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
882 KItemListWidget
* widget
= m_visibleItems
.value(i
);
884 const int newIndex
= i
- count
;
885 setWidgetIndex(widget
, newIndex
);
889 m_layouter
->markAsDirty();
890 if (!hasMultipleRanges
) {
891 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
892 // assumes an updated geometry. If items are removed during an active transaction,
893 // the transaction will be temporary deactivated so that doLayout() triggers a
894 // geometry update if necessary.
895 const int activeTransactions
= m_activeTransactions
;
896 m_activeTransactions
= 0;
897 doLayout(Animation
, index
, -count
);
898 m_activeTransactions
= activeTransactions
;
903 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
906 if (hasMultipleRanges
) {
911 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
913 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
914 m_layouter
->markAsDirty();
917 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
920 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
921 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
923 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
924 KItemListWidget
* widget
= m_visibleItems
.value(index
);
926 updateWidgetProperties(widget
, index
);
928 updateGroupHeaderForWidget(widget
);
930 initializeItemListWidget(widget
);
934 doLayout(NoAnimation
);
937 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
938 const QSet
<QByteArray
>& roles
)
940 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
941 if (updateSizeHints
) {
942 updateVisibleRolesSizes(itemRanges
);
945 foreach (const KItemRange
& itemRange
, itemRanges
) {
946 const int index
= itemRange
.index
;
947 const int count
= itemRange
.count
;
949 if (updateSizeHints
) {
950 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
951 m_layouter
->markAsDirty();
953 if (!m_layoutTimer
->isActive()) {
954 m_layoutTimer
->start();
958 // Apply the changed roles to the visible item-widgets
959 const int lastIndex
= index
+ count
- 1;
960 for (int i
= index
; i
<= lastIndex
; ++i
) {
961 KItemListWidget
* widget
= m_visibleItems
.value(i
);
963 widget
->setData(m_model
->data(i
), roles
);
967 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
968 // The sort-role has been changed which might result
969 // in modified group headers
970 updateVisibleGroupHeaders();
971 doLayout(NoAnimation
);
976 void KItemListView::slotGroupedSortingChanged(bool current
)
979 m_layouter
->markAsDirty();
982 // Apply the height of the header to the layouter
983 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
984 m_styleOption
.margin
* 2;
985 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
987 updateVisibleGroupHeaders();
989 // Clear all visible headers
990 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
991 while (it
.hasNext()) {
993 recycleGroupHeaderForWidget(it
.key());
995 Q_ASSERT(m_visibleGroups
.isEmpty());
1001 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1006 updateVisibleGroupHeaders();
1007 doLayout(Animation
);
1011 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1016 updateVisibleGroupHeaders();
1017 doLayout(Animation
);
1021 void KItemListView::slotCurrentChanged(int current
, int previous
)
1025 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1026 if (previousWidget
) {
1027 Q_ASSERT(previousWidget
->isCurrent());
1028 previousWidget
->setCurrent(false);
1031 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1032 if (currentWidget
) {
1033 Q_ASSERT(!currentWidget
->isCurrent());
1034 currentWidget
->setCurrent(true);
1038 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1042 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1043 while (it
.hasNext()) {
1045 const int index
= it
.key();
1046 KItemListWidget
* widget
= it
.value();
1047 widget
->setSelected(current
.contains(index
));
1051 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1052 KItemListViewAnimation::AnimationType type
)
1054 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1055 Q_ASSERT(itemListWidget
);
1058 case KItemListViewAnimation::DeleteAnimation
: {
1059 // As we recycle the widget in this case it is important to assure that no
1060 // other animation has been started. This is a convention in KItemListView and
1061 // not a requirement defined by KItemListViewAnimation.
1062 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1064 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1065 // by m_visibleWidgets and must be deleted manually after the animation has
1067 recycleGroupHeaderForWidget(itemListWidget
);
1068 m_widgetCreator
->recycle(itemListWidget
);
1072 case KItemListViewAnimation::CreateAnimation
:
1073 case KItemListViewAnimation::MovingAnimation
:
1074 case KItemListViewAnimation::ResizeAnimation
: {
1075 const int index
= itemListWidget
->index();
1076 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1077 (index
> m_layouter
->lastVisibleIndex());
1078 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1079 recycleWidget(itemListWidget
);
1088 void KItemListView::slotLayoutTimerFinished()
1090 m_layouter
->setSize(geometry().size());
1091 doLayout(Animation
);
1094 void KItemListView::slotRubberBandPosChanged()
1099 void KItemListView::slotRubberBandActivationChanged(bool active
)
1102 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1103 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1104 m_skipAutoScrollForRubberBand
= true;
1106 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1107 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1108 m_skipAutoScrollForRubberBand
= false;
1114 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1116 qreal previousWidth
)
1118 Q_UNUSED(previousWidth
);
1120 m_useHeaderWidths
= true;
1122 if (m_visibleRolesSizes
.contains(role
)) {
1123 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1124 roleSize
.setWidth(currentWidth
);
1125 m_visibleRolesSizes
.insert(role
, roleSize
);
1126 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1128 // Apply the new size to the layouter
1129 QSizeF dynamicItemSize
= m_itemSize
;
1130 if (dynamicItemSize
.width() < 0) {
1131 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1132 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1134 if (dynamicItemSize
.height() < 0) {
1135 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1136 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1139 m_layouter
->setItemSize(dynamicItemSize
);
1141 // Update the role sizes for all visible widgets
1142 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1143 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1146 doLayout(Animation
);
1150 void KItemListView::triggerAutoScrolling()
1152 if (!m_autoScrollTimer
) {
1157 int visibleSize
= 0;
1158 if (scrollOrientation() == Qt::Vertical
) {
1159 pos
= m_mousePos
.y();
1160 visibleSize
= size().height();
1162 pos
= m_mousePos
.x();
1163 visibleSize
= size().width();
1166 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1167 m_autoScrollIncrement
= 0;
1170 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1171 if (m_autoScrollIncrement
== 0) {
1172 // The mouse position is not above an autoscroll margin (the autoscroll timer
1173 // will be restarted in mouseMoveEvent())
1174 m_autoScrollTimer
->stop();
1178 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1179 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1180 // if the direction of the rubberband is similar to the autoscroll direction. This
1181 // prevents that starting to create a rubberband within the autoscroll margins starts
1182 // an autoscrolling.
1184 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1185 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1186 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1187 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1188 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1189 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1190 // been moved up although the autoscroll direction might be down)
1191 m_autoScrollTimer
->stop();
1196 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1197 // the autoscrolling may not get skipped anymore until a new rubberband is created
1198 m_skipAutoScrollForRubberBand
= false;
1200 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1201 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1202 setScrollOffset(newScrollOffset
);
1204 // Trigger the autoscroll timer which will periodically call
1205 // triggerAutoScrolling()
1206 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1209 void KItemListView::setController(KItemListController
* controller
)
1211 if (m_controller
!= controller
) {
1212 KItemListController
* previous
= m_controller
;
1214 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1215 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1216 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1219 m_controller
= controller
;
1222 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1223 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1224 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1227 onControllerChanged(controller
, previous
);
1231 void KItemListView::setModel(KItemModelBase
* model
)
1233 if (m_model
== model
) {
1237 KItemModelBase
* previous
= m_model
;
1240 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1241 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1242 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1243 this, SLOT(slotItemsInserted(KItemRangeList
)));
1244 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1245 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1246 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1247 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1248 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1249 this, SLOT(slotGroupedSortingChanged(bool)));
1250 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1251 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1252 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1253 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1257 m_layouter
->setModel(model
);
1258 m_grouped
= model
->groupedSorting();
1261 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1262 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1263 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1264 this, SLOT(slotItemsInserted(KItemRangeList
)));
1265 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1266 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1267 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1268 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1269 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1270 this, SLOT(slotGroupedSortingChanged(bool)));
1271 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1272 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1273 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1274 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1277 onModelChanged(model
, previous
);
1280 KItemListRubberBand
* KItemListView::rubberBand() const
1282 return m_rubberBand
;
1285 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1287 if (m_layoutTimer
->isActive()) {
1288 m_layoutTimer
->stop();
1291 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1295 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1296 if (firstVisibleIndex
< 0) {
1297 emitOffsetChanges();
1301 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1302 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1303 // is still shown if the maximum offset got decreased.
1304 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1305 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1306 if (scrollOffset() > maxOffsetToShowFullRange
) {
1307 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1308 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1311 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1313 // Determine all items that are completely invisible and might be
1314 // reused for items that just got (at least partly) visible.
1315 // Items that do e.g. an animated moving of their position are not
1316 // marked as invisible: This assures that a scrolling inside the view
1317 // can be done without breaking an animation.
1318 QList
<int> reusableItems
;
1319 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1320 while (it
.hasNext()) {
1322 KItemListWidget
* widget
= it
.value();
1323 const int index
= widget
->index();
1324 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1325 if (invisible
&& !m_animation
->isStarted(widget
)) {
1326 widget
->setVisible(false);
1327 reusableItems
.append(index
);
1330 recycleGroupHeaderForWidget(widget
);
1335 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1336 // instances from invisible items are reused. If no reusable items are
1337 // found then new KItemListWidget instances get created.
1338 const bool animate
= (hint
== Animation
);
1339 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1340 bool applyNewPos
= true;
1341 bool wasHidden
= false;
1343 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1344 const QPointF newPos
= itemBounds
.topLeft();
1345 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1348 if (!reusableItems
.isEmpty()) {
1349 // Reuse a KItemListWidget instance from an invisible item
1350 const int oldIndex
= reusableItems
.takeLast();
1351 widget
= m_visibleItems
.value(oldIndex
);
1352 setWidgetIndex(widget
, i
);
1355 updateGroupHeaderForWidget(widget
);
1358 // No reusable KItemListWidget instance is available, create a new one
1359 widget
= createWidget(i
);
1361 widget
->resize(itemBounds
.size());
1363 if (animate
&& changedCount
< 0) {
1364 // Items have been deleted, move the created item to the
1365 // imaginary old position. They will get animated to the new position
1367 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1368 if (itemRect
.isEmpty()) {
1369 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1370 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1371 widget
->setPos(invisibleOldPos
);
1373 widget
->setPos(itemRect
.topLeft());
1375 applyNewPos
= false;
1377 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1378 applyNewPos
= false;
1382 const bool itemsRemoved
= (changedCount
< 0);
1383 const bool itemsInserted
= (changedCount
> 0);
1384 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1385 // The item is located after the removed items. Animate the moving of the position.
1386 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1387 applyNewPos
= false;
1388 } else if (itemsInserted
&& i
>= changedIndex
) {
1389 // The item is located after the first inserted item
1390 if (i
<= changedIndex
+ changedCount
- 1) {
1391 // The item is an inserted item. Animate the appearing of the item.
1392 // For performance reasons no animation is done when changedCount is equal
1393 // to all available items.
1394 if (changedCount
< m_model
->count()) {
1395 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1397 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1398 // The item was already there before, so animate the moving of the position.
1399 // No moving animation is done if the item is animated by a create animation: This
1400 // prevents a "move animation mess" when inserting several ranges in parallel.
1401 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1402 applyNewPos
= false;
1404 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1405 // The size of the view might have been changed. Animate the moving of the position.
1406 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1407 applyNewPos
= false;
1412 widget
->setPos(newPos
);
1415 Q_ASSERT(widget
->index() == i
);
1416 widget
->setVisible(true);
1418 if (widget
->size() != itemBounds
.size()) {
1419 // Resize the widget for the item to the changed size.
1421 // If a dynamic item size is used then no animation is done in the direction
1422 // of the dynamic size.
1423 if (m_itemSize
.width() <= 0) {
1424 // The width is dynamic, apply the new width without animation.
1425 widget
->resize(itemBounds
.width(), widget
->size().height());
1426 } else if (m_itemSize
.height() <= 0) {
1427 // The height is dynamic, apply the new height without animation.
1428 widget
->resize(widget
->size().width(), itemBounds
.height());
1430 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1432 widget
->resize(itemBounds
.size());
1437 // Delete invisible KItemListWidget instances that have not been reused
1438 foreach (int index
, reusableItems
) {
1439 recycleWidget(m_visibleItems
.value(index
));
1443 // Update the layout of all visible group headers
1444 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1445 while (it
.hasNext()) {
1447 updateGroupHeaderLayout(it
.key());
1451 emitOffsetChanges();
1454 void KItemListView::emitOffsetChanges()
1456 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1457 if (m_oldScrollOffset
!= newScrollOffset
) {
1458 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1459 m_oldScrollOffset
= newScrollOffset
;
1462 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1463 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1464 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1465 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1468 const qreal newItemOffset
= m_layouter
->itemOffset();
1469 if (m_oldItemOffset
!= newItemOffset
) {
1470 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1471 m_oldItemOffset
= newItemOffset
;
1474 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1475 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1476 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1477 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1481 KItemListWidget
* KItemListView::createWidget(int index
)
1483 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1484 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1486 updateWidgetProperties(widget
, index
);
1487 m_visibleItems
.insert(index
, widget
);
1490 updateGroupHeaderForWidget(widget
);
1493 initializeItemListWidget(widget
);
1497 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1500 recycleGroupHeaderForWidget(widget
);
1503 m_visibleItems
.remove(widget
->index());
1504 m_widgetCreator
->recycle(widget
);
1507 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1509 const int oldIndex
= widget
->index();
1510 m_visibleItems
.remove(oldIndex
);
1511 updateWidgetProperties(widget
, index
);
1512 m_visibleItems
.insert(index
, widget
);
1514 initializeItemListWidget(widget
);
1517 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1519 // Calculate the first visible index and last visible index for the current size
1520 const int currentFirst
= m_layouter
->firstVisibleIndex();
1521 const int currentLast
= m_layouter
->lastVisibleIndex();
1523 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1525 // Calculate the first visible index and last visible index for the new size
1526 setLayouterSize(size
, sizeType
);
1527 const int newFirst
= m_layouter
->firstVisibleIndex();
1528 const int newLast
= m_layouter
->lastVisibleIndex();
1530 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1531 // At least one index has been changed. Assure that widgets for all possible
1532 // visible items get created so that a move-animation can be started later.
1533 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1534 int minFirst
= qMin(newFirst
, currentFirst
);
1535 const int maxLast
= qMax(newLast
, currentLast
);
1537 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1538 // Increasing the size might result in a smaller KItemListView::offset().
1539 // Decrease the first visible index in a way that at least the maximum
1540 // visible items are shown.
1541 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1544 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1545 // The creating of widgets is quite expensive. Assure that never more
1546 // than 50 % of the maximum visible items get created for the animations.
1550 setLayouterSize(currentSize
, sizeType
);
1551 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1552 if (!m_visibleItems
.contains(i
)) {
1553 KItemListWidget
* widget
= createWidget(i
);
1554 const QRectF itemRect
= m_layouter
->itemRect(i
);
1555 widget
->setPos(itemRect
.topLeft());
1556 widget
->resize(itemRect
.size());
1559 setLayouterSize(size
, sizeType
);
1563 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1566 case LayouterSize
: m_layouter
->setSize(size
); break;
1567 case ItemSize
: m_layouter
->setItemSize(size
); break;
1572 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1574 widget
->setVisibleRoles(m_visibleRoles
);
1575 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1576 widget
->setStyleOption(m_styleOption
);
1578 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1579 widget
->setCurrent(index
== selectionManager
->currentItem());
1580 widget
->setSelected(selectionManager
->isSelected(index
));
1581 widget
->setHovered(false);
1582 widget
->setAlternatingBackgroundColors(false);
1583 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1584 widget
->setIndex(index
);
1585 widget
->setData(m_model
->data(index
));
1588 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1590 Q_ASSERT(m_grouped
);
1592 const int index
= widget
->index();
1593 if (!m_layouter
->isFirstGroupItem(index
)) {
1594 // The widget does not represent the first item of a group
1595 // and hence requires no header
1596 recycleGroupHeaderForWidget(widget
);
1600 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1601 if (groups
.isEmpty()) {
1605 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1607 header
= m_groupHeaderCreator
->create(this);
1608 header
->setParentItem(widget
);
1609 m_visibleGroups
.insert(widget
, header
);
1611 Q_ASSERT(header
->parentItem() == widget
);
1613 // Determine the shown data for the header by doing a binary
1614 // search in the groups-list
1616 int max
= groups
.count() - 1;
1619 mid
= (min
+ max
) / 2;
1620 if (index
> groups
.at(mid
).first
) {
1625 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1627 header
->setData(groups
.at(mid
).second
);
1628 header
->setRole(model()->sortRole());
1629 header
->setStyleOption(m_styleOption
);
1630 header
->setScrollOrientation(scrollOrientation());
1635 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1637 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1640 const int index
= widget
->index();
1641 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1642 const QRectF itemRect
= m_layouter
->itemRect(index
);
1644 // The group-header is a child of the itemlist widget. Translate the
1645 // group header position to the relative position.
1646 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1647 - groupHeaderRect
.height());
1648 header
->setPos(groupHeaderPos
);
1649 header
->resize(groupHeaderRect
.size());
1652 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1654 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1656 header
->setParentItem(0);
1657 m_groupHeaderCreator
->recycle(header
);
1658 m_visibleGroups
.remove(widget
);
1662 void KItemListView::updateVisibleGroupHeaders()
1664 Q_ASSERT(m_grouped
);
1665 m_layouter
->markAsDirty();
1667 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1668 while (it
.hasNext()) {
1670 updateGroupHeaderForWidget(it
.value());
1674 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1676 QHash
<QByteArray
, qreal
> rolesWidths
;
1678 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1679 while (it
.hasNext()) {
1681 rolesWidths
.insert(it
.key(), it
.value().width());
1687 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1689 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1693 const int itemCount
= m_model
->count();
1694 int rangesItemCount
= 0;
1695 foreach (const KItemRange
& range
, itemRanges
) {
1696 rangesItemCount
+= range
.count
;
1699 if (itemCount
== rangesItemCount
) {
1700 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1702 // Assure the the sizes are not smaller than the minimum defined by the header
1703 // TODO: Currently only implemented for a top-aligned header
1704 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1705 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1706 while (it
.hasNext()) {
1708 const QSizeF
& size
= it
.value();
1709 if (size
.width() < minHeaderRoleWidth
) {
1710 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1711 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1716 // Only a sub range of the roles need to be determined.
1717 // The chances are good that the sizes of the sub ranges
1718 // already fit into the available sizes and hence no
1719 // expensive update might be required.
1720 bool updateRequired
= false;
1722 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1723 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1724 while (it
.hasNext()) {
1726 const QByteArray
& role
= it
.key();
1727 const QSizeF
& updatedSize
= it
.value();
1728 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1729 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1730 m_visibleRolesSizes
.insert(role
, updatedSize
);
1731 updateRequired
= true;
1735 if (!updateRequired
) {
1736 // All the updated sizes are smaller than the current sizes and no change
1737 // of the stretched roles-widths is required
1742 updateStretchedVisibleRolesSizes();
1745 void KItemListView::updateVisibleRolesSizes()
1751 const int itemCount
= m_model
->count();
1752 if (itemCount
> 0) {
1753 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1757 void KItemListView::updateStretchedVisibleRolesSizes()
1759 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1763 // Calculate the maximum size of an item by considering the
1764 // visible role sizes and apply them to the layouter. If the
1765 // size does not use the available view-size it the size of the
1766 // first role will get stretched.
1767 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1768 const QByteArray role
= m_visibleRoles
.first();
1769 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1771 QSizeF dynamicItemSize
= m_itemSize
;
1773 if (dynamicItemSize
.width() <= 0) {
1774 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1775 const qreal availableWidth
= size().width();
1776 if (requiredWidth
< availableWidth
) {
1777 // Stretch the first role to use the whole width for the item
1778 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1779 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1781 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1784 if (dynamicItemSize
.height() <= 0) {
1785 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1786 const qreal availableHeight
= size().height();
1787 if (requiredHeight
< availableHeight
) {
1788 // Stretch the first role to use the whole height for the item
1789 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1790 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1792 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1795 m_layouter
->setItemSize(dynamicItemSize
);
1798 m_header
->setVisibleRolesWidths(headerRolesWidths());
1799 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1802 // Update the role sizes for all visible widgets
1803 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1804 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1808 qreal
KItemListView::visibleRolesSizesWidthSum() const
1811 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1812 while (it
.hasNext()) {
1814 widthSum
+= it
.value().width();
1819 qreal
KItemListView::visibleRolesSizesHeightSum() const
1821 qreal heightSum
= 0;
1822 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1823 while (it
.hasNext()) {
1825 heightSum
+= it
.value().height();
1830 QRectF
KItemListView::headerBoundaries() const
1832 return m_header
? m_header
->geometry() : QRectF();
1835 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1839 const int minSpeed
= 4;
1840 const int maxSpeed
= 128;
1841 const int speedLimiter
= 96;
1842 const int autoScrollBorder
= 64;
1844 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1845 // This assures that the autoscrolling speed grows gradually.
1846 const int incLimiter
= 1;
1848 if (pos
< autoScrollBorder
) {
1849 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1850 inc
= qMax(inc
, -maxSpeed
);
1851 inc
= qMax(inc
, oldInc
- incLimiter
);
1852 } else if (pos
> range
- autoScrollBorder
) {
1853 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1854 inc
= qMin(inc
, maxSpeed
);
1855 inc
= qMin(inc
, oldInc
+ incLimiter
);
1863 KItemListCreatorBase::~KItemListCreatorBase()
1865 qDeleteAll(m_recycleableWidgets
);
1866 qDeleteAll(m_createdWidgets
);
1869 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1871 m_createdWidgets
.insert(widget
);
1874 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1876 Q_ASSERT(m_createdWidgets
.contains(widget
));
1877 m_createdWidgets
.remove(widget
);
1879 if (m_recycleableWidgets
.count() < 100) {
1880 m_recycleableWidgets
.append(widget
);
1881 widget
->setVisible(false);
1887 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1889 if (m_recycleableWidgets
.isEmpty()) {
1893 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1894 m_createdWidgets
.insert(widget
);
1898 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1902 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1904 widget
->setParentItem(0);
1905 widget
->setOpacity(1.0);
1906 pushRecycleableWidget(widget
);
1909 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1913 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1915 header
->setOpacity(1.0);
1916 pushRecycleableWidget(header
);
1919 #include "kitemlistview.moc"