1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "kitemlistcontroller.h"
26 #include "kitemlistheader_p.h"
27 #include "kitemlistrubberband_p.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistsizehintresolver_p.h"
30 #include "kitemlistviewlayouter_p.h"
31 #include "kitemlistviewanimation_p.h"
32 #include "kitemlistwidget.h"
37 #include <QGraphicsSceneMouseEvent>
39 #include <QPropertyAnimation>
41 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
54 QGraphicsWidget(parent
),
55 m_enabledSelectionToggles(false),
57 m_activeTransactions(0),
62 m_visibleRolesSizes(),
63 m_stretchedVisibleRolesSizes(),
65 m_groupHeaderCreator(0),
69 m_sizeHintResolver(0),
74 m_oldMaximumScrollOffset(0),
76 m_oldMaximumItemOffset(0),
77 m_skipAutoScrollForRubberBand(false),
80 m_autoScrollIncrement(0),
83 m_useHeaderWidths(false)
85 setAcceptHoverEvents(true);
87 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
89 m_layouter
= new KItemListViewLayouter(this);
90 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
92 m_animation
= new KItemListViewAnimation(this);
93 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
94 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
96 m_layoutTimer
= new QTimer(this);
97 m_layoutTimer
->setInterval(300);
98 m_layoutTimer
->setSingleShot(true);
99 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
101 m_rubberBand
= new KItemListRubberBand(this);
102 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
105 KItemListView::~KItemListView()
107 delete m_sizeHintResolver
;
108 m_sizeHintResolver
= 0;
111 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
113 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
114 if (orientation
== previousOrientation
) {
118 m_layouter
->setScrollOrientation(orientation
);
119 m_animation
->setScrollOrientation(orientation
);
120 m_sizeHintResolver
->clearCache();
123 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
124 while (it
.hasNext()) {
126 it
.value()->setScrollOrientation(orientation
);
130 doLayout(NoAnimation
);
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 // Skip animations when the number of rows or columns
149 // are changed in the grid layout. Although the animation
150 // engine can handle this usecase, it looks obtrusive.
151 const bool animate
= !changesItemGridLayout(m_layouter
->size(), itemSize
);
153 m_itemSize
= itemSize
;
155 if (itemSize
.isEmpty()) {
156 updateVisibleRolesSizes();
158 m_layouter
->setItemSize(itemSize
);
161 m_sizeHintResolver
->clearCache();
162 doLayout(animate
? Animation
: NoAnimation
);
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();
252 doLayout(NoAnimation
);
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(true);
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 const bool animate
= !changesItemGridLayout(newSize
, m_layouter
->itemSize());
395 m_layouter
->setSize(newSize
);
398 // Trigger an asynchronous relayout with m_layoutTimer to prevent
399 // performance bottlenecks. If the timer is exceeded, an animated layout
400 // will be triggered.
401 if (!m_layoutTimer
->isActive()) {
402 m_layoutTimer
->start();
405 m_layoutTimer
->stop();
406 doLayout(NoAnimation
);
411 int KItemListView::itemAt(const QPointF
& pos
) const
413 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
414 while (it
.hasNext()) {
417 const KItemListWidget
* widget
= it
.value();
418 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
419 if (widget
->contains(mappedPos
)) {
427 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
429 if (!m_enabledSelectionToggles
) {
433 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
435 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
436 if (!selectionToggleRect
.isEmpty()) {
437 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
438 return selectionToggleRect
.contains(mappedPos
);
444 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
446 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
448 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
449 if (!expansionToggleRect
.isEmpty()) {
450 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
451 return expansionToggleRect
.contains(mappedPos
);
457 int KItemListView::firstVisibleIndex() const
459 return m_layouter
->firstVisibleIndex();
462 int KItemListView::lastVisibleIndex() const
464 return m_layouter
->lastVisibleIndex();
467 QSizeF
KItemListView::itemSizeHint(int index
) const
473 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
475 Q_UNUSED(itemRanges
);
476 return QHash
<QByteArray
, QSizeF
>();
479 bool KItemListView::supportsItemExpanding() const
484 QRectF
KItemListView::itemRect(int index
) const
486 return m_layouter
->itemRect(index
);
489 QRectF
KItemListView::itemContextRect(int index
) const
493 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
495 contextRect
= widget
->iconRect() | widget
->textRect();
496 contextRect
.translate(itemRect(index
).topLeft());
502 void KItemListView::scrollToItem(int index
)
504 QRectF viewGeometry
= geometry();
506 const qreal headerHeight
= m_header
->size().height();
507 viewGeometry
.adjust(0, headerHeight
, 0, 0);
509 const QRectF currentRect
= itemRect(index
);
511 if (!viewGeometry
.contains(currentRect
)) {
512 qreal newOffset
= scrollOffset();
513 if (scrollOrientation() == Qt::Vertical
) {
514 if (currentRect
.top() < viewGeometry
.top()) {
515 newOffset
+= currentRect
.top() - viewGeometry
.top();
516 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
517 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
520 if (currentRect
.left() < viewGeometry
.left()) {
521 newOffset
+= currentRect
.left() - viewGeometry
.left();
522 } else if (currentRect
.right() > viewGeometry
.right()) {
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) {
551 doLayout(NoAnimation
);
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(animateChangedItemCount(count
) ? Animation
: NoAnimation
, 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 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
864 // Remove the widget without animation
865 recycleWidget(widget
);
867 // Animate the removing of the items. Special case: When removing an item there
868 // is no valid model index available anymore. For the
869 // remove-animation the item gets removed from m_visibleItems but the widget
870 // will stay alive until the animation has been finished and will
871 // be recycled (deleted) in KItemListView::slotAnimationFinished().
872 m_visibleItems
.remove(i
);
873 widget
->setIndex(-1);
874 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
878 // Update the indexes of all KItemListWidget instances that are located
879 // after the deleted items
880 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
881 KItemListWidget
* widget
= m_visibleItems
.value(i
);
883 const int newIndex
= i
- count
;
884 setWidgetIndex(widget
, newIndex
);
888 m_layouter
->markAsDirty();
889 if (!hasMultipleRanges
) {
890 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
891 // assumes an updated geometry. If items are removed during an active transaction,
892 // the transaction will be temporary deactivated so that doLayout() triggers a
893 // geometry update if necessary.
894 const int activeTransactions
= m_activeTransactions
;
895 m_activeTransactions
= 0;
896 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
897 m_activeTransactions
= activeTransactions
;
902 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
905 if (hasMultipleRanges
) {
910 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
912 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
913 m_layouter
->markAsDirty();
916 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
919 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
920 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
922 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
923 KItemListWidget
* widget
= m_visibleItems
.value(index
);
925 updateWidgetProperties(widget
, index
);
927 updateGroupHeaderForWidget(widget
);
929 initializeItemListWidget(widget
);
933 doLayout(NoAnimation
);
936 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
937 const QSet
<QByteArray
>& roles
)
939 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
940 if (updateSizeHints
) {
941 updateVisibleRolesSizes(itemRanges
);
944 foreach (const KItemRange
& itemRange
, itemRanges
) {
945 const int index
= itemRange
.index
;
946 const int count
= itemRange
.count
;
948 if (updateSizeHints
) {
949 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
950 m_layouter
->markAsDirty();
952 if (!m_layoutTimer
->isActive()) {
953 m_layoutTimer
->start();
957 // Apply the changed roles to the visible item-widgets
958 const int lastIndex
= index
+ count
- 1;
959 for (int i
= index
; i
<= lastIndex
; ++i
) {
960 KItemListWidget
* widget
= m_visibleItems
.value(i
);
962 widget
->setData(m_model
->data(i
), roles
);
966 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
967 // The sort-role has been changed which might result
968 // in modified group headers
969 updateVisibleGroupHeaders();
970 doLayout(NoAnimation
);
975 void KItemListView::slotGroupedSortingChanged(bool current
)
978 m_layouter
->markAsDirty();
981 // Apply the height of the header to the layouter
982 const qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height() +
983 m_styleOption
.margin
* 2;
984 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
986 updateVisibleGroupHeaders();
988 // Clear all visible headers
989 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
990 while (it
.hasNext()) {
992 recycleGroupHeaderForWidget(it
.key());
994 Q_ASSERT(m_visibleGroups
.isEmpty());
997 doLayout(NoAnimation
);
1000 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1005 updateVisibleGroupHeaders();
1006 doLayout(NoAnimation
);
1010 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1015 updateVisibleGroupHeaders();
1016 doLayout(NoAnimation
);
1020 void KItemListView::slotCurrentChanged(int current
, int previous
)
1024 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1025 if (previousWidget
) {
1026 Q_ASSERT(previousWidget
->isCurrent());
1027 previousWidget
->setCurrent(false);
1030 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1031 if (currentWidget
) {
1032 Q_ASSERT(!currentWidget
->isCurrent());
1033 currentWidget
->setCurrent(true);
1037 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1041 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1042 while (it
.hasNext()) {
1044 const int index
= it
.key();
1045 KItemListWidget
* widget
= it
.value();
1046 widget
->setSelected(current
.contains(index
));
1050 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1051 KItemListViewAnimation::AnimationType type
)
1053 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1054 Q_ASSERT(itemListWidget
);
1057 case KItemListViewAnimation::DeleteAnimation
: {
1058 // As we recycle the widget in this case it is important to assure that no
1059 // other animation has been started. This is a convention in KItemListView and
1060 // not a requirement defined by KItemListViewAnimation.
1061 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1063 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1064 // by m_visibleWidgets and must be deleted manually after the animation has
1066 recycleGroupHeaderForWidget(itemListWidget
);
1067 m_widgetCreator
->recycle(itemListWidget
);
1071 case KItemListViewAnimation::CreateAnimation
:
1072 case KItemListViewAnimation::MovingAnimation
:
1073 case KItemListViewAnimation::ResizeAnimation
: {
1074 const int index
= itemListWidget
->index();
1075 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1076 (index
> m_layouter
->lastVisibleIndex());
1077 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1078 recycleWidget(itemListWidget
);
1087 void KItemListView::slotLayoutTimerFinished()
1089 m_layouter
->setSize(geometry().size());
1090 doLayout(Animation
);
1093 void KItemListView::slotRubberBandPosChanged()
1098 void KItemListView::slotRubberBandActivationChanged(bool active
)
1101 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1102 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1103 m_skipAutoScrollForRubberBand
= true;
1105 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1106 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1107 m_skipAutoScrollForRubberBand
= false;
1113 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1115 qreal previousWidth
)
1117 Q_UNUSED(previousWidth
);
1119 m_useHeaderWidths
= true;
1121 if (m_visibleRolesSizes
.contains(role
)) {
1122 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1123 roleSize
.setWidth(currentWidth
);
1124 m_visibleRolesSizes
.insert(role
, roleSize
);
1125 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1127 // Apply the new size to the layouter
1128 QSizeF dynamicItemSize
= m_itemSize
;
1129 if (dynamicItemSize
.width() < 0) {
1130 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1131 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1133 if (dynamicItemSize
.height() < 0) {
1134 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1135 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1138 m_layouter
->setItemSize(dynamicItemSize
);
1140 // Update the role sizes for all visible widgets
1141 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1142 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1145 doLayout(NoAnimation
);
1149 void KItemListView::triggerAutoScrolling()
1151 if (!m_autoScrollTimer
) {
1156 int visibleSize
= 0;
1157 if (scrollOrientation() == Qt::Vertical
) {
1158 pos
= m_mousePos
.y();
1159 visibleSize
= size().height();
1161 pos
= m_mousePos
.x();
1162 visibleSize
= size().width();
1165 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1166 m_autoScrollIncrement
= 0;
1169 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1170 if (m_autoScrollIncrement
== 0) {
1171 // The mouse position is not above an autoscroll margin (the autoscroll timer
1172 // will be restarted in mouseMoveEvent())
1173 m_autoScrollTimer
->stop();
1177 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1178 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1179 // if the direction of the rubberband is similar to the autoscroll direction. This
1180 // prevents that starting to create a rubberband within the autoscroll margins starts
1181 // an autoscrolling.
1183 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1184 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1185 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1186 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1187 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1188 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1189 // been moved up although the autoscroll direction might be down)
1190 m_autoScrollTimer
->stop();
1195 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1196 // the autoscrolling may not get skipped anymore until a new rubberband is created
1197 m_skipAutoScrollForRubberBand
= false;
1199 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1200 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1201 setScrollOffset(newScrollOffset
);
1203 // Trigger the autoscroll timer which will periodically call
1204 // triggerAutoScrolling()
1205 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1208 void KItemListView::setController(KItemListController
* controller
)
1210 if (m_controller
!= controller
) {
1211 KItemListController
* previous
= m_controller
;
1213 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1214 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1215 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1218 m_controller
= controller
;
1221 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1222 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1223 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1226 onControllerChanged(controller
, previous
);
1230 void KItemListView::setModel(KItemModelBase
* model
)
1232 if (m_model
== model
) {
1236 KItemModelBase
* previous
= m_model
;
1239 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1240 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1241 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1242 this, SLOT(slotItemsInserted(KItemRangeList
)));
1243 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1244 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1245 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1246 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1247 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1248 this, SLOT(slotGroupedSortingChanged(bool)));
1249 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1250 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1251 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1252 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1256 m_layouter
->setModel(model
);
1257 m_grouped
= model
->groupedSorting();
1260 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1261 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1262 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1263 this, SLOT(slotItemsInserted(KItemRangeList
)));
1264 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1265 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1266 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1267 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1268 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1269 this, SLOT(slotGroupedSortingChanged(bool)));
1270 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1271 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1272 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1273 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1276 onModelChanged(model
, previous
);
1279 KItemListRubberBand
* KItemListView::rubberBand() const
1281 return m_rubberBand
;
1284 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1286 if (m_layoutTimer
->isActive()) {
1287 m_layoutTimer
->stop();
1290 if (!m_model
|| m_model
->count() < 0 || m_activeTransactions
> 0) {
1294 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1295 if (firstVisibleIndex
< 0) {
1296 emitOffsetChanges();
1300 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1301 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1302 // is still shown if the maximum offset got decreased.
1303 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1304 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1305 if (scrollOffset() > maxOffsetToShowFullRange
) {
1306 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1307 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1310 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1312 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1314 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1315 // instances from invisible items are reused. If no reusable items are
1316 // found then new KItemListWidget instances get created.
1317 const bool animate
= (hint
== Animation
);
1318 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1319 bool applyNewPos
= true;
1320 bool wasHidden
= false;
1322 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1323 const QPointF newPos
= itemBounds
.topLeft();
1324 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1327 if (!reusableItems
.isEmpty()) {
1328 // Reuse a KItemListWidget instance from an invisible item
1329 const int oldIndex
= reusableItems
.takeLast();
1330 widget
= m_visibleItems
.value(oldIndex
);
1331 setWidgetIndex(widget
, i
);
1334 updateGroupHeaderForWidget(widget
);
1337 // No reusable KItemListWidget instance is available, create a new one
1338 widget
= createWidget(i
);
1340 widget
->resize(itemBounds
.size());
1342 if (animate
&& changedCount
< 0) {
1343 // Items have been deleted, move the created item to the
1344 // imaginary old position. They will get animated to the new position
1346 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1347 if (itemRect
.isEmpty()) {
1348 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1349 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1350 widget
->setPos(invisibleOldPos
);
1352 widget
->setPos(itemRect
.topLeft());
1354 applyNewPos
= false;
1359 const bool itemsRemoved
= (changedCount
< 0);
1360 const bool itemsInserted
= (changedCount
> 0);
1361 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1362 // The item is located after the removed items. Animate the moving of the position.
1363 applyNewPos
= !moveWidget(widget
, itemBounds
);
1364 } else if (itemsInserted
&& i
>= changedIndex
) {
1365 // The item is located after the first inserted item
1366 if (i
<= changedIndex
+ changedCount
- 1) {
1367 // The item is an inserted item. Animate the appearing of the item.
1368 // For performance reasons no animation is done when changedCount is equal
1369 // to all available items.
1370 if (changedCount
< m_model
->count()) {
1371 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1373 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1374 // The item was already there before, so animate the moving of the position.
1375 // No moving animation is done if the item is animated by a create animation: This
1376 // prevents a "move animation mess" when inserting several ranges in parallel.
1377 applyNewPos
= !moveWidget(widget
, itemBounds
);
1379 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1380 // The size of the view might have been changed. Animate the moving of the position.
1381 applyNewPos
= !moveWidget(widget
, itemBounds
);
1384 m_animation
->stop(widget
);
1388 widget
->setPos(newPos
);
1391 Q_ASSERT(widget
->index() == i
);
1392 widget
->setVisible(true);
1394 if (widget
->size() != itemBounds
.size()) {
1395 // Resize the widget for the item to the changed size.
1397 // If a dynamic item size is used then no animation is done in the direction
1398 // of the dynamic size.
1399 if (m_itemSize
.width() <= 0) {
1400 // The width is dynamic, apply the new width without animation.
1401 widget
->resize(itemBounds
.width(), widget
->size().height());
1402 } else if (m_itemSize
.height() <= 0) {
1403 // The height is dynamic, apply the new height without animation.
1404 widget
->resize(widget
->size().width(), itemBounds
.height());
1406 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1408 widget
->resize(itemBounds
.size());
1413 // Delete invisible KItemListWidget instances that have not been reused
1414 foreach (int index
, reusableItems
) {
1415 recycleWidget(m_visibleItems
.value(index
));
1419 // Update the layout of all visible group headers
1420 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1421 while (it
.hasNext()) {
1423 updateGroupHeaderLayout(it
.key());
1427 emitOffsetChanges();
1430 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1431 int lastVisibleIndex
,
1432 LayoutAnimationHint hint
)
1434 // Determine all items that are completely invisible and might be
1435 // reused for items that just got (at least partly) visible. If the
1436 // animation hint is set to 'Animation' items that do e.g. an animated
1437 // moving of their position are not marked as invisible: This assures
1438 // that a scrolling inside the view can be done without breaking an animation.
1442 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1443 while (it
.hasNext()) {
1446 KItemListWidget
* widget
= it
.value();
1447 const int index
= widget
->index();
1448 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1451 if (m_animation
->isStarted(widget
)) {
1452 if (hint
== NoAnimation
) {
1453 // Stopping the animation will call KItemListView::slotAnimationFinished()
1454 // and the widget will be recycled if necessary there.
1455 m_animation
->stop(widget
);
1458 widget
->setVisible(false);
1459 items
.append(index
);
1462 recycleGroupHeaderForWidget(widget
);
1471 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QRectF
& itemBounds
)
1473 const QPointF oldPos
= widget
->pos();
1474 const QPointF newPos
= itemBounds
.topLeft();
1475 if (oldPos
== newPos
) {
1479 bool startMovingAnim
= m_itemSize
.isEmpty() || widget
->size() != itemBounds
.size();
1480 if (!startMovingAnim
) {
1481 // When having a grid the moving-animation should only be started, if it is done within
1482 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1483 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1484 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1485 const qreal xMax
= m_itemSize
.width();
1486 const qreal yMax
= m_itemSize
.height();
1487 qreal xDiff
= qAbs(oldPos
.x() - newPos
.x());
1488 qreal yDiff
= qAbs(oldPos
.y() - newPos
.y());
1489 if (scrollOrientation() == Qt::Vertical
) {
1490 startMovingAnim
= (xDiff
> yDiff
&& yDiff
< yMax
);
1492 startMovingAnim
= (yDiff
> xDiff
&& xDiff
< xMax
);
1496 if (startMovingAnim
) {
1497 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1501 m_animation
->stop(widget
);
1502 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1506 void KItemListView::emitOffsetChanges()
1508 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1509 if (m_oldScrollOffset
!= newScrollOffset
) {
1510 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1511 m_oldScrollOffset
= newScrollOffset
;
1514 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1515 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1516 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1517 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1520 const qreal newItemOffset
= m_layouter
->itemOffset();
1521 if (m_oldItemOffset
!= newItemOffset
) {
1522 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1523 m_oldItemOffset
= newItemOffset
;
1526 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1527 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1528 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1529 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1533 KItemListWidget
* KItemListView::createWidget(int index
)
1535 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1536 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1538 updateWidgetProperties(widget
, index
);
1539 m_visibleItems
.insert(index
, widget
);
1542 updateGroupHeaderForWidget(widget
);
1545 initializeItemListWidget(widget
);
1549 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1552 recycleGroupHeaderForWidget(widget
);
1555 m_visibleItems
.remove(widget
->index());
1556 m_widgetCreator
->recycle(widget
);
1559 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1561 const int oldIndex
= widget
->index();
1562 m_visibleItems
.remove(oldIndex
);
1563 updateWidgetProperties(widget
, index
);
1564 m_visibleItems
.insert(index
, widget
);
1566 initializeItemListWidget(widget
);
1569 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1572 case LayouterSize
: m_layouter
->setSize(size
); break;
1573 case ItemSize
: m_layouter
->setItemSize(size
); break;
1578 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1580 widget
->setVisibleRoles(m_visibleRoles
);
1581 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1582 widget
->setStyleOption(m_styleOption
);
1584 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1585 widget
->setCurrent(index
== selectionManager
->currentItem());
1586 widget
->setSelected(selectionManager
->isSelected(index
));
1587 widget
->setHovered(false);
1588 widget
->setAlternatingBackgroundColors(false);
1589 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1590 widget
->setIndex(index
);
1591 widget
->setData(m_model
->data(index
));
1594 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1596 Q_ASSERT(m_grouped
);
1598 const int index
= widget
->index();
1599 if (!m_layouter
->isFirstGroupItem(index
)) {
1600 // The widget does not represent the first item of a group
1601 // and hence requires no header
1602 recycleGroupHeaderForWidget(widget
);
1606 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1607 if (groups
.isEmpty()) {
1611 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1613 header
= m_groupHeaderCreator
->create(this);
1614 header
->setParentItem(widget
);
1615 m_visibleGroups
.insert(widget
, header
);
1617 Q_ASSERT(header
->parentItem() == widget
);
1619 // Determine the shown data for the header by doing a binary
1620 // search in the groups-list
1622 int max
= groups
.count() - 1;
1625 mid
= (min
+ max
) / 2;
1626 if (index
> groups
.at(mid
).first
) {
1631 } while (groups
.at(mid
).first
!= index
&& min
<= max
);
1633 header
->setData(groups
.at(mid
).second
);
1634 header
->setRole(model()->sortRole());
1635 header
->setStyleOption(m_styleOption
);
1636 header
->setScrollOrientation(scrollOrientation());
1641 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1643 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1646 const int index
= widget
->index();
1647 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1648 const QRectF itemRect
= m_layouter
->itemRect(index
);
1650 // The group-header is a child of the itemlist widget. Translate the
1651 // group header position to the relative position.
1652 const QPointF
groupHeaderPos(groupHeaderRect
.x() - itemRect
.x(),
1653 - groupHeaderRect
.height());
1654 header
->setPos(groupHeaderPos
);
1655 header
->resize(groupHeaderRect
.size());
1658 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1660 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1662 header
->setParentItem(0);
1663 m_groupHeaderCreator
->recycle(header
);
1664 m_visibleGroups
.remove(widget
);
1668 void KItemListView::updateVisibleGroupHeaders()
1670 Q_ASSERT(m_grouped
);
1671 m_layouter
->markAsDirty();
1673 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1674 while (it
.hasNext()) {
1676 updateGroupHeaderForWidget(it
.value());
1680 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1682 QHash
<QByteArray
, qreal
> rolesWidths
;
1684 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1685 while (it
.hasNext()) {
1687 rolesWidths
.insert(it
.key(), it
.value().width());
1693 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1695 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1699 const int itemCount
= m_model
->count();
1700 int rangesItemCount
= 0;
1701 foreach (const KItemRange
& range
, itemRanges
) {
1702 rangesItemCount
+= range
.count
;
1705 if (itemCount
== rangesItemCount
) {
1706 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1708 // Assure the the sizes are not smaller than the minimum defined by the header
1709 // TODO: Currently only implemented for a top-aligned header
1710 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1711 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1712 while (it
.hasNext()) {
1714 const QSizeF
& size
= it
.value();
1715 if (size
.width() < minHeaderRoleWidth
) {
1716 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1717 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1722 // Only a sub range of the roles need to be determined.
1723 // The chances are good that the sizes of the sub ranges
1724 // already fit into the available sizes and hence no
1725 // expensive update might be required.
1726 bool updateRequired
= false;
1728 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1729 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1730 while (it
.hasNext()) {
1732 const QByteArray
& role
= it
.key();
1733 const QSizeF
& updatedSize
= it
.value();
1734 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1735 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1736 m_visibleRolesSizes
.insert(role
, updatedSize
);
1737 updateRequired
= true;
1741 if (!updateRequired
) {
1742 // All the updated sizes are smaller than the current sizes and no change
1743 // of the stretched roles-widths is required
1748 updateStretchedVisibleRolesSizes();
1751 void KItemListView::updateVisibleRolesSizes()
1757 const int itemCount
= m_model
->count();
1758 if (itemCount
> 0) {
1759 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1763 void KItemListView::updateStretchedVisibleRolesSizes()
1765 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1769 // Calculate the maximum size of an item by considering the
1770 // visible role sizes and apply them to the layouter. If the
1771 // size does not use the available view-size it the size of the
1772 // first role will get stretched.
1773 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1774 const QByteArray role
= m_visibleRoles
.first();
1775 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1777 QSizeF dynamicItemSize
= m_itemSize
;
1779 if (dynamicItemSize
.width() <= 0) {
1780 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1781 const qreal availableWidth
= size().width();
1782 if (requiredWidth
< availableWidth
) {
1783 // Stretch the first role to use the whole width for the item
1784 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1785 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1787 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1790 if (dynamicItemSize
.height() <= 0) {
1791 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1792 const qreal availableHeight
= size().height();
1793 if (requiredHeight
< availableHeight
) {
1794 // Stretch the first role to use the whole height for the item
1795 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1796 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1798 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1801 m_layouter
->setItemSize(dynamicItemSize
);
1804 m_header
->setVisibleRolesWidths(headerRolesWidths());
1805 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
1808 // Update the role sizes for all visible widgets
1809 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1810 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1814 qreal
KItemListView::visibleRolesSizesWidthSum() const
1817 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1818 while (it
.hasNext()) {
1820 widthSum
+= it
.value().width();
1825 qreal
KItemListView::visibleRolesSizesHeightSum() const
1827 qreal heightSum
= 0;
1828 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1829 while (it
.hasNext()) {
1831 heightSum
+= it
.value().height();
1836 QRectF
KItemListView::headerBoundaries() const
1838 return m_header
? m_header
->geometry() : QRectF();
1841 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
, const QSizeF
& newItemSize
) const
1843 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
1847 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
1848 const qreal itemWidth
= m_layouter
->itemSize().width();
1849 if (itemWidth
> 0) {
1850 const int newColumnCount
= newGridSize
.width() / newItemSize
.width();
1851 if (m_model
->count() > newColumnCount
) {
1852 const int oldColumnCount
= m_layouter
->size().width() / itemWidth
;
1853 return oldColumnCount
!= newColumnCount
;
1857 const qreal itemHeight
= m_layouter
->itemSize().height();
1858 if (itemHeight
> 0) {
1859 const int newRowCount
= newGridSize
.height() / newItemSize
.height();
1860 if (m_model
->count() > newRowCount
) {
1861 const int oldRowCount
= m_layouter
->size().height() / itemHeight
;
1862 return oldRowCount
!= newRowCount
;
1870 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
1872 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
1876 const int maximum
= (scrollOrientation() == Qt::Vertical
)
1877 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
1878 : m_layouter
->size().height() / m_layouter
->itemSize().height();
1879 // Only animate if up to 2/3 of a row or column are inserted or removed
1880 return changedItemCount
<= maximum
* 2 / 3;
1884 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
1886 const QSizeF oldSize
= m_layouter
->size();
1888 m_layouter
->setSize(size
);
1889 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
1890 m_layouter
->setSize(oldSize
);
1892 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
1893 : maxOffset
> size
.width();
1896 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1900 const int minSpeed
= 4;
1901 const int maxSpeed
= 128;
1902 const int speedLimiter
= 96;
1903 const int autoScrollBorder
= 64;
1905 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1906 // This assures that the autoscrolling speed grows gradually.
1907 const int incLimiter
= 1;
1909 if (pos
< autoScrollBorder
) {
1910 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1911 inc
= qMax(inc
, -maxSpeed
);
1912 inc
= qMax(inc
, oldInc
- incLimiter
);
1913 } else if (pos
> range
- autoScrollBorder
) {
1914 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1915 inc
= qMin(inc
, maxSpeed
);
1916 inc
= qMin(inc
, oldInc
+ incLimiter
);
1924 KItemListCreatorBase::~KItemListCreatorBase()
1926 qDeleteAll(m_recycleableWidgets
);
1927 qDeleteAll(m_createdWidgets
);
1930 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1932 m_createdWidgets
.insert(widget
);
1935 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1937 Q_ASSERT(m_createdWidgets
.contains(widget
));
1938 m_createdWidgets
.remove(widget
);
1940 if (m_recycleableWidgets
.count() < 100) {
1941 m_recycleableWidgets
.append(widget
);
1942 widget
->setVisible(false);
1948 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1950 if (m_recycleableWidgets
.isEmpty()) {
1954 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1955 m_createdWidgets
.insert(widget
);
1959 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1963 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1965 widget
->setParentItem(0);
1966 widget
->setOpacity(1.0);
1967 pushRecycleableWidget(widget
);
1970 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1974 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1976 header
->setOpacity(1.0);
1977 pushRecycleableWidget(header
);
1980 #include "kitemlistview.moc"