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_supportsItemExpanding(false),
58 m_activeTransactions(0),
59 m_endTransactionAnimationHint(Animation
),
64 m_visibleRolesSizes(),
65 m_stretchedVisibleRolesSizes(),
67 m_groupHeaderCreator(0),
72 m_sizeHintResolver(0),
77 m_oldMaximumScrollOffset(0),
79 m_oldMaximumItemOffset(0),
80 m_skipAutoScrollForRubberBand(false),
83 m_autoScrollIncrement(0),
86 m_useHeaderWidths(false)
88 setAcceptHoverEvents(true);
90 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
92 m_layouter
= new KItemListViewLayouter(this);
93 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
95 m_animation
= new KItemListViewAnimation(this);
96 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
97 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
99 m_layoutTimer
= new QTimer(this);
100 m_layoutTimer
->setInterval(300);
101 m_layoutTimer
->setSingleShot(true);
102 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
104 m_rubberBand
= new KItemListRubberBand(this);
105 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
108 KItemListView::~KItemListView()
110 delete m_sizeHintResolver
;
111 m_sizeHintResolver
= 0;
114 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
116 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
117 if (orientation
== previousOrientation
) {
121 m_layouter
->setScrollOrientation(orientation
);
122 m_animation
->setScrollOrientation(orientation
);
123 m_sizeHintResolver
->clearCache();
126 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
127 while (it
.hasNext()) {
129 it
.value()->setScrollOrientation(orientation
);
131 updateGroupHeaderHeight();
135 doLayout(NoAnimation
);
137 onScrollOrientationChanged(orientation
, previousOrientation
);
138 emit
scrollOrientationChanged(orientation
, previousOrientation
);
141 Qt::Orientation
KItemListView::scrollOrientation() const
143 return m_layouter
->scrollOrientation();
146 void KItemListView::setItemSize(const QSizeF
& itemSize
)
148 const QSizeF previousSize
= m_itemSize
;
149 if (itemSize
== previousSize
) {
153 // Skip animations when the number of rows or columns
154 // are changed in the grid layout. Although the animation
155 // engine can handle this usecase, it looks obtrusive.
156 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
158 m_layouter
->itemMargin());
160 const bool updateAlternateBackgrounds
= (m_visibleRoles
.count() > 1) &&
161 (( m_itemSize
.isEmpty() && !itemSize
.isEmpty()) ||
162 (!m_itemSize
.isEmpty() && itemSize
.isEmpty()));
164 m_itemSize
= itemSize
;
166 if (updateAlternateBackgrounds
) {
167 // For an empty item size alternate backgrounds are drawn if more than
168 // one role is shown. Assure that the backgrounds for visible items are
169 // updated when changing the size in this context.
170 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
171 while (it
.hasNext()) {
173 updateAlternateBackgroundForWidget(it
.value());
177 if (itemSize
.isEmpty()) {
178 updateVisibleRolesSizes();
180 m_layouter
->setItemSize(itemSize
);
183 m_sizeHintResolver
->clearCache();
184 doLayout(animate
? Animation
: NoAnimation
);
185 onItemSizeChanged(itemSize
, previousSize
);
188 QSizeF
KItemListView::itemSize() const
193 void KItemListView::setScrollOffset(qreal offset
)
199 const qreal previousOffset
= m_layouter
->scrollOffset();
200 if (offset
== previousOffset
) {
204 m_layouter
->setScrollOffset(offset
);
205 m_animation
->setScrollOffset(offset
);
207 // Don't check whether the m_layoutTimer is active: Changing the
208 // scroll offset must always trigger a synchronous layout, otherwise
209 // the smooth-scrolling might get jerky.
210 doLayout(NoAnimation
);
211 onScrollOffsetChanged(offset
, previousOffset
);
214 qreal
KItemListView::scrollOffset() const
216 return m_layouter
->scrollOffset();
219 qreal
KItemListView::maximumScrollOffset() const
221 return m_layouter
->maximumScrollOffset();
224 void KItemListView::setItemOffset(qreal offset
)
226 if (m_layouter
->itemOffset() == offset
) {
230 m_layouter
->setItemOffset(offset
);
232 m_header
->setPos(-offset
, 0);
235 // Don't check whether the m_layoutTimer is active: Changing the
236 // item offset must always trigger a synchronous layout, otherwise
237 // the smooth-scrolling might get jerky.
238 doLayout(NoAnimation
);
241 qreal
KItemListView::itemOffset() const
243 return m_layouter
->itemOffset();
246 qreal
KItemListView::maximumItemOffset() const
248 return m_layouter
->maximumItemOffset();
251 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
253 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
254 m_visibleRoles
= roles
;
256 const bool updateAlternateBackgrounds
= m_itemSize
.isEmpty() &&
257 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
258 (roles
.count() <= 1 && previousRoles
.count() > 1));
260 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
261 while (it
.hasNext()) {
263 KItemListWidget
* widget
= it
.value();
264 widget
->setVisibleRoles(roles
);
265 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
266 if (updateAlternateBackgrounds
) {
267 updateAlternateBackgroundForWidget(widget
);
271 m_sizeHintResolver
->clearCache();
272 m_layouter
->markAsDirty();
275 m_header
->setVisibleRoles(roles
);
276 m_header
->setVisibleRolesWidths(headerRolesWidths());
277 m_useHeaderWidths
= false;
280 updateVisibleRolesSizes();
281 doLayout(NoAnimation
);
283 onVisibleRolesChanged(roles
, previousRoles
);
286 QList
<QByteArray
> KItemListView::visibleRoles() const
288 return m_visibleRoles
;
291 void KItemListView::setAutoScroll(bool enabled
)
293 if (enabled
&& !m_autoScrollTimer
) {
294 m_autoScrollTimer
= new QTimer(this);
295 m_autoScrollTimer
->setSingleShot(true);
296 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
297 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
298 } else if (!enabled
&& m_autoScrollTimer
) {
299 delete m_autoScrollTimer
;
300 m_autoScrollTimer
= 0;
305 bool KItemListView::autoScroll() const
307 return m_autoScrollTimer
!= 0;
310 void KItemListView::setEnabledSelectionToggles(bool enabled
)
312 if (m_enabledSelectionToggles
!= enabled
) {
313 m_enabledSelectionToggles
= enabled
;
315 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
316 while (it
.hasNext()) {
318 it
.value()->setEnabledSelectionToggle(enabled
);
323 bool KItemListView::enabledSelectionToggles() const
325 return m_enabledSelectionToggles
;
328 KItemListController
* KItemListView::controller() const
333 KItemModelBase
* KItemListView::model() const
338 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
340 m_widgetCreator
= widgetCreator
;
343 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
345 return m_widgetCreator
;
348 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
350 m_groupHeaderCreator
= groupHeaderCreator
;
353 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
355 return m_groupHeaderCreator
;
358 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
360 const KItemListStyleOption previousOption
= m_styleOption
;
361 m_styleOption
= option
;
364 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
365 if (margin
!= m_layouter
->itemMargin()) {
366 // Skip animations when the number of rows or columns
367 // are changed in the grid layout. Although the animation
368 // engine can handle this usecase, it looks obtrusive.
369 animate
= !changesItemGridLayout(m_layouter
->size(),
370 m_layouter
->itemSize(),
372 m_layouter
->setItemMargin(margin
);
376 updateGroupHeaderHeight();
379 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
380 while (it
.hasNext()) {
382 it
.value()->setStyleOption(option
);
385 m_sizeHintResolver
->clearCache();
386 doLayout(animate
? Animation
: NoAnimation
);
388 onStyleOptionChanged(option
, previousOption
);
391 const KItemListStyleOption
& KItemListView::styleOption() const
393 return m_styleOption
;
396 void KItemListView::setGeometry(const QRectF
& rect
)
398 QGraphicsWidget::setGeometry(rect
);
404 const QSizeF newSize
= rect
.size();
405 if (m_itemSize
.isEmpty()) {
406 // The item size is dynamic:
407 // Changing the geometry does not require to do an expensive
408 // update of the visible-roles sizes, only the stretched sizes
409 // need to be adjusted to the new size.
410 updateStretchedVisibleRolesSizes();
412 if (m_useHeaderWidths
) {
413 QSizeF dynamicItemSize
= m_layouter
->itemSize();
415 if (m_itemSize
.width() < 0) {
416 const qreal requiredWidth
= visibleRolesSizesWidthSum();
417 if (newSize
.width() > requiredWidth
) {
418 dynamicItemSize
.setWidth(newSize
.width());
420 const qreal headerWidth
= qMax(newSize
.width(), requiredWidth
);
421 m_header
->resize(headerWidth
, m_header
->size().height());
424 if (m_itemSize
.height() < 0) {
425 const qreal requiredHeight
= visibleRolesSizesHeightSum();
426 if (newSize
.height() > requiredHeight
) {
427 dynamicItemSize
.setHeight(newSize
.height());
429 // TODO: KItemListHeader is not prepared for vertical alignment
432 m_layouter
->setItemSize(dynamicItemSize
);
435 // Triggering a synchronous layout is fine from a performance point of view,
436 // as with dynamic item sizes no moving animation must be done.
437 m_layouter
->setSize(newSize
);
440 const bool animate
= !changesItemGridLayout(newSize
,
441 m_layouter
->itemSize(),
442 m_layouter
->itemMargin());
443 m_layouter
->setSize(newSize
);
446 // Trigger an asynchronous relayout with m_layoutTimer to prevent
447 // performance bottlenecks. If the timer is exceeded, an animated layout
448 // will be triggered.
449 if (!m_layoutTimer
->isActive()) {
450 m_layoutTimer
->start();
453 m_layoutTimer
->stop();
454 doLayout(NoAnimation
);
459 int KItemListView::itemAt(const QPointF
& pos
) const
461 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
462 while (it
.hasNext()) {
465 const KItemListWidget
* widget
= it
.value();
466 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
467 if (widget
->contains(mappedPos
)) {
475 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
477 if (!m_enabledSelectionToggles
) {
481 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
483 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
484 if (!selectionToggleRect
.isEmpty()) {
485 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
486 return selectionToggleRect
.contains(mappedPos
);
492 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
494 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
496 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
497 if (!expansionToggleRect
.isEmpty()) {
498 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
499 return expansionToggleRect
.contains(mappedPos
);
505 int KItemListView::firstVisibleIndex() const
507 return m_layouter
->firstVisibleIndex();
510 int KItemListView::lastVisibleIndex() const
512 return m_layouter
->lastVisibleIndex();
515 QSizeF
KItemListView::itemSizeHint(int index
) const
521 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRolesSizes(const KItemRangeList
& itemRanges
) const
523 Q_UNUSED(itemRanges
);
524 return QHash
<QByteArray
, QSizeF
>();
527 bool KItemListView::supportsItemExpanding() const
529 return m_supportsItemExpanding
;
532 QRectF
KItemListView::itemRect(int index
) const
534 return m_layouter
->itemRect(index
);
537 QRectF
KItemListView::itemContextRect(int index
) const
541 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
543 contextRect
= widget
->iconRect() | widget
->textRect();
544 contextRect
.translate(itemRect(index
).topLeft());
550 void KItemListView::scrollToItem(int index
)
552 QRectF viewGeometry
= geometry();
554 const qreal headerHeight
= m_header
->size().height();
555 viewGeometry
.adjust(0, headerHeight
, 0, 0);
557 const QRectF currentRect
= itemRect(index
);
559 if (!viewGeometry
.contains(currentRect
)) {
560 qreal newOffset
= scrollOffset();
561 if (scrollOrientation() == Qt::Vertical
) {
562 if (currentRect
.top() < viewGeometry
.top()) {
563 newOffset
+= currentRect
.top() - viewGeometry
.top();
564 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
565 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
568 if (currentRect
.left() < viewGeometry
.left()) {
569 newOffset
+= currentRect
.left() - viewGeometry
.left();
570 } else if (currentRect
.right() > viewGeometry
.right()) {
571 newOffset
+= currentRect
.right() - viewGeometry
.right();
575 if (newOffset
!= scrollOffset()) {
576 emit
scrollTo(newOffset
);
581 void KItemListView::beginTransaction()
583 ++m_activeTransactions
;
584 if (m_activeTransactions
== 1) {
585 onTransactionBegin();
589 void KItemListView::endTransaction()
591 --m_activeTransactions
;
592 if (m_activeTransactions
< 0) {
593 m_activeTransactions
= 0;
594 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
597 if (m_activeTransactions
== 0) {
599 doLayout(m_endTransactionAnimationHint
);
600 m_endTransactionAnimationHint
= Animation
;
604 bool KItemListView::isTransactionActive() const
606 return m_activeTransactions
> 0;
609 void KItemListView::setHeaderShown(bool show
)
612 if (show
&& !m_header
) {
613 m_header
= new KItemListHeader(this);
614 m_header
->setPos(0, 0);
615 m_header
->setModel(m_model
);
616 m_header
->setVisibleRoles(m_visibleRoles
);
617 m_header
->setVisibleRolesWidths(headerRolesWidths());
618 m_header
->setZValue(1);
620 connect(m_header
, SIGNAL(visibleRoleWidthChanged(QByteArray
,qreal
,qreal
)),
621 this, SLOT(slotVisibleRoleWidthChanged(QByteArray
,qreal
,qreal
)));
622 connect(m_header
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
623 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
624 connect(m_header
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
625 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
627 m_useHeaderWidths
= false;
629 m_layouter
->setHeaderHeight(m_header
->size().height());
630 } else if (!show
&& m_header
) {
633 m_useHeaderWidths
= false;
634 m_layouter
->setHeaderHeight(0);
638 bool KItemListView::isHeaderShown() const
640 return m_header
!= 0;
643 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
649 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
651 QGraphicsWidget::paint(painter
, option
, widget
);
653 if (m_rubberBand
->isActive()) {
654 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
655 m_rubberBand
->endPosition()).normalized();
657 const QPointF topLeft
= rubberBandRect
.topLeft();
658 if (scrollOrientation() == Qt::Vertical
) {
659 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
661 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
664 QStyleOptionRubberBand opt
;
665 opt
.initFrom(widget
);
666 opt
.shape
= QRubberBand::Rectangle
;
668 opt
.rect
= rubberBandRect
.toRect();
669 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
673 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
678 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
680 Q_UNUSED(changedRoles
);
684 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
690 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
696 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
702 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
708 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
714 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
720 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
726 void KItemListView::onTransactionBegin()
730 void KItemListView::onTransactionEnd()
734 bool KItemListView::event(QEvent
* event
)
736 // Forward all events to the controller and handle them there
737 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
741 return QGraphicsWidget::event(event
);
744 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
746 m_mousePos
= transform().map(event
->pos());
750 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
752 QGraphicsWidget::mouseMoveEvent(event
);
754 m_mousePos
= transform().map(event
->pos());
755 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
756 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
760 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
762 event
->setAccepted(true);
766 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
768 QGraphicsWidget::dragMoveEvent(event
);
770 m_mousePos
= transform().map(event
->pos());
771 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
772 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
776 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
778 QGraphicsWidget::dragLeaveEvent(event
);
779 setAutoScroll(false);
782 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
784 QGraphicsWidget::dropEvent(event
);
785 setAutoScroll(false);
788 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
790 return m_visibleItems
.values();
793 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
795 if (m_supportsItemExpanding
!= supportsExpanding
) {
796 m_supportsItemExpanding
= supportsExpanding
;
797 updateSiblingsInformation();
801 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
803 updateVisibleRolesSizes(itemRanges
);
805 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
806 if (hasMultipleRanges
) {
810 m_layouter
->markAsDirty();
812 int previouslyInsertedCount
= 0;
813 foreach (const KItemRange
& range
, itemRanges
) {
814 // range.index is related to the model before anything has been inserted.
815 // As in each loop the current item-range gets inserted the index must
816 // be increased by the already previously inserted items.
817 const int index
= range
.index
+ previouslyInsertedCount
;
818 const int count
= range
.count
;
819 if (index
< 0 || count
<= 0) {
820 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
823 previouslyInsertedCount
+= count
;
825 m_sizeHintResolver
->itemsInserted(index
, count
);
827 // Determine which visible items must be moved
828 QList
<int> itemsToMove
;
829 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
830 while (it
.hasNext()) {
832 const int visibleItemIndex
= it
.key();
833 if (visibleItemIndex
>= index
) {
834 itemsToMove
.append(visibleItemIndex
);
838 // Update the indexes of all KItemListWidget instances that are located
839 // after the inserted items. It is important to adjust the indexes in the order
840 // from the highest index to the lowest index to prevent overlaps when setting the new index.
842 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
843 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
845 const int newIndex
= widget
->index() + count
;
846 if (hasMultipleRanges
) {
847 setWidgetIndex(widget
, newIndex
);
849 // Try to animate the moving of the item
850 moveWidgetToIndex(widget
, newIndex
);
854 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
855 // Check whether a scrollbar is required to show the inserted items. In this case
856 // the size of the layouter will be decreased before calling doLayout(): This prevents
857 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
858 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
859 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
860 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
861 if (decreaseLayouterSize
) {
862 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
863 QSizeF layouterSize
= m_layouter
->size();
864 if (verticalScrollOrientation
) {
865 layouterSize
.rwidth() -= scrollBarExtent
;
867 layouterSize
.rheight() -= scrollBarExtent
;
869 m_layouter
->setSize(layouterSize
);
873 if (!hasMultipleRanges
) {
874 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
875 updateSiblingsInformation();
880 m_controller
->selectionManager()->itemsInserted(itemRanges
);
883 if (hasMultipleRanges
) {
885 // Important: Don't read any m_layouter-property inside the for-loop in case if
886 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
887 // updated in each loop-cycle and has only a consistent state after the loop.
888 Q_ASSERT(m_layouter
->isDirty());
890 m_endTransactionAnimationHint
= NoAnimation
;
892 updateSiblingsInformation();
896 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
898 updateVisibleRolesSizes();
900 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
901 if (hasMultipleRanges
) {
905 m_layouter
->markAsDirty();
907 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
908 const KItemRange
& range
= itemRanges
.at(i
);
909 const int index
= range
.index
;
910 const int count
= range
.count
;
911 if (index
< 0 || count
<= 0) {
912 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
916 m_sizeHintResolver
->itemsRemoved(index
, count
);
918 const int firstRemovedIndex
= index
;
919 const int lastRemovedIndex
= index
+ count
- 1;
920 const int lastIndex
= m_model
->count() + count
- 1;
922 // Remove all KItemListWidget instances that got deleted
923 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
924 KItemListWidget
* widget
= m_visibleItems
.value(i
);
929 m_animation
->stop(widget
);
930 // Stopping the animation might lead to recycling the widget if
931 // it is invisible (see slotAnimationFinished()).
932 // Check again whether it is still visible:
933 if (!m_visibleItems
.contains(i
)) {
937 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
938 // Remove the widget without animation
939 recycleWidget(widget
);
941 // Animate the removing of the items. Special case: When removing an item there
942 // is no valid model index available anymore. For the
943 // remove-animation the item gets removed from m_visibleItems but the widget
944 // will stay alive until the animation has been finished and will
945 // be recycled (deleted) in KItemListView::slotAnimationFinished().
946 m_visibleItems
.remove(i
);
947 widget
->setIndex(-1);
948 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
952 // Update the indexes of all KItemListWidget instances that are located
953 // after the deleted items
954 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
955 KItemListWidget
* widget
= m_visibleItems
.value(i
);
957 const int newIndex
= i
- count
;
958 if (hasMultipleRanges
) {
959 setWidgetIndex(widget
, newIndex
);
961 // Try to animate the moving of the item
962 moveWidgetToIndex(widget
, newIndex
);
967 if (!hasMultipleRanges
) {
968 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
969 // assumes an updated geometry. If items are removed during an active transaction,
970 // the transaction will be temporary deactivated so that doLayout() triggers a
971 // geometry update if necessary.
972 const int activeTransactions
= m_activeTransactions
;
973 m_activeTransactions
= 0;
974 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
975 m_activeTransactions
= activeTransactions
;
976 updateSiblingsInformation();
981 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
984 if (hasMultipleRanges
) {
986 // Important: Don't read any m_layouter-property inside the for-loop in case if
987 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
988 // updated in each loop-cycle and has only a consistent state after the loop.
989 Q_ASSERT(m_layouter
->isDirty());
991 m_endTransactionAnimationHint
= NoAnimation
;
993 updateSiblingsInformation();
997 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
999 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1000 m_layouter
->markAsDirty();
1003 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1006 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1007 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1009 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1010 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1012 updateWidgetProperties(widget
, index
);
1013 initializeItemListWidget(widget
);
1017 doLayout(NoAnimation
);
1018 updateSiblingsInformation();
1021 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1022 const QSet
<QByteArray
>& roles
)
1024 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1025 if (updateSizeHints
) {
1026 updateVisibleRolesSizes(itemRanges
);
1029 foreach (const KItemRange
& itemRange
, itemRanges
) {
1030 const int index
= itemRange
.index
;
1031 const int count
= itemRange
.count
;
1033 if (updateSizeHints
) {
1034 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1035 m_layouter
->markAsDirty();
1037 if (!m_layoutTimer
->isActive()) {
1038 m_layoutTimer
->start();
1042 // Apply the changed roles to the visible item-widgets
1043 const int lastIndex
= index
+ count
- 1;
1044 for (int i
= index
; i
<= lastIndex
; ++i
) {
1045 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1047 widget
->setData(m_model
->data(i
), roles
);
1051 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1052 // The sort-role has been changed which might result
1053 // in modified group headers
1054 updateVisibleGroupHeaders();
1055 doLayout(NoAnimation
);
1060 void KItemListView::slotGroupedSortingChanged(bool current
)
1062 m_grouped
= current
;
1063 m_layouter
->markAsDirty();
1066 updateGroupHeaderHeight();
1068 // Clear all visible headers
1069 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1070 while (it
.hasNext()) {
1072 recycleGroupHeaderForWidget(it
.key());
1074 Q_ASSERT(m_visibleGroups
.isEmpty());
1077 if (useAlternateBackgrounds()) {
1078 // Changing the group mode requires to update the alternate backgrounds
1079 // as with the enabled group mode the altering is done on base of the first
1081 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1082 while (it
.hasNext()) {
1084 updateAlternateBackgroundForWidget(it
.value());
1088 updateSiblingsInformation();
1089 doLayout(NoAnimation
);
1092 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1097 updateVisibleGroupHeaders();
1098 doLayout(NoAnimation
);
1102 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1107 updateVisibleGroupHeaders();
1108 doLayout(NoAnimation
);
1112 void KItemListView::slotCurrentChanged(int current
, int previous
)
1116 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1117 if (previousWidget
) {
1118 previousWidget
->setCurrent(false);
1121 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1122 if (currentWidget
) {
1123 currentWidget
->setCurrent(true);
1127 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1131 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1132 while (it
.hasNext()) {
1134 const int index
= it
.key();
1135 KItemListWidget
* widget
= it
.value();
1136 widget
->setSelected(current
.contains(index
));
1140 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1141 KItemListViewAnimation::AnimationType type
)
1143 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1144 Q_ASSERT(itemListWidget
);
1147 case KItemListViewAnimation::DeleteAnimation
: {
1148 // As we recycle the widget in this case it is important to assure that no
1149 // other animation has been started. This is a convention in KItemListView and
1150 // not a requirement defined by KItemListViewAnimation.
1151 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1153 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1154 // by m_visibleWidgets and must be deleted manually after the animation has
1156 recycleGroupHeaderForWidget(itemListWidget
);
1157 m_widgetCreator
->recycle(itemListWidget
);
1161 case KItemListViewAnimation::CreateAnimation
:
1162 case KItemListViewAnimation::MovingAnimation
:
1163 case KItemListViewAnimation::ResizeAnimation
: {
1164 const int index
= itemListWidget
->index();
1165 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1166 (index
> m_layouter
->lastVisibleIndex());
1167 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1168 recycleWidget(itemListWidget
);
1177 void KItemListView::slotLayoutTimerFinished()
1179 m_layouter
->setSize(geometry().size());
1180 doLayout(Animation
);
1183 void KItemListView::slotRubberBandPosChanged()
1188 void KItemListView::slotRubberBandActivationChanged(bool active
)
1191 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1192 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1193 m_skipAutoScrollForRubberBand
= true;
1195 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1196 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1197 m_skipAutoScrollForRubberBand
= false;
1203 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray
& role
,
1205 qreal previousWidth
)
1207 Q_UNUSED(previousWidth
);
1209 m_useHeaderWidths
= true;
1211 if (m_visibleRolesSizes
.contains(role
)) {
1212 QSizeF roleSize
= m_visibleRolesSizes
.value(role
);
1213 roleSize
.setWidth(currentWidth
);
1214 m_visibleRolesSizes
.insert(role
, roleSize
);
1215 m_stretchedVisibleRolesSizes
.insert(role
, roleSize
);
1217 // Apply the new size to the layouter
1218 QSizeF dynamicItemSize
= m_itemSize
;
1219 if (dynamicItemSize
.width() < 0) {
1220 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1221 dynamicItemSize
.setWidth(qMax(size().width(), requiredWidth
));
1223 if (dynamicItemSize
.height() < 0) {
1224 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1225 dynamicItemSize
.setHeight(qMax(size().height(), requiredHeight
));
1228 m_layouter
->setItemSize(dynamicItemSize
);
1230 // Update the role sizes for all visible widgets
1231 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1232 while (it
.hasNext()) {
1234 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1236 doLayout(NoAnimation
);
1240 void KItemListView::triggerAutoScrolling()
1242 if (!m_autoScrollTimer
) {
1247 int visibleSize
= 0;
1248 if (scrollOrientation() == Qt::Vertical
) {
1249 pos
= m_mousePos
.y();
1250 visibleSize
= size().height();
1252 pos
= m_mousePos
.x();
1253 visibleSize
= size().width();
1256 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1257 m_autoScrollIncrement
= 0;
1260 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1261 if (m_autoScrollIncrement
== 0) {
1262 // The mouse position is not above an autoscroll margin (the autoscroll timer
1263 // will be restarted in mouseMoveEvent())
1264 m_autoScrollTimer
->stop();
1268 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1269 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1270 // if the direction of the rubberband is similar to the autoscroll direction. This
1271 // prevents that starting to create a rubberband within the autoscroll margins starts
1272 // an autoscrolling.
1274 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1275 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1276 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1277 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1278 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1279 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1280 // been moved up although the autoscroll direction might be down)
1281 m_autoScrollTimer
->stop();
1286 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1287 // the autoscrolling may not get skipped anymore until a new rubberband is created
1288 m_skipAutoScrollForRubberBand
= false;
1290 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1291 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1292 setScrollOffset(newScrollOffset
);
1294 // Trigger the autoscroll timer which will periodically call
1295 // triggerAutoScrolling()
1296 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1299 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1301 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1303 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1304 Q_ASSERT(groupHeader
);
1305 updateGroupHeaderLayout(widget
);
1308 void KItemListView::setController(KItemListController
* controller
)
1310 if (m_controller
!= controller
) {
1311 KItemListController
* previous
= m_controller
;
1313 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1314 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1315 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1318 m_controller
= controller
;
1321 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1322 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1323 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1326 onControllerChanged(controller
, previous
);
1330 void KItemListView::setModel(KItemModelBase
* model
)
1332 if (m_model
== model
) {
1336 KItemModelBase
* previous
= m_model
;
1339 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1340 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1341 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1342 this, SLOT(slotItemsInserted(KItemRangeList
)));
1343 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1344 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1345 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1346 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1347 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1348 this, SLOT(slotGroupedSortingChanged(bool)));
1349 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1350 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1351 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1352 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1356 m_layouter
->setModel(model
);
1357 m_grouped
= model
->groupedSorting();
1360 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1361 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1362 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1363 this, SLOT(slotItemsInserted(KItemRangeList
)));
1364 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1365 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1366 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1367 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1368 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1369 this, SLOT(slotGroupedSortingChanged(bool)));
1370 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1371 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1372 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1373 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1376 onModelChanged(model
, previous
);
1379 KItemListRubberBand
* KItemListView::rubberBand() const
1381 return m_rubberBand
;
1384 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1386 if (m_layoutTimer
->isActive()) {
1387 m_layoutTimer
->stop();
1390 if (m_activeTransactions
> 0) {
1391 if (hint
== NoAnimation
) {
1392 // As soon as at least one property change should be done without animation,
1393 // the whole transaction will be marked as not animated.
1394 m_endTransactionAnimationHint
= NoAnimation
;
1399 if (!m_model
|| m_model
->count() < 0) {
1403 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1404 if (firstVisibleIndex
< 0) {
1405 emitOffsetChanges();
1409 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1410 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1411 // is still shown if the maximum offset got decreased.
1412 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1413 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1414 if (scrollOffset() > maxOffsetToShowFullRange
) {
1415 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1416 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1419 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1421 int firstSibblingIndex
= -1;
1422 int lastSibblingIndex
= -1;
1423 const bool supportsExpanding
= supportsItemExpanding();
1425 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1427 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1428 // instances from invisible items are reused. If no reusable items are
1429 // found then new KItemListWidget instances get created.
1430 const bool animate
= (hint
== Animation
);
1431 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1432 bool applyNewPos
= true;
1433 bool wasHidden
= false;
1435 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1436 const QPointF newPos
= itemBounds
.topLeft();
1437 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1440 if (!reusableItems
.isEmpty()) {
1441 // Reuse a KItemListWidget instance from an invisible item
1442 const int oldIndex
= reusableItems
.takeLast();
1443 widget
= m_visibleItems
.value(oldIndex
);
1444 setWidgetIndex(widget
, i
);
1445 updateWidgetProperties(widget
, i
);
1446 initializeItemListWidget(widget
);
1448 // No reusable KItemListWidget instance is available, create a new one
1449 widget
= createWidget(i
);
1451 widget
->resize(itemBounds
.size());
1453 if (animate
&& changedCount
< 0) {
1454 // Items have been deleted, move the created item to the
1455 // imaginary old position. They will get animated to the new position
1457 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1458 if (itemRect
.isEmpty()) {
1459 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1460 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1461 widget
->setPos(invisibleOldPos
);
1463 widget
->setPos(itemRect
.topLeft());
1465 applyNewPos
= false;
1468 if (supportsExpanding
&& changedCount
== 0) {
1469 if (firstSibblingIndex
< 0) {
1470 firstSibblingIndex
= i
;
1472 lastSibblingIndex
= i
;
1477 const bool itemsRemoved
= (changedCount
< 0);
1478 const bool itemsInserted
= (changedCount
> 0);
1479 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1480 // The item is located after the removed items. Animate the moving of the position.
1481 applyNewPos
= !moveWidget(widget
, newPos
);
1482 } else if (itemsInserted
&& i
>= changedIndex
) {
1483 // The item is located after the first inserted item
1484 if (i
<= changedIndex
+ changedCount
- 1) {
1485 // The item is an inserted item. Animate the appearing of the item.
1486 // For performance reasons no animation is done when changedCount is equal
1487 // to all available items.
1488 if (changedCount
< m_model
->count()) {
1489 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1491 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1492 // The item was already there before, so animate the moving of the position.
1493 // No moving animation is done if the item is animated by a create animation: This
1494 // prevents a "move animation mess" when inserting several ranges in parallel.
1495 applyNewPos
= !moveWidget(widget
, newPos
);
1497 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1498 // The size of the view might have been changed. Animate the moving of the position.
1499 applyNewPos
= !moveWidget(widget
, newPos
);
1502 m_animation
->stop(widget
);
1506 widget
->setPos(newPos
);
1509 Q_ASSERT(widget
->index() == i
);
1510 widget
->setVisible(true);
1512 if (widget
->size() != itemBounds
.size()) {
1513 // Resize the widget for the item to the changed size.
1515 // If a dynamic item size is used then no animation is done in the direction
1516 // of the dynamic size.
1517 if (m_itemSize
.width() <= 0) {
1518 // The width is dynamic, apply the new width without animation.
1519 widget
->resize(itemBounds
.width(), widget
->size().height());
1520 } else if (m_itemSize
.height() <= 0) {
1521 // The height is dynamic, apply the new height without animation.
1522 widget
->resize(widget
->size().width(), itemBounds
.height());
1524 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1526 widget
->resize(itemBounds
.size());
1530 // Updating the cell-information must be done as last step: The decision whether the
1531 // moving-animation should be started at all is based on the previous cell-information.
1532 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1533 m_visibleCells
.insert(i
, cell
);
1536 // Delete invisible KItemListWidget instances that have not been reused
1537 foreach (int index
, reusableItems
) {
1538 recycleWidget(m_visibleItems
.value(index
));
1541 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1542 Q_ASSERT(lastSibblingIndex
>= 0);
1543 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1547 // Update the layout of all visible group headers
1548 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1549 while (it
.hasNext()) {
1551 updateGroupHeaderLayout(it
.key());
1555 emitOffsetChanges();
1558 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1559 int lastVisibleIndex
,
1560 LayoutAnimationHint hint
)
1562 // Determine all items that are completely invisible and might be
1563 // reused for items that just got (at least partly) visible. If the
1564 // animation hint is set to 'Animation' items that do e.g. an animated
1565 // moving of their position are not marked as invisible: This assures
1566 // that a scrolling inside the view can be done without breaking an animation.
1570 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1571 while (it
.hasNext()) {
1574 KItemListWidget
* widget
= it
.value();
1575 const int index
= widget
->index();
1576 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1579 if (m_animation
->isStarted(widget
)) {
1580 if (hint
== NoAnimation
) {
1581 // Stopping the animation will call KItemListView::slotAnimationFinished()
1582 // and the widget will be recycled if necessary there.
1583 m_animation
->stop(widget
);
1586 widget
->setVisible(false);
1587 items
.append(index
);
1590 recycleGroupHeaderForWidget(widget
);
1599 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1601 if (widget
->pos() == newPos
) {
1605 bool startMovingAnim
= false;
1607 // When having a grid the moving-animation should only be started, if it is done within
1608 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1609 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1610 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1611 const int index
= widget
->index();
1612 const Cell cell
= m_visibleCells
.value(index
);
1613 if (cell
.column
>= 0 && cell
.row
>= 0) {
1614 if (scrollOrientation() == Qt::Vertical
) {
1615 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1617 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1621 if (startMovingAnim
) {
1622 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1626 m_animation
->stop(widget
);
1627 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1631 void KItemListView::emitOffsetChanges()
1633 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1634 if (m_oldScrollOffset
!= newScrollOffset
) {
1635 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1636 m_oldScrollOffset
= newScrollOffset
;
1639 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1640 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1641 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1642 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1645 const qreal newItemOffset
= m_layouter
->itemOffset();
1646 if (m_oldItemOffset
!= newItemOffset
) {
1647 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1648 m_oldItemOffset
= newItemOffset
;
1651 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1652 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1653 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1654 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1658 KItemListWidget
* KItemListView::createWidget(int index
)
1660 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1661 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1663 m_visibleItems
.insert(index
, widget
);
1664 m_visibleCells
.insert(index
, Cell());
1665 updateWidgetProperties(widget
, index
);
1666 initializeItemListWidget(widget
);
1670 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1673 recycleGroupHeaderForWidget(widget
);
1676 const int index
= widget
->index();
1677 m_visibleItems
.remove(index
);
1678 m_visibleCells
.remove(index
);
1680 m_widgetCreator
->recycle(widget
);
1683 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1685 const int oldIndex
= widget
->index();
1686 m_visibleItems
.remove(oldIndex
);
1687 m_visibleCells
.remove(oldIndex
);
1689 m_visibleItems
.insert(index
, widget
);
1690 m_visibleCells
.insert(index
, Cell());
1692 widget
->setIndex(index
);
1695 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1697 const int oldIndex
= widget
->index();
1698 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1700 setWidgetIndex(widget
, index
);
1702 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1703 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1704 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1705 (!vertical
&& oldCell
.column
== newCell
.column
);
1707 m_visibleCells
.insert(index
, newCell
);
1711 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1714 case LayouterSize
: m_layouter
->setSize(size
); break;
1715 case ItemSize
: m_layouter
->setItemSize(size
); break;
1720 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1722 widget
->setVisibleRoles(m_visibleRoles
);
1723 widget
->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
1724 widget
->setStyleOption(m_styleOption
);
1726 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1727 widget
->setCurrent(index
== selectionManager
->currentItem());
1728 widget
->setSelected(selectionManager
->isSelected(index
));
1729 widget
->setHovered(false);
1730 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1731 widget
->setIndex(index
);
1732 widget
->setData(m_model
->data(index
));
1733 widget
->setSiblingsInformation(QBitArray());
1734 updateAlternateBackgroundForWidget(widget
);
1737 updateGroupHeaderForWidget(widget
);
1741 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1743 Q_ASSERT(m_grouped
);
1745 const int index
= widget
->index();
1746 if (!m_layouter
->isFirstGroupItem(index
)) {
1747 // The widget does not represent the first item of a group
1748 // and hence requires no header
1749 recycleGroupHeaderForWidget(widget
);
1753 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1754 if (groups
.isEmpty()) {
1758 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1760 groupHeader
= m_groupHeaderCreator
->create(this);
1761 groupHeader
->setParentItem(widget
);
1762 m_visibleGroups
.insert(widget
, groupHeader
);
1763 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1765 Q_ASSERT(groupHeader
->parentItem() == widget
);
1767 const int groupIndex
= groupIndexForItem(index
);
1768 Q_ASSERT(groupIndex
>= 0);
1769 groupHeader
->setData(groups
.at(groupIndex
).second
);
1770 groupHeader
->setRole(model()->sortRole());
1771 groupHeader
->setStyleOption(m_styleOption
);
1772 groupHeader
->setScrollOrientation(scrollOrientation());
1773 groupHeader
->setItemIndex(index
);
1775 groupHeader
->show();
1778 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1780 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1781 Q_ASSERT(groupHeader
);
1783 const int index
= widget
->index();
1784 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1785 const QRectF itemRect
= m_layouter
->itemRect(index
);
1787 // The group-header is a child of the itemlist widget. Translate the
1788 // group header position to the relative position.
1789 if (scrollOrientation() == Qt::Vertical
) {
1790 // In the vertical scroll orientation the group header should always span
1791 // the whole width no matter which temporary position the parent widget
1792 // has. In this case the x-position and width will be adjusted manually.
1793 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1794 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1796 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1797 groupHeader
->resize(groupHeaderRect
.size());
1801 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1803 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1805 header
->setParentItem(0);
1806 m_groupHeaderCreator
->recycle(header
);
1807 m_visibleGroups
.remove(widget
);
1808 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1812 void KItemListView::updateVisibleGroupHeaders()
1814 Q_ASSERT(m_grouped
);
1815 m_layouter
->markAsDirty();
1817 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1818 while (it
.hasNext()) {
1820 updateGroupHeaderForWidget(it
.value());
1824 int KItemListView::groupIndexForItem(int index
) const
1826 Q_ASSERT(m_grouped
);
1828 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1829 if (groups
.isEmpty()) {
1834 int max
= groups
.count() - 1;
1837 mid
= (min
+ max
) / 2;
1838 if (index
> groups
[mid
].first
) {
1843 } while (groups
[mid
].first
!= index
&& min
<= max
);
1846 while (groups
[mid
].first
> index
&& mid
> 0) {
1854 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1856 bool enabled
= useAlternateBackgrounds();
1858 const int index
= widget
->index();
1859 enabled
= (index
& 0x1) > 0;
1861 const int groupIndex
= groupIndexForItem(index
);
1862 if (groupIndex
>= 0) {
1863 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1864 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1865 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1866 enabled
= (relativeIndex
& 0x1) > 0;
1870 widget
->setAlternateBackground(enabled
);
1873 bool KItemListView::useAlternateBackgrounds() const
1875 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1878 QHash
<QByteArray
, qreal
> KItemListView::headerRolesWidths() const
1880 QHash
<QByteArray
, qreal
> rolesWidths
;
1882 QHashIterator
<QByteArray
, QSizeF
> it(m_stretchedVisibleRolesSizes
);
1883 while (it
.hasNext()) {
1885 rolesWidths
.insert(it
.key(), it
.value().width());
1891 void KItemListView::updateVisibleRolesSizes(const KItemRangeList
& itemRanges
)
1893 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
) {
1897 const int itemCount
= m_model
->count();
1898 int rangesItemCount
= 0;
1899 foreach (const KItemRange
& range
, itemRanges
) {
1900 rangesItemCount
+= range
.count
;
1903 if (itemCount
== rangesItemCount
) {
1904 m_visibleRolesSizes
= visibleRolesSizes(itemRanges
);
1906 // Assure the the sizes are not smaller than the minimum defined by the header
1907 // TODO: Currently only implemented for a top-aligned header
1908 const qreal minHeaderRoleWidth
= m_header
->minimumRoleWidth();
1909 QMutableHashIterator
<QByteArray
, QSizeF
> it (m_visibleRolesSizes
);
1910 while (it
.hasNext()) {
1912 const QSizeF
& size
= it
.value();
1913 if (size
.width() < minHeaderRoleWidth
) {
1914 const QSizeF
newSize(minHeaderRoleWidth
, size
.height());
1915 m_visibleRolesSizes
.insert(it
.key(), newSize
);
1920 // Only a sub range of the roles need to be determined.
1921 // The chances are good that the sizes of the sub ranges
1922 // already fit into the available sizes and hence no
1923 // expensive update might be required.
1924 bool updateRequired
= false;
1926 const QHash
<QByteArray
, QSizeF
> updatedSizes
= visibleRolesSizes(itemRanges
);
1927 QHashIterator
<QByteArray
, QSizeF
> it(updatedSizes
);
1928 while (it
.hasNext()) {
1930 const QByteArray
& role
= it
.key();
1931 const QSizeF
& updatedSize
= it
.value();
1932 const QSizeF currentSize
= m_visibleRolesSizes
.value(role
);
1933 if (updatedSize
.width() > currentSize
.width() || updatedSize
.height() > currentSize
.height()) {
1934 m_visibleRolesSizes
.insert(role
, updatedSize
);
1935 updateRequired
= true;
1939 if (!updateRequired
) {
1940 // All the updated sizes are smaller than the current sizes and no change
1941 // of the stretched roles-widths is required
1946 updateStretchedVisibleRolesSizes();
1949 void KItemListView::updateVisibleRolesSizes()
1955 const int itemCount
= m_model
->count();
1956 if (itemCount
> 0) {
1957 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount
));
1961 void KItemListView::updateStretchedVisibleRolesSizes()
1963 if (!m_itemSize
.isEmpty() || m_useHeaderWidths
|| m_visibleRoles
.isEmpty()) {
1967 // Calculate the maximum size of an item by considering the
1968 // visible role sizes and apply them to the layouter. If the
1969 // size does not use the available view-size it the size of the
1970 // first role will get stretched.
1971 m_stretchedVisibleRolesSizes
= m_visibleRolesSizes
;
1972 const QByteArray role
= m_visibleRoles
.first();
1973 QSizeF firstRoleSize
= m_stretchedVisibleRolesSizes
.value(role
);
1975 QSizeF dynamicItemSize
= m_itemSize
;
1977 if (dynamicItemSize
.width() <= 0) {
1978 const qreal requiredWidth
= visibleRolesSizesWidthSum();
1979 const qreal availableWidth
= size().width();
1980 if (requiredWidth
< availableWidth
) {
1981 // Stretch the first role to use the whole width for the item
1982 firstRoleSize
.rwidth() += availableWidth
- requiredWidth
;
1983 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1985 dynamicItemSize
.setWidth(qMax(requiredWidth
, availableWidth
));
1988 if (dynamicItemSize
.height() <= 0) {
1989 const qreal requiredHeight
= visibleRolesSizesHeightSum();
1990 const qreal availableHeight
= size().height();
1991 if (requiredHeight
< availableHeight
) {
1992 // Stretch the first role to use the whole height for the item
1993 firstRoleSize
.rheight() += availableHeight
- requiredHeight
;
1994 m_stretchedVisibleRolesSizes
.insert(role
, firstRoleSize
);
1996 dynamicItemSize
.setHeight(qMax(requiredHeight
, availableHeight
));
1999 m_layouter
->setItemSize(dynamicItemSize
);
2002 m_header
->setVisibleRolesWidths(headerRolesWidths());
2003 m_header
->resize(dynamicItemSize
.width(), m_header
->size().height());
2006 // Update the role sizes for all visible widgets
2007 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2008 while (it
.hasNext()) {
2010 it
.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes
);
2014 qreal
KItemListView::visibleRolesSizesWidthSum() const
2017 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2018 while (it
.hasNext()) {
2020 widthSum
+= it
.value().width();
2025 qreal
KItemListView::visibleRolesSizesHeightSum() const
2027 qreal heightSum
= 0;
2028 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
2029 while (it
.hasNext()) {
2031 heightSum
+= it
.value().height();
2036 QRectF
KItemListView::headerBoundaries() const
2038 return m_header
? m_header
->geometry() : QRectF();
2041 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2042 const QSizeF
& newItemSize
,
2043 const QSizeF
& newItemMargin
) const
2045 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2049 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2050 const qreal itemWidth
= m_layouter
->itemSize().width();
2051 if (itemWidth
> 0) {
2052 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2053 newItemSize
.width(),
2054 newItemMargin
.width());
2055 if (m_model
->count() > newColumnCount
) {
2056 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2058 m_layouter
->itemMargin().width());
2059 return oldColumnCount
!= newColumnCount
;
2063 const qreal itemHeight
= m_layouter
->itemSize().height();
2064 if (itemHeight
> 0) {
2065 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2066 newItemSize
.height(),
2067 newItemMargin
.height());
2068 if (m_model
->count() > newRowCount
) {
2069 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2071 m_layouter
->itemMargin().height());
2072 return oldRowCount
!= newRowCount
;
2080 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2082 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2086 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2087 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2088 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2089 // Only animate if up to 2/3 of a row or column are inserted or removed
2090 return changedItemCount
<= maximum
* 2 / 3;
2094 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2096 const QSizeF oldSize
= m_layouter
->size();
2098 m_layouter
->setSize(size
);
2099 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2100 m_layouter
->setSize(oldSize
);
2102 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2103 : maxOffset
> size
.width();
2106 void KItemListView::updateGroupHeaderHeight()
2108 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2109 qreal groupHeaderMargin
= 0;
2111 if (scrollOrientation() == Qt::Horizontal
) {
2112 // The vertical margin above and below the header should be
2113 // equal to the horizontal margin, not the vertical margin
2114 // from m_styleOption.
2115 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2116 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2117 } else if (m_itemSize
.isEmpty()){
2118 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2119 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2121 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2122 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2124 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2125 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2127 updateVisibleGroupHeaders();
2130 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2132 if (!supportsItemExpanding() || !m_model
) {
2136 if (firstIndex
< 0 || lastIndex
< 0) {
2137 firstIndex
= m_layouter
->firstVisibleIndex();
2138 lastIndex
= m_layouter
->lastVisibleIndex();
2140 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2141 lastIndex
>= m_layouter
->firstVisibleIndex());
2142 if (!isRangeVisible
) {
2147 int previousParents
= 0;
2148 QBitArray previousSiblings
;
2150 // The rootIndex describes the first index where the siblings get
2151 // calculated from. For the calculation the upper most parent item
2152 // is required. For performance reasons it is checked first whether
2153 // the visible items before or after the current range already
2154 // contain a siblings information which can be used as base.
2155 int rootIndex
= firstIndex
;
2157 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2159 // There is no visible widget before the range, check whether there
2160 // is one after the range:
2161 widget
= m_visibleItems
.value(lastIndex
+ 1);
2163 // The sibling information of the widget may only be used if
2164 // all items of the range have the same number of parents.
2165 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2166 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2167 if (m_model
->expandedParentsCount(i
) != parents
) {
2176 // Performance optimization: Use the sibling information of the visible
2177 // widget beside the given range.
2178 previousSiblings
= widget
->siblingsInformation();
2179 if (previousSiblings
.isEmpty()) {
2182 previousParents
= previousSiblings
.count() - 1;
2183 previousSiblings
.truncate(previousParents
);
2185 // Potentially slow path: Go back to the upper most parent of firstIndex
2186 // to be able to calculate the initial value for the siblings.
2187 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2192 Q_ASSERT(previousParents
>= 0);
2193 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2194 // Update the parent-siblings in case if the current item represents
2195 // a child or an upper parent.
2196 const int currentParents
= m_model
->expandedParentsCount(i
);
2197 Q_ASSERT(currentParents
>= 0);
2198 if (previousParents
< currentParents
) {
2199 previousParents
= currentParents
;
2200 previousSiblings
.resize(currentParents
);
2201 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2202 } else if (previousParents
> currentParents
) {
2203 previousParents
= currentParents
;
2204 previousSiblings
.truncate(currentParents
);
2207 if (i
>= firstIndex
) {
2208 // The index represents a visible item. Apply the parent-siblings
2209 // and update the sibling of the current item.
2210 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2215 QBitArray siblings
= previousSiblings
;
2216 siblings
.resize(siblings
.count() + 1);
2217 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2219 widget
->setSiblingsInformation(siblings
);
2224 bool KItemListView::hasSiblingSuccessor(int index
) const
2226 bool hasSuccessor
= false;
2227 const int parentsCount
= m_model
->expandedParentsCount(index
);
2228 int successorIndex
= index
+ 1;
2230 // Search the next sibling
2231 const int itemCount
= m_model
->count();
2232 while (successorIndex
< itemCount
) {
2233 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2234 if (currentParentsCount
== parentsCount
) {
2235 hasSuccessor
= true;
2237 } else if (currentParentsCount
< parentsCount
) {
2243 if (m_grouped
&& hasSuccessor
) {
2244 // If the sibling is part of another group, don't mark it as
2245 // successor as the group header is between the sibling connections.
2246 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2247 if (m_layouter
->isFirstGroupItem(i
)) {
2248 hasSuccessor
= false;
2254 return hasSuccessor
;
2257 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2261 const int minSpeed
= 4;
2262 const int maxSpeed
= 128;
2263 const int speedLimiter
= 96;
2264 const int autoScrollBorder
= 64;
2266 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2267 // This assures that the autoscrolling speed grows gradually.
2268 const int incLimiter
= 1;
2270 if (pos
< autoScrollBorder
) {
2271 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2272 inc
= qMax(inc
, -maxSpeed
);
2273 inc
= qMax(inc
, oldInc
- incLimiter
);
2274 } else if (pos
> range
- autoScrollBorder
) {
2275 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2276 inc
= qMin(inc
, maxSpeed
);
2277 inc
= qMin(inc
, oldInc
+ incLimiter
);
2283 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2285 const qreal availableSize
= size
- itemMargin
;
2286 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2292 KItemListCreatorBase::~KItemListCreatorBase()
2294 qDeleteAll(m_recycleableWidgets
);
2295 qDeleteAll(m_createdWidgets
);
2298 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2300 m_createdWidgets
.insert(widget
);
2303 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2305 Q_ASSERT(m_createdWidgets
.contains(widget
));
2306 m_createdWidgets
.remove(widget
);
2308 if (m_recycleableWidgets
.count() < 100) {
2309 m_recycleableWidgets
.append(widget
);
2310 widget
->setVisible(false);
2316 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2318 if (m_recycleableWidgets
.isEmpty()) {
2322 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2323 m_createdWidgets
.insert(widget
);
2327 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2331 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2333 widget
->setParentItem(0);
2334 widget
->setOpacity(1.0);
2335 pushRecycleableWidget(widget
);
2338 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2342 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2344 header
->setOpacity(1.0);
2345 pushRecycleableWidget(header
);
2348 #include "kitemlistview.moc"