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.h"
27 #include "kitemlistselectionmanager.h"
28 #include "kitemlistwidget.h"
30 #include "private/kitemlistheaderwidget.h"
31 #include "private/kitemlistrubberband.h"
32 #include "private/kitemlistsizehintresolver.h"
33 #include "private/kitemlistviewlayouter.h"
34 #include "private/kitemlistviewanimation.h"
39 #include <QGraphicsSceneMouseEvent>
41 #include <QPropertyAnimation>
43 #include <QStyleOptionRubberBand>
47 // Time in ms until reaching the autoscroll margin triggers
48 // an initial autoscrolling
49 const int InitialAutoScrollDelay
= 700;
51 // Delay in ms for triggering the next autoscroll
52 const int RepeatingAutoScrollDelay
= 1000 / 60;
55 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
56 QGraphicsWidget(parent
),
57 m_enabledSelectionToggles(false),
59 m_supportsItemExpanding(false),
60 m_activeTransactions(0),
61 m_endTransactionAnimationHint(Animation
),
67 m_groupHeaderCreator(0),
72 m_sizeHintResolver(0),
77 m_oldMaximumScrollOffset(0),
79 m_oldMaximumItemOffset(0),
80 m_skipAutoScrollForRubberBand(false),
83 m_autoScrollIncrement(0),
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)));
107 m_headerWidget
= new KItemListHeaderWidget(this);
108 m_headerWidget
->setVisible(false);
110 m_header
= new KItemListHeader(this);
113 KItemListView::~KItemListView()
115 delete m_sizeHintResolver
;
116 m_sizeHintResolver
= 0;
119 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
121 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
122 if (orientation
== previousOrientation
) {
126 m_layouter
->setScrollOrientation(orientation
);
127 m_animation
->setScrollOrientation(orientation
);
128 m_sizeHintResolver
->clearCache();
131 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
132 while (it
.hasNext()) {
134 it
.value()->setScrollOrientation(orientation
);
136 updateGroupHeaderHeight();
140 doLayout(NoAnimation
);
142 onScrollOrientationChanged(orientation
, previousOrientation
);
143 emit
scrollOrientationChanged(orientation
, previousOrientation
);
146 Qt::Orientation
KItemListView::scrollOrientation() const
148 return m_layouter
->scrollOrientation();
151 void KItemListView::setItemSize(const QSizeF
& itemSize
)
153 const QSizeF previousSize
= m_itemSize
;
154 if (itemSize
== previousSize
) {
158 // Skip animations when the number of rows or columns
159 // are changed in the grid layout. Although the animation
160 // engine can handle this usecase, it looks obtrusive.
161 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
163 m_layouter
->itemMargin());
165 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
166 (( m_itemSize
.isEmpty() && !itemSize
.isEmpty()) ||
167 (!m_itemSize
.isEmpty() && itemSize
.isEmpty()));
169 m_itemSize
= itemSize
;
171 if (alternateBackgroundsChanged
) {
172 // For an empty item size alternate backgrounds are drawn if more than
173 // one role is shown. Assure that the backgrounds for visible items are
174 // updated when changing the size in this context.
175 updateAlternateBackgrounds();
178 if (itemSize
.isEmpty()) {
179 if (m_headerWidget
->automaticColumnResizing()) {
180 updatePreferredColumnWidths();
182 // Only apply the changed height and respect the header widths
184 const qreal currentWidth
= m_layouter
->itemSize().width();
185 const QSizeF
newSize(currentWidth
, itemSize
.height());
186 m_layouter
->setItemSize(newSize
);
189 m_layouter
->setItemSize(itemSize
);
192 m_sizeHintResolver
->clearCache();
193 doLayout(animate
? Animation
: NoAnimation
);
194 onItemSizeChanged(itemSize
, previousSize
);
197 QSizeF
KItemListView::itemSize() const
202 void KItemListView::setScrollOffset(qreal offset
)
208 const qreal previousOffset
= m_layouter
->scrollOffset();
209 if (offset
== previousOffset
) {
213 m_layouter
->setScrollOffset(offset
);
214 m_animation
->setScrollOffset(offset
);
216 // Don't check whether the m_layoutTimer is active: Changing the
217 // scroll offset must always trigger a synchronous layout, otherwise
218 // the smooth-scrolling might get jerky.
219 doLayout(NoAnimation
);
220 onScrollOffsetChanged(offset
, previousOffset
);
223 qreal
KItemListView::scrollOffset() const
225 return m_layouter
->scrollOffset();
228 qreal
KItemListView::maximumScrollOffset() const
230 return m_layouter
->maximumScrollOffset();
233 void KItemListView::setItemOffset(qreal offset
)
235 if (m_layouter
->itemOffset() == offset
) {
239 m_layouter
->setItemOffset(offset
);
240 if (m_headerWidget
->isVisible()) {
241 m_headerWidget
->setOffset(offset
);
244 // Don't check whether the m_layoutTimer is active: Changing the
245 // item offset must always trigger a synchronous layout, otherwise
246 // the smooth-scrolling might get jerky.
247 doLayout(NoAnimation
);
250 qreal
KItemListView::itemOffset() const
252 return m_layouter
->itemOffset();
255 qreal
KItemListView::maximumItemOffset() const
257 return m_layouter
->maximumItemOffset();
260 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
262 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
263 m_visibleRoles
= roles
;
264 onVisibleRolesChanged(roles
, previousRoles
);
266 m_sizeHintResolver
->clearCache();
267 m_layouter
->markAsDirty();
269 if (m_itemSize
.isEmpty()) {
270 m_headerWidget
->setColumns(roles
);
271 updatePreferredColumnWidths();
272 if (!m_headerWidget
->automaticColumnResizing()) {
273 // The column-width of new roles are still 0. Apply the preferred
274 // column-width as default with.
275 foreach (const QByteArray
& role
, m_visibleRoles
) {
276 if (m_headerWidget
->columnWidth(role
) == 0) {
277 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
278 m_headerWidget
->setColumnWidth(role
, width
);
282 applyColumnWidthsFromHeader();
286 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
287 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
288 (roles
.count() <= 1 && previousRoles
.count() > 1));
290 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
291 while (it
.hasNext()) {
293 KItemListWidget
* widget
= it
.value();
294 widget
->setVisibleRoles(roles
);
295 if (alternateBackgroundsChanged
) {
296 updateAlternateBackgroundForWidget(widget
);
300 doLayout(NoAnimation
);
303 QList
<QByteArray
> KItemListView::visibleRoles() const
305 return m_visibleRoles
;
308 void KItemListView::setAutoScroll(bool enabled
)
310 if (enabled
&& !m_autoScrollTimer
) {
311 m_autoScrollTimer
= new QTimer(this);
312 m_autoScrollTimer
->setSingleShot(true);
313 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
314 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
315 } else if (!enabled
&& m_autoScrollTimer
) {
316 delete m_autoScrollTimer
;
317 m_autoScrollTimer
= 0;
321 bool KItemListView::autoScroll() const
323 return m_autoScrollTimer
!= 0;
326 void KItemListView::setEnabledSelectionToggles(bool enabled
)
328 if (m_enabledSelectionToggles
!= enabled
) {
329 m_enabledSelectionToggles
= enabled
;
331 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
332 while (it
.hasNext()) {
334 it
.value()->setEnabledSelectionToggle(enabled
);
339 bool KItemListView::enabledSelectionToggles() const
341 return m_enabledSelectionToggles
;
344 KItemListController
* KItemListView::controller() const
349 KItemModelBase
* KItemListView::model() const
354 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
356 m_widgetCreator
= widgetCreator
;
359 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
361 return m_widgetCreator
;
364 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
366 m_groupHeaderCreator
= groupHeaderCreator
;
369 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
371 return m_groupHeaderCreator
;
374 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
376 const KItemListStyleOption previousOption
= m_styleOption
;
377 m_styleOption
= option
;
380 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
381 if (margin
!= m_layouter
->itemMargin()) {
382 // Skip animations when the number of rows or columns
383 // are changed in the grid layout. Although the animation
384 // engine can handle this usecase, it looks obtrusive.
385 animate
= !changesItemGridLayout(m_layouter
->size(),
386 m_layouter
->itemSize(),
388 m_layouter
->setItemMargin(margin
);
392 updateGroupHeaderHeight();
395 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
396 while (it
.hasNext()) {
398 it
.value()->setStyleOption(option
);
401 m_sizeHintResolver
->clearCache();
402 doLayout(animate
? Animation
: NoAnimation
);
404 onStyleOptionChanged(option
, previousOption
);
407 const KItemListStyleOption
& KItemListView::styleOption() const
409 return m_styleOption
;
412 void KItemListView::setGeometry(const QRectF
& rect
)
414 QGraphicsWidget::setGeometry(rect
);
420 const QSizeF newSize
= rect
.size();
421 if (m_itemSize
.isEmpty()) {
422 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
423 if (m_headerWidget
->automaticColumnResizing()) {
424 applyAutomaticColumnWidths();
426 const qreal requiredWidth
= columnWidthsSum();
427 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
428 m_itemSize
.height());
429 m_layouter
->setItemSize(dynamicItemSize
);
432 // Triggering a synchronous layout is fine from a performance point of view,
433 // as with dynamic item sizes no moving animation must be done.
434 m_layouter
->setSize(newSize
);
435 doLayout(NoAnimation
);
437 const bool animate
= !changesItemGridLayout(newSize
,
438 m_layouter
->itemSize(),
439 m_layouter
->itemMargin());
440 m_layouter
->setSize(newSize
);
443 // Trigger an asynchronous relayout with m_layoutTimer to prevent
444 // performance bottlenecks. If the timer is exceeded, an animated layout
445 // will be triggered.
446 if (!m_layoutTimer
->isActive()) {
447 m_layoutTimer
->start();
450 m_layoutTimer
->stop();
451 doLayout(NoAnimation
);
456 int KItemListView::itemAt(const QPointF
& pos
) const
458 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
459 while (it
.hasNext()) {
462 const KItemListWidget
* widget
= it
.value();
463 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
464 if (widget
->contains(mappedPos
)) {
472 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
474 if (!m_enabledSelectionToggles
) {
478 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
480 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
481 if (!selectionToggleRect
.isEmpty()) {
482 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
483 return selectionToggleRect
.contains(mappedPos
);
489 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
491 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
493 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
494 if (!expansionToggleRect
.isEmpty()) {
495 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
496 return expansionToggleRect
.contains(mappedPos
);
502 int KItemListView::firstVisibleIndex() const
504 return m_layouter
->firstVisibleIndex();
507 int KItemListView::lastVisibleIndex() const
509 return m_layouter
->lastVisibleIndex();
512 QSizeF
KItemListView::itemSizeHint(int index
) const
514 return m_widgetCreator
->itemSizeHint(index
, this);
517 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
519 if (m_supportsItemExpanding
!= supportsExpanding
) {
520 m_supportsItemExpanding
= supportsExpanding
;
521 updateSiblingsInformation();
522 onSupportsItemExpandingChanged(supportsExpanding
);
526 bool KItemListView::supportsItemExpanding() const
528 return m_supportsItemExpanding
;
531 QRectF
KItemListView::itemRect(int index
) const
533 return m_layouter
->itemRect(index
);
536 QRectF
KItemListView::itemContextRect(int index
) const
540 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
542 contextRect
= widget
->iconRect() | widget
->textRect();
543 contextRect
.translate(itemRect(index
).topLeft());
549 void KItemListView::scrollToItem(int index
)
551 QRectF viewGeometry
= geometry();
552 if (m_headerWidget
->isVisible()) {
553 const qreal headerHeight
= m_headerWidget
->size().height();
554 viewGeometry
.adjust(0, headerHeight
, 0, 0);
556 const QRectF currentRect
= itemRect(index
);
558 if (!viewGeometry
.contains(currentRect
)) {
559 qreal newOffset
= scrollOffset();
560 if (scrollOrientation() == Qt::Vertical
) {
561 if (currentRect
.top() < viewGeometry
.top()) {
562 newOffset
+= currentRect
.top() - viewGeometry
.top();
563 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
564 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
567 if (currentRect
.left() < viewGeometry
.left()) {
568 newOffset
+= currentRect
.left() - viewGeometry
.left();
569 } else if (currentRect
.right() > viewGeometry
.right()) {
570 newOffset
+= currentRect
.right() - viewGeometry
.right();
574 if (newOffset
!= scrollOffset()) {
575 emit
scrollTo(newOffset
);
580 void KItemListView::beginTransaction()
582 ++m_activeTransactions
;
583 if (m_activeTransactions
== 1) {
584 onTransactionBegin();
588 void KItemListView::endTransaction()
590 --m_activeTransactions
;
591 if (m_activeTransactions
< 0) {
592 m_activeTransactions
= 0;
593 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
596 if (m_activeTransactions
== 0) {
598 doLayout(m_endTransactionAnimationHint
);
599 m_endTransactionAnimationHint
= Animation
;
603 bool KItemListView::isTransactionActive() const
605 return m_activeTransactions
> 0;
608 void KItemListView::setHeaderVisible(bool visible
)
610 if (visible
&& !m_headerWidget
->isVisible()) {
611 QStyleOptionHeader option
;
612 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
615 m_headerWidget
->setPos(0, 0);
616 m_headerWidget
->resize(size().width(), headerSize
.height());
617 m_headerWidget
->setModel(m_model
);
618 m_headerWidget
->setColumns(m_visibleRoles
);
619 m_headerWidget
->setZValue(1);
621 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
622 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
623 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
624 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
625 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
626 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
627 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
628 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
630 m_layouter
->setHeaderHeight(headerSize
.height());
631 m_headerWidget
->setVisible(true);
632 } else if (!visible
&& m_headerWidget
->isVisible()) {
633 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
634 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
635 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
636 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
637 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
638 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
639 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
640 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
642 m_layouter
->setHeaderHeight(0);
643 m_headerWidget
->setVisible(false);
647 bool KItemListView::isHeaderVisible() const
649 return m_headerWidget
->isVisible();
652 KItemListHeader
* KItemListView::header() const
657 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
663 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
665 QGraphicsWidget::paint(painter
, option
, widget
);
667 if (m_rubberBand
->isActive()) {
668 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
669 m_rubberBand
->endPosition()).normalized();
671 const QPointF topLeft
= rubberBandRect
.topLeft();
672 if (scrollOrientation() == Qt::Vertical
) {
673 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
675 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
678 QStyleOptionRubberBand opt
;
679 opt
.initFrom(widget
);
680 opt
.shape
= QRubberBand::Rectangle
;
682 opt
.rect
= rubberBandRect
.toRect();
683 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
687 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
692 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
694 Q_UNUSED(changedRoles
);
698 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
704 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
710 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
716 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
722 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
728 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
734 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
740 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
742 Q_UNUSED(supportsExpanding
);
745 void KItemListView::onTransactionBegin()
749 void KItemListView::onTransactionEnd()
753 bool KItemListView::event(QEvent
* event
)
755 // Forward all events to the controller and handle them there
756 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
760 return QGraphicsWidget::event(event
);
763 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
765 m_mousePos
= transform().map(event
->pos());
769 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
771 QGraphicsWidget::mouseMoveEvent(event
);
773 m_mousePos
= transform().map(event
->pos());
774 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
775 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
779 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
781 event
->setAccepted(true);
785 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
787 QGraphicsWidget::dragMoveEvent(event
);
789 m_mousePos
= transform().map(event
->pos());
790 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
791 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
795 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
797 QGraphicsWidget::dragLeaveEvent(event
);
798 setAutoScroll(false);
801 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
803 QGraphicsWidget::dropEvent(event
);
804 setAutoScroll(false);
807 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
809 return m_visibleItems
.values();
812 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
814 if (m_itemSize
.isEmpty()) {
815 updatePreferredColumnWidths(itemRanges
);
818 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
819 if (hasMultipleRanges
) {
823 m_layouter
->markAsDirty();
825 int previouslyInsertedCount
= 0;
826 foreach (const KItemRange
& range
, itemRanges
) {
827 // range.index is related to the model before anything has been inserted.
828 // As in each loop the current item-range gets inserted the index must
829 // be increased by the already previously inserted items.
830 const int index
= range
.index
+ previouslyInsertedCount
;
831 const int count
= range
.count
;
832 if (index
< 0 || count
<= 0) {
833 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
836 previouslyInsertedCount
+= count
;
838 m_sizeHintResolver
->itemsInserted(index
, count
);
840 // Determine which visible items must be moved
841 QList
<int> itemsToMove
;
842 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
843 while (it
.hasNext()) {
845 const int visibleItemIndex
= it
.key();
846 if (visibleItemIndex
>= index
) {
847 itemsToMove
.append(visibleItemIndex
);
851 // Update the indexes of all KItemListWidget instances that are located
852 // after the inserted items. It is important to adjust the indexes in the order
853 // from the highest index to the lowest index to prevent overlaps when setting the new index.
855 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
856 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
858 const int newIndex
= widget
->index() + count
;
859 if (hasMultipleRanges
) {
860 setWidgetIndex(widget
, newIndex
);
862 // Try to animate the moving of the item
863 moveWidgetToIndex(widget
, newIndex
);
867 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
868 // Check whether a scrollbar is required to show the inserted items. In this case
869 // the size of the layouter will be decreased before calling doLayout(): This prevents
870 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
871 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
872 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
873 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
874 if (decreaseLayouterSize
) {
875 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
876 QSizeF layouterSize
= m_layouter
->size();
877 if (verticalScrollOrientation
) {
878 layouterSize
.rwidth() -= scrollBarExtent
;
880 layouterSize
.rheight() -= scrollBarExtent
;
882 m_layouter
->setSize(layouterSize
);
886 if (!hasMultipleRanges
) {
887 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
888 updateSiblingsInformation();
893 m_controller
->selectionManager()->itemsInserted(itemRanges
);
896 if (hasMultipleRanges
) {
898 // Important: Don't read any m_layouter-property inside the for-loop in case if
899 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
900 // updated in each loop-cycle and has only a consistent state after the loop.
901 Q_ASSERT(m_layouter
->isDirty());
903 m_endTransactionAnimationHint
= NoAnimation
;
905 updateSiblingsInformation();
908 if (useAlternateBackgrounds()) {
909 updateAlternateBackgrounds();
913 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
915 if (m_itemSize
.isEmpty()) {
916 // Don't pass the item-range: The preferred column-widths of
917 // all items must be adjusted when removing items.
918 updatePreferredColumnWidths();
921 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
922 if (hasMultipleRanges
) {
926 m_layouter
->markAsDirty();
928 int removedItemsCount
= 0;
929 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
930 removedItemsCount
+= itemRanges
[i
].count
;
933 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
934 const KItemRange
& range
= itemRanges
[i
];
935 const int index
= range
.index
;
936 const int count
= range
.count
;
937 if (index
< 0 || count
<= 0) {
938 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
942 m_sizeHintResolver
->itemsRemoved(index
, count
);
944 const int firstRemovedIndex
= index
;
945 const int lastRemovedIndex
= index
+ count
- 1;
946 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
947 removedItemsCount
-= count
;
949 // Remove all KItemListWidget instances that got deleted
950 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
951 KItemListWidget
* widget
= m_visibleItems
.value(i
);
956 m_animation
->stop(widget
);
957 // Stopping the animation might lead to recycling the widget if
958 // it is invisible (see slotAnimationFinished()).
959 // Check again whether it is still visible:
960 if (!m_visibleItems
.contains(i
)) {
964 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
965 // Remove the widget without animation
966 recycleWidget(widget
);
968 // Animate the removing of the items. Special case: When removing an item there
969 // is no valid model index available anymore. For the
970 // remove-animation the item gets removed from m_visibleItems but the widget
971 // will stay alive until the animation has been finished and will
972 // be recycled (deleted) in KItemListView::slotAnimationFinished().
973 m_visibleItems
.remove(i
);
974 widget
->setIndex(-1);
975 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
979 // Update the indexes of all KItemListWidget instances that are located
980 // after the deleted items
981 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
982 KItemListWidget
* widget
= m_visibleItems
.value(i
);
984 const int newIndex
= i
- count
;
985 if (hasMultipleRanges
) {
986 setWidgetIndex(widget
, newIndex
);
988 // Try to animate the moving of the item
989 moveWidgetToIndex(widget
, newIndex
);
994 if (!hasMultipleRanges
) {
995 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
996 // assumes an updated geometry. If items are removed during an active transaction,
997 // the transaction will be temporary deactivated so that doLayout() triggers a
998 // geometry update if necessary.
999 const int activeTransactions
= m_activeTransactions
;
1000 m_activeTransactions
= 0;
1001 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1002 m_activeTransactions
= activeTransactions
;
1003 updateSiblingsInformation();
1008 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1011 if (hasMultipleRanges
) {
1013 // Important: Don't read any m_layouter-property inside the for-loop in case if
1014 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1015 // updated in each loop-cycle and has only a consistent state after the loop.
1016 Q_ASSERT(m_layouter
->isDirty());
1018 m_endTransactionAnimationHint
= NoAnimation
;
1020 updateSiblingsInformation();
1023 if (useAlternateBackgrounds()) {
1024 updateAlternateBackgrounds();
1028 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1030 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1031 m_layouter
->markAsDirty();
1034 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1037 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1038 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1040 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1041 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1043 updateWidgetProperties(widget
, index
);
1044 initializeItemListWidget(widget
);
1048 doLayout(NoAnimation
);
1049 updateSiblingsInformation();
1052 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1053 const QSet
<QByteArray
>& roles
)
1055 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1056 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1057 updatePreferredColumnWidths(itemRanges
);
1060 foreach (const KItemRange
& itemRange
, itemRanges
) {
1061 const int index
= itemRange
.index
;
1062 const int count
= itemRange
.count
;
1064 if (updateSizeHints
) {
1065 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1066 m_layouter
->markAsDirty();
1068 if (!m_layoutTimer
->isActive()) {
1069 m_layoutTimer
->start();
1073 // Apply the changed roles to the visible item-widgets
1074 const int lastIndex
= index
+ count
- 1;
1075 for (int i
= index
; i
<= lastIndex
; ++i
) {
1076 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1078 widget
->setData(m_model
->data(i
), roles
);
1082 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1083 // The sort-role has been changed which might result
1084 // in modified group headers
1085 updateVisibleGroupHeaders();
1086 doLayout(NoAnimation
);
1091 void KItemListView::slotGroupedSortingChanged(bool current
)
1093 m_grouped
= current
;
1094 m_layouter
->markAsDirty();
1097 updateGroupHeaderHeight();
1099 // Clear all visible headers
1100 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1101 while (it
.hasNext()) {
1103 recycleGroupHeaderForWidget(it
.key());
1105 Q_ASSERT(m_visibleGroups
.isEmpty());
1108 if (useAlternateBackgrounds()) {
1109 // Changing the group mode requires to update the alternate backgrounds
1110 // as with the enabled group mode the altering is done on base of the first
1112 updateAlternateBackgrounds();
1114 updateSiblingsInformation();
1115 doLayout(NoAnimation
);
1118 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1123 updateVisibleGroupHeaders();
1124 doLayout(NoAnimation
);
1128 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1133 updateVisibleGroupHeaders();
1134 doLayout(NoAnimation
);
1138 void KItemListView::slotCurrentChanged(int current
, int previous
)
1142 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1143 if (previousWidget
) {
1144 previousWidget
->setCurrent(false);
1147 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1148 if (currentWidget
) {
1149 currentWidget
->setCurrent(true);
1153 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1157 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1158 while (it
.hasNext()) {
1160 const int index
= it
.key();
1161 KItemListWidget
* widget
= it
.value();
1162 widget
->setSelected(current
.contains(index
));
1166 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1167 KItemListViewAnimation::AnimationType type
)
1169 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1170 Q_ASSERT(itemListWidget
);
1173 case KItemListViewAnimation::DeleteAnimation
: {
1174 // As we recycle the widget in this case it is important to assure that no
1175 // other animation has been started. This is a convention in KItemListView and
1176 // not a requirement defined by KItemListViewAnimation.
1177 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1179 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1180 // by m_visibleWidgets and must be deleted manually after the animation has
1182 recycleGroupHeaderForWidget(itemListWidget
);
1183 m_widgetCreator
->recycle(itemListWidget
);
1187 case KItemListViewAnimation::CreateAnimation
:
1188 case KItemListViewAnimation::MovingAnimation
:
1189 case KItemListViewAnimation::ResizeAnimation
: {
1190 const int index
= itemListWidget
->index();
1191 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1192 (index
> m_layouter
->lastVisibleIndex());
1193 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1194 recycleWidget(itemListWidget
);
1203 void KItemListView::slotLayoutTimerFinished()
1205 m_layouter
->setSize(geometry().size());
1206 doLayout(Animation
);
1209 void KItemListView::slotRubberBandPosChanged()
1214 void KItemListView::slotRubberBandActivationChanged(bool active
)
1217 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1218 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1219 m_skipAutoScrollForRubberBand
= true;
1221 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1222 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1223 m_skipAutoScrollForRubberBand
= false;
1229 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1231 qreal previousWidth
)
1234 Q_UNUSED(currentWidth
);
1235 Q_UNUSED(previousWidth
);
1237 m_headerWidget
->setAutomaticColumnResizing(false);
1238 applyColumnWidthsFromHeader();
1239 doLayout(NoAnimation
);
1242 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1246 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1248 const QList
<QByteArray
> previous
= m_visibleRoles
;
1250 QList
<QByteArray
> current
= m_visibleRoles
;
1251 current
.removeAt(previousIndex
);
1252 current
.insert(currentIndex
, role
);
1254 setVisibleRoles(current
);
1256 emit
visibleRolesChanged(current
, previous
);
1259 void KItemListView::triggerAutoScrolling()
1261 if (!m_autoScrollTimer
) {
1266 int visibleSize
= 0;
1267 if (scrollOrientation() == Qt::Vertical
) {
1268 pos
= m_mousePos
.y();
1269 visibleSize
= size().height();
1271 pos
= m_mousePos
.x();
1272 visibleSize
= size().width();
1275 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1276 m_autoScrollIncrement
= 0;
1279 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1280 if (m_autoScrollIncrement
== 0) {
1281 // The mouse position is not above an autoscroll margin (the autoscroll timer
1282 // will be restarted in mouseMoveEvent())
1283 m_autoScrollTimer
->stop();
1287 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1288 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1289 // if the direction of the rubberband is similar to the autoscroll direction. This
1290 // prevents that starting to create a rubberband within the autoscroll margins starts
1291 // an autoscrolling.
1293 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1294 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1295 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1296 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1297 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1298 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1299 // been moved up although the autoscroll direction might be down)
1300 m_autoScrollTimer
->stop();
1305 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1306 // the autoscrolling may not get skipped anymore until a new rubberband is created
1307 m_skipAutoScrollForRubberBand
= false;
1309 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1310 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1311 setScrollOffset(newScrollOffset
);
1313 // Trigger the autoscroll timer which will periodically call
1314 // triggerAutoScrolling()
1315 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1318 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1320 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1322 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1323 Q_ASSERT(groupHeader
);
1324 updateGroupHeaderLayout(widget
);
1327 void KItemListView::setController(KItemListController
* controller
)
1329 if (m_controller
!= controller
) {
1330 KItemListController
* previous
= m_controller
;
1332 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1333 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1334 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1337 m_controller
= controller
;
1340 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1341 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1342 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1345 onControllerChanged(controller
, previous
);
1349 void KItemListView::setModel(KItemModelBase
* model
)
1351 if (m_model
== model
) {
1355 KItemModelBase
* previous
= m_model
;
1358 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1359 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1360 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1361 this, SLOT(slotItemsInserted(KItemRangeList
)));
1362 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1363 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1364 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1365 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1366 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1367 this, SLOT(slotGroupedSortingChanged(bool)));
1368 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1369 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1370 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1371 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1375 m_layouter
->setModel(model
);
1376 m_grouped
= model
->groupedSorting();
1379 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1380 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1381 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1382 this, SLOT(slotItemsInserted(KItemRangeList
)));
1383 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1384 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1385 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1386 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1387 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1388 this, SLOT(slotGroupedSortingChanged(bool)));
1389 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1390 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1391 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1392 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1395 onModelChanged(model
, previous
);
1398 KItemListRubberBand
* KItemListView::rubberBand() const
1400 return m_rubberBand
;
1403 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1405 if (m_layoutTimer
->isActive()) {
1406 m_layoutTimer
->stop();
1409 if (m_activeTransactions
> 0) {
1410 if (hint
== NoAnimation
) {
1411 // As soon as at least one property change should be done without animation,
1412 // the whole transaction will be marked as not animated.
1413 m_endTransactionAnimationHint
= NoAnimation
;
1418 if (!m_model
|| m_model
->count() < 0) {
1422 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1423 if (firstVisibleIndex
< 0) {
1424 emitOffsetChanges();
1428 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1429 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1430 // is still shown if the maximum offset got decreased.
1431 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1432 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1433 if (scrollOffset() > maxOffsetToShowFullRange
) {
1434 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1435 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1438 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1440 int firstSibblingIndex
= -1;
1441 int lastSibblingIndex
= -1;
1442 const bool supportsExpanding
= supportsItemExpanding();
1444 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1446 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1447 // instances from invisible items are reused. If no reusable items are
1448 // found then new KItemListWidget instances get created.
1449 const bool animate
= (hint
== Animation
);
1450 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1451 bool applyNewPos
= true;
1452 bool wasHidden
= false;
1454 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1455 const QPointF newPos
= itemBounds
.topLeft();
1456 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1459 if (!reusableItems
.isEmpty()) {
1460 // Reuse a KItemListWidget instance from an invisible item
1461 const int oldIndex
= reusableItems
.takeLast();
1462 widget
= m_visibleItems
.value(oldIndex
);
1463 setWidgetIndex(widget
, i
);
1464 updateWidgetProperties(widget
, i
);
1465 initializeItemListWidget(widget
);
1467 // No reusable KItemListWidget instance is available, create a new one
1468 widget
= createWidget(i
);
1470 widget
->resize(itemBounds
.size());
1472 if (animate
&& changedCount
< 0) {
1473 // Items have been deleted, move the created item to the
1474 // imaginary old position. They will get animated to the new position
1476 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1477 if (itemRect
.isEmpty()) {
1478 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1479 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1480 widget
->setPos(invisibleOldPos
);
1482 widget
->setPos(itemRect
.topLeft());
1484 applyNewPos
= false;
1487 if (supportsExpanding
&& changedCount
== 0) {
1488 if (firstSibblingIndex
< 0) {
1489 firstSibblingIndex
= i
;
1491 lastSibblingIndex
= i
;
1496 const bool itemsRemoved
= (changedCount
< 0);
1497 const bool itemsInserted
= (changedCount
> 0);
1498 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1499 // The item is located after the removed items. Animate the moving of the position.
1500 applyNewPos
= !moveWidget(widget
, newPos
);
1501 } else if (itemsInserted
&& i
>= changedIndex
) {
1502 // The item is located after the first inserted item
1503 if (i
<= changedIndex
+ changedCount
- 1) {
1504 // The item is an inserted item. Animate the appearing of the item.
1505 // For performance reasons no animation is done when changedCount is equal
1506 // to all available items.
1507 if (changedCount
< m_model
->count()) {
1508 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1510 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1511 // The item was already there before, so animate the moving of the position.
1512 // No moving animation is done if the item is animated by a create animation: This
1513 // prevents a "move animation mess" when inserting several ranges in parallel.
1514 applyNewPos
= !moveWidget(widget
, newPos
);
1516 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1517 // The size of the view might have been changed. Animate the moving of the position.
1518 applyNewPos
= !moveWidget(widget
, newPos
);
1521 m_animation
->stop(widget
);
1525 widget
->setPos(newPos
);
1528 Q_ASSERT(widget
->index() == i
);
1529 widget
->setVisible(true);
1531 if (widget
->size() != itemBounds
.size()) {
1532 // Resize the widget for the item to the changed size.
1534 // If a dynamic item size is used then no animation is done in the direction
1535 // of the dynamic size.
1536 if (m_itemSize
.width() <= 0) {
1537 // The width is dynamic, apply the new width without animation.
1538 widget
->resize(itemBounds
.width(), widget
->size().height());
1539 } else if (m_itemSize
.height() <= 0) {
1540 // The height is dynamic, apply the new height without animation.
1541 widget
->resize(widget
->size().width(), itemBounds
.height());
1543 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1545 widget
->resize(itemBounds
.size());
1549 // Updating the cell-information must be done as last step: The decision whether the
1550 // moving-animation should be started at all is based on the previous cell-information.
1551 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1552 m_visibleCells
.insert(i
, cell
);
1555 // Delete invisible KItemListWidget instances that have not been reused
1556 foreach (int index
, reusableItems
) {
1557 recycleWidget(m_visibleItems
.value(index
));
1560 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1561 Q_ASSERT(lastSibblingIndex
>= 0);
1562 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1566 // Update the layout of all visible group headers
1567 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1568 while (it
.hasNext()) {
1570 updateGroupHeaderLayout(it
.key());
1574 emitOffsetChanges();
1577 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1578 int lastVisibleIndex
,
1579 LayoutAnimationHint hint
)
1581 // Determine all items that are completely invisible and might be
1582 // reused for items that just got (at least partly) visible. If the
1583 // animation hint is set to 'Animation' items that do e.g. an animated
1584 // moving of their position are not marked as invisible: This assures
1585 // that a scrolling inside the view can be done without breaking an animation.
1589 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1590 while (it
.hasNext()) {
1593 KItemListWidget
* widget
= it
.value();
1594 const int index
= widget
->index();
1595 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1598 if (m_animation
->isStarted(widget
)) {
1599 if (hint
== NoAnimation
) {
1600 // Stopping the animation will call KItemListView::slotAnimationFinished()
1601 // and the widget will be recycled if necessary there.
1602 m_animation
->stop(widget
);
1605 widget
->setVisible(false);
1606 items
.append(index
);
1609 recycleGroupHeaderForWidget(widget
);
1618 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1620 if (widget
->pos() == newPos
) {
1624 bool startMovingAnim
= false;
1626 // When having a grid the moving-animation should only be started, if it is done within
1627 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1628 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1629 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1630 const int index
= widget
->index();
1631 const Cell cell
= m_visibleCells
.value(index
);
1632 if (cell
.column
>= 0 && cell
.row
>= 0) {
1633 if (scrollOrientation() == Qt::Vertical
) {
1634 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1636 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1640 if (startMovingAnim
) {
1641 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1645 m_animation
->stop(widget
);
1646 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1650 void KItemListView::emitOffsetChanges()
1652 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1653 if (m_oldScrollOffset
!= newScrollOffset
) {
1654 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1655 m_oldScrollOffset
= newScrollOffset
;
1658 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1659 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1660 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1661 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1664 const qreal newItemOffset
= m_layouter
->itemOffset();
1665 if (m_oldItemOffset
!= newItemOffset
) {
1666 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1667 m_oldItemOffset
= newItemOffset
;
1670 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1671 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1672 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1673 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1677 KItemListWidget
* KItemListView::createWidget(int index
)
1679 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1680 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1682 m_visibleItems
.insert(index
, widget
);
1683 m_visibleCells
.insert(index
, Cell());
1684 updateWidgetProperties(widget
, index
);
1685 initializeItemListWidget(widget
);
1689 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1692 recycleGroupHeaderForWidget(widget
);
1695 const int index
= widget
->index();
1696 m_visibleItems
.remove(index
);
1697 m_visibleCells
.remove(index
);
1699 m_widgetCreator
->recycle(widget
);
1702 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1704 const int oldIndex
= widget
->index();
1705 m_visibleItems
.remove(oldIndex
);
1706 m_visibleCells
.remove(oldIndex
);
1708 m_visibleItems
.insert(index
, widget
);
1709 m_visibleCells
.insert(index
, Cell());
1711 widget
->setIndex(index
);
1714 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1716 const int oldIndex
= widget
->index();
1717 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1719 setWidgetIndex(widget
, index
);
1721 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1722 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1723 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1724 (!vertical
&& oldCell
.column
== newCell
.column
);
1726 m_visibleCells
.insert(index
, newCell
);
1730 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1733 case LayouterSize
: m_layouter
->setSize(size
); break;
1734 case ItemSize
: m_layouter
->setItemSize(size
); break;
1739 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1741 widget
->setVisibleRoles(m_visibleRoles
);
1742 updateWidgetColumnWidths(widget
);
1743 widget
->setStyleOption(m_styleOption
);
1745 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1746 widget
->setCurrent(index
== selectionManager
->currentItem());
1747 widget
->setSelected(selectionManager
->isSelected(index
));
1748 widget
->setHovered(false);
1749 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1750 widget
->setIndex(index
);
1751 widget
->setData(m_model
->data(index
));
1752 widget
->setSiblingsInformation(QBitArray());
1753 updateAlternateBackgroundForWidget(widget
);
1756 updateGroupHeaderForWidget(widget
);
1760 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1762 Q_ASSERT(m_grouped
);
1764 const int index
= widget
->index();
1765 if (!m_layouter
->isFirstGroupItem(index
)) {
1766 // The widget does not represent the first item of a group
1767 // and hence requires no header
1768 recycleGroupHeaderForWidget(widget
);
1772 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1773 if (groups
.isEmpty()) {
1777 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1779 groupHeader
= m_groupHeaderCreator
->create(this);
1780 groupHeader
->setParentItem(widget
);
1781 m_visibleGroups
.insert(widget
, groupHeader
);
1782 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1784 Q_ASSERT(groupHeader
->parentItem() == widget
);
1786 const int groupIndex
= groupIndexForItem(index
);
1787 Q_ASSERT(groupIndex
>= 0);
1788 groupHeader
->setData(groups
.at(groupIndex
).second
);
1789 groupHeader
->setRole(model()->sortRole());
1790 groupHeader
->setStyleOption(m_styleOption
);
1791 groupHeader
->setScrollOrientation(scrollOrientation());
1792 groupHeader
->setItemIndex(index
);
1794 groupHeader
->show();
1797 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1799 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1800 Q_ASSERT(groupHeader
);
1802 const int index
= widget
->index();
1803 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1804 const QRectF itemRect
= m_layouter
->itemRect(index
);
1806 // The group-header is a child of the itemlist widget. Translate the
1807 // group header position to the relative position.
1808 if (scrollOrientation() == Qt::Vertical
) {
1809 // In the vertical scroll orientation the group header should always span
1810 // the whole width no matter which temporary position the parent widget
1811 // has. In this case the x-position and width will be adjusted manually.
1812 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1813 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1815 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1816 groupHeader
->resize(groupHeaderRect
.size());
1820 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1822 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1824 header
->setParentItem(0);
1825 m_groupHeaderCreator
->recycle(header
);
1826 m_visibleGroups
.remove(widget
);
1827 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1831 void KItemListView::updateVisibleGroupHeaders()
1833 Q_ASSERT(m_grouped
);
1834 m_layouter
->markAsDirty();
1836 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1837 while (it
.hasNext()) {
1839 updateGroupHeaderForWidget(it
.value());
1843 int KItemListView::groupIndexForItem(int index
) const
1845 Q_ASSERT(m_grouped
);
1847 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1848 if (groups
.isEmpty()) {
1853 int max
= groups
.count() - 1;
1856 mid
= (min
+ max
) / 2;
1857 if (index
> groups
[mid
].first
) {
1862 } while (groups
[mid
].first
!= index
&& min
<= max
);
1865 while (groups
[mid
].first
> index
&& mid
> 0) {
1873 void KItemListView::updateAlternateBackgrounds()
1875 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1876 while (it
.hasNext()) {
1878 updateAlternateBackgroundForWidget(it
.value());
1882 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1884 bool enabled
= useAlternateBackgrounds();
1886 const int index
= widget
->index();
1887 enabled
= (index
& 0x1) > 0;
1889 const int groupIndex
= groupIndexForItem(index
);
1890 if (groupIndex
>= 0) {
1891 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1892 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1893 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1894 enabled
= (relativeIndex
& 0x1) > 0;
1898 widget
->setAlternateBackground(enabled
);
1901 bool KItemListView::useAlternateBackgrounds() const
1903 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1906 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
1908 QElapsedTimer timer
;
1911 QHash
<QByteArray
, qreal
> widths
;
1913 // Calculate the minimum width for each column that is required
1914 // to show the headline unclipped.
1915 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
1916 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
1917 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
1918 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
1919 const QString headerText
= m_model
->roleDescription(visibleRole
);
1920 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
1921 widths
.insert(visibleRole
, headerWidth
);
1924 // Calculate the preferred column withs for each item and ignore values
1925 // smaller than the width for showing the headline unclipped.
1926 int calculatedItemCount
= 0;
1927 bool maxTimeExceeded
= false;
1928 foreach (const KItemRange
& itemRange
, itemRanges
) {
1929 const int startIndex
= itemRange
.index
;
1930 const int endIndex
= startIndex
+ itemRange
.count
- 1;
1932 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
1933 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
1934 qreal maxWidth
= widths
.value(visibleRole
, 0);
1935 const qreal width
= m_widgetCreator
->preferredRoleColumnWidth(visibleRole
, i
, this);
1936 maxWidth
= qMax(width
, maxWidth
);
1937 widths
.insert(visibleRole
, maxWidth
);
1940 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
1941 // When having several thousands of items calculating the sizes can get
1942 // very expensive. We accept a possibly too small role-size in favour
1943 // of having no blocking user interface.
1944 maxTimeExceeded
= true;
1947 ++calculatedItemCount
;
1949 if (maxTimeExceeded
) {
1957 void KItemListView::applyColumnWidthsFromHeader()
1959 // Apply the new size to the layouter
1960 const qreal requiredWidth
= columnWidthsSum();
1961 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
1962 m_itemSize
.height());
1963 m_layouter
->setItemSize(dynamicItemSize
);
1965 // Update the role sizes for all visible widgets
1966 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1967 while (it
.hasNext()) {
1969 updateWidgetColumnWidths(it
.value());
1973 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
1975 foreach (const QByteArray
& role
, m_visibleRoles
) {
1976 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
1980 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
1982 Q_ASSERT(m_itemSize
.isEmpty());
1983 const int itemCount
= m_model
->count();
1984 int rangesItemCount
= 0;
1985 foreach (const KItemRange
& range
, itemRanges
) {
1986 rangesItemCount
+= range
.count
;
1989 if (itemCount
== rangesItemCount
) {
1990 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
1991 foreach (const QByteArray
& role
, m_visibleRoles
) {
1992 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
1995 // Only a sub range of the roles need to be determined.
1996 // The chances are good that the widths of the sub ranges
1997 // already fit into the available widths and hence no
1998 // expensive update might be required.
1999 bool changed
= false;
2001 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2002 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2003 while (it
.hasNext()) {
2005 const QByteArray
& role
= it
.key();
2006 const qreal updatedWidth
= it
.value();
2007 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2008 if (updatedWidth
> currentWidth
) {
2009 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2015 // All the updated sizes are smaller than the current sizes and no change
2016 // of the stretched roles-widths is required
2021 if (m_headerWidget
->automaticColumnResizing()) {
2022 applyAutomaticColumnWidths();
2026 void KItemListView::updatePreferredColumnWidths()
2029 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2033 void KItemListView::applyAutomaticColumnWidths()
2035 Q_ASSERT(m_itemSize
.isEmpty());
2036 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2038 // Calculate the maximum size of an item by considering the
2039 // visible role sizes and apply them to the layouter. If the
2040 // size does not use the available view-size the size of the
2041 // first role will get stretched.
2043 foreach (const QByteArray
& role
, m_visibleRoles
) {
2044 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2045 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2048 const QByteArray firstRole
= m_visibleRoles
.first();
2049 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2050 QSizeF dynamicItemSize
= m_itemSize
;
2052 qreal requiredWidth
= columnWidthsSum();
2053 const qreal availableWidth
= size().width();
2054 if (requiredWidth
< availableWidth
) {
2055 // Stretch the first column to use the whole remaining width
2056 firstColumnWidth
+= availableWidth
- requiredWidth
;
2057 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2058 } else if (requiredWidth
> availableWidth
) {
2059 // Shrink the first column to be able to show as much other
2060 // columns as possible
2061 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2063 // TODO: A proper calculation of the minimum width depends on the implementation
2064 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2066 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2067 if (shrinkedFirstColumnWidth
< minWidth
) {
2068 shrinkedFirstColumnWidth
= minWidth
;
2071 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2072 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2075 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2077 m_layouter
->setItemSize(dynamicItemSize
);
2079 // Update the role sizes for all visible widgets
2080 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2081 while (it
.hasNext()) {
2083 updateWidgetColumnWidths(it
.value());
2087 qreal
KItemListView::columnWidthsSum() const
2089 qreal widthsSum
= 0;
2090 foreach (const QByteArray
& role
, m_visibleRoles
) {
2091 widthsSum
+= m_headerWidget
->columnWidth(role
);
2096 QRectF
KItemListView::headerBoundaries() const
2098 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2101 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2102 const QSizeF
& newItemSize
,
2103 const QSizeF
& newItemMargin
) const
2105 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2109 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2110 const qreal itemWidth
= m_layouter
->itemSize().width();
2111 if (itemWidth
> 0) {
2112 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2113 newItemSize
.width(),
2114 newItemMargin
.width());
2115 if (m_model
->count() > newColumnCount
) {
2116 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2118 m_layouter
->itemMargin().width());
2119 return oldColumnCount
!= newColumnCount
;
2123 const qreal itemHeight
= m_layouter
->itemSize().height();
2124 if (itemHeight
> 0) {
2125 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2126 newItemSize
.height(),
2127 newItemMargin
.height());
2128 if (m_model
->count() > newRowCount
) {
2129 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2131 m_layouter
->itemMargin().height());
2132 return oldRowCount
!= newRowCount
;
2140 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2142 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2146 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2147 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2148 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2149 // Only animate if up to 2/3 of a row or column are inserted or removed
2150 return changedItemCount
<= maximum
* 2 / 3;
2154 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2156 const QSizeF oldSize
= m_layouter
->size();
2158 m_layouter
->setSize(size
);
2159 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2160 m_layouter
->setSize(oldSize
);
2162 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2163 : maxOffset
> size
.width();
2166 void KItemListView::updateGroupHeaderHeight()
2168 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2169 qreal groupHeaderMargin
= 0;
2171 if (scrollOrientation() == Qt::Horizontal
) {
2172 // The vertical margin above and below the header should be
2173 // equal to the horizontal margin, not the vertical margin
2174 // from m_styleOption.
2175 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2176 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2177 } else if (m_itemSize
.isEmpty()){
2178 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2179 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2181 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2182 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2184 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2185 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2187 updateVisibleGroupHeaders();
2190 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2192 if (!supportsItemExpanding() || !m_model
) {
2196 if (firstIndex
< 0 || lastIndex
< 0) {
2197 firstIndex
= m_layouter
->firstVisibleIndex();
2198 lastIndex
= m_layouter
->lastVisibleIndex();
2200 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2201 lastIndex
>= m_layouter
->firstVisibleIndex());
2202 if (!isRangeVisible
) {
2207 int previousParents
= 0;
2208 QBitArray previousSiblings
;
2210 // The rootIndex describes the first index where the siblings get
2211 // calculated from. For the calculation the upper most parent item
2212 // is required. For performance reasons it is checked first whether
2213 // the visible items before or after the current range already
2214 // contain a siblings information which can be used as base.
2215 int rootIndex
= firstIndex
;
2217 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2219 // There is no visible widget before the range, check whether there
2220 // is one after the range:
2221 widget
= m_visibleItems
.value(lastIndex
+ 1);
2223 // The sibling information of the widget may only be used if
2224 // all items of the range have the same number of parents.
2225 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2226 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2227 if (m_model
->expandedParentsCount(i
) != parents
) {
2236 // Performance optimization: Use the sibling information of the visible
2237 // widget beside the given range.
2238 previousSiblings
= widget
->siblingsInformation();
2239 if (previousSiblings
.isEmpty()) {
2242 previousParents
= previousSiblings
.count() - 1;
2243 previousSiblings
.truncate(previousParents
);
2245 // Potentially slow path: Go back to the upper most parent of firstIndex
2246 // to be able to calculate the initial value for the siblings.
2247 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2252 Q_ASSERT(previousParents
>= 0);
2253 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2254 // Update the parent-siblings in case if the current item represents
2255 // a child or an upper parent.
2256 const int currentParents
= m_model
->expandedParentsCount(i
);
2257 Q_ASSERT(currentParents
>= 0);
2258 if (previousParents
< currentParents
) {
2259 previousParents
= currentParents
;
2260 previousSiblings
.resize(currentParents
);
2261 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2262 } else if (previousParents
> currentParents
) {
2263 previousParents
= currentParents
;
2264 previousSiblings
.truncate(currentParents
);
2267 if (i
>= firstIndex
) {
2268 // The index represents a visible item. Apply the parent-siblings
2269 // and update the sibling of the current item.
2270 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2275 QBitArray siblings
= previousSiblings
;
2276 siblings
.resize(siblings
.count() + 1);
2277 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2279 widget
->setSiblingsInformation(siblings
);
2284 bool KItemListView::hasSiblingSuccessor(int index
) const
2286 bool hasSuccessor
= false;
2287 const int parentsCount
= m_model
->expandedParentsCount(index
);
2288 int successorIndex
= index
+ 1;
2290 // Search the next sibling
2291 const int itemCount
= m_model
->count();
2292 while (successorIndex
< itemCount
) {
2293 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2294 if (currentParentsCount
== parentsCount
) {
2295 hasSuccessor
= true;
2297 } else if (currentParentsCount
< parentsCount
) {
2303 if (m_grouped
&& hasSuccessor
) {
2304 // If the sibling is part of another group, don't mark it as
2305 // successor as the group header is between the sibling connections.
2306 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2307 if (m_layouter
->isFirstGroupItem(i
)) {
2308 hasSuccessor
= false;
2314 return hasSuccessor
;
2317 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2321 const int minSpeed
= 4;
2322 const int maxSpeed
= 128;
2323 const int speedLimiter
= 96;
2324 const int autoScrollBorder
= 64;
2326 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2327 // This assures that the autoscrolling speed grows gradually.
2328 const int incLimiter
= 1;
2330 if (pos
< autoScrollBorder
) {
2331 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2332 inc
= qMax(inc
, -maxSpeed
);
2333 inc
= qMax(inc
, oldInc
- incLimiter
);
2334 } else if (pos
> range
- autoScrollBorder
) {
2335 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2336 inc
= qMin(inc
, maxSpeed
);
2337 inc
= qMin(inc
, oldInc
+ incLimiter
);
2343 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2345 const qreal availableSize
= size
- itemMargin
;
2346 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2352 KItemListCreatorBase::~KItemListCreatorBase()
2354 qDeleteAll(m_recycleableWidgets
);
2355 qDeleteAll(m_createdWidgets
);
2358 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2360 m_createdWidgets
.insert(widget
);
2363 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2365 Q_ASSERT(m_createdWidgets
.contains(widget
));
2366 m_createdWidgets
.remove(widget
);
2368 if (m_recycleableWidgets
.count() < 100) {
2369 m_recycleableWidgets
.append(widget
);
2370 widget
->setVisible(false);
2376 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2378 if (m_recycleableWidgets
.isEmpty()) {
2382 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2383 m_createdWidgets
.insert(widget
);
2387 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2391 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2393 widget
->setParentItem(0);
2394 widget
->setOpacity(1.0);
2395 pushRecycleableWidget(widget
);
2398 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2402 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2404 header
->setOpacity(1.0);
2405 pushRecycleableWidget(header
);
2408 #include "kitemlistview.moc"