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 "kitemlistheaderwidget_p.h"
28 #include "kitemlistrubberband_p.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistsizehintresolver_p.h"
31 #include "kitemlistviewlayouter_p.h"
32 #include "kitemlistviewanimation_p.h"
33 #include "kitemlistwidget.h"
38 #include <QGraphicsSceneMouseEvent>
40 #include <QPropertyAnimation>
42 #include <QStyleOptionRubberBand>
46 // Time in ms until reaching the autoscroll margin triggers
47 // an initial autoscrolling
48 const int InitialAutoScrollDelay
= 700;
50 // Delay in ms for triggering the next autoscroll
51 const int RepeatingAutoScrollDelay
= 1000 / 60;
54 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
55 QGraphicsWidget(parent
),
56 m_enabledSelectionToggles(false),
58 m_supportsItemExpanding(false),
59 m_activeTransactions(0),
60 m_endTransactionAnimationHint(Animation
),
66 m_groupHeaderCreator(0),
71 m_sizeHintResolver(0),
76 m_oldMaximumScrollOffset(0),
78 m_oldMaximumItemOffset(0),
79 m_skipAutoScrollForRubberBand(false),
82 m_autoScrollIncrement(0),
87 setAcceptHoverEvents(true);
89 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
91 m_layouter
= new KItemListViewLayouter(this);
92 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
94 m_animation
= new KItemListViewAnimation(this);
95 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
96 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
98 m_layoutTimer
= new QTimer(this);
99 m_layoutTimer
->setInterval(300);
100 m_layoutTimer
->setSingleShot(true);
101 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
103 m_rubberBand
= new KItemListRubberBand(this);
104 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
106 m_headerWidget
= new KItemListHeaderWidget(this);
107 m_headerWidget
->setVisible(false);
109 m_header
= new KItemListHeader(this);
112 KItemListView::~KItemListView()
114 delete m_sizeHintResolver
;
115 m_sizeHintResolver
= 0;
118 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
120 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
121 if (orientation
== previousOrientation
) {
125 m_layouter
->setScrollOrientation(orientation
);
126 m_animation
->setScrollOrientation(orientation
);
127 m_sizeHintResolver
->clearCache();
130 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
131 while (it
.hasNext()) {
133 it
.value()->setScrollOrientation(orientation
);
135 updateGroupHeaderHeight();
139 doLayout(NoAnimation
);
141 onScrollOrientationChanged(orientation
, previousOrientation
);
142 emit
scrollOrientationChanged(orientation
, previousOrientation
);
145 Qt::Orientation
KItemListView::scrollOrientation() const
147 return m_layouter
->scrollOrientation();
150 void KItemListView::setItemSize(const QSizeF
& itemSize
)
152 const QSizeF previousSize
= m_itemSize
;
153 if (itemSize
== previousSize
) {
157 // Skip animations when the number of rows or columns
158 // are changed in the grid layout. Although the animation
159 // engine can handle this usecase, it looks obtrusive.
160 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
162 m_layouter
->itemMargin());
164 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
165 (( m_itemSize
.isEmpty() && !itemSize
.isEmpty()) ||
166 (!m_itemSize
.isEmpty() && itemSize
.isEmpty()));
168 m_itemSize
= itemSize
;
170 if (alternateBackgroundsChanged
) {
171 // For an empty item size alternate backgrounds are drawn if more than
172 // one role is shown. Assure that the backgrounds for visible items are
173 // updated when changing the size in this context.
174 updateAlternateBackgrounds();
177 if (itemSize
.isEmpty()) {
178 if (m_headerWidget
->automaticColumnResizing()) {
179 updatePreferredColumnWidths();
181 // Only apply the changed height and respect the header widths
183 const qreal currentWidth
= m_layouter
->itemSize().width();
184 const QSizeF
newSize(currentWidth
, itemSize
.height());
185 m_layouter
->setItemSize(newSize
);
188 m_layouter
->setItemSize(itemSize
);
191 m_sizeHintResolver
->clearCache();
192 doLayout(animate
? Animation
: NoAnimation
);
193 onItemSizeChanged(itemSize
, previousSize
);
196 QSizeF
KItemListView::itemSize() const
201 void KItemListView::setScrollOffset(qreal offset
)
207 const qreal previousOffset
= m_layouter
->scrollOffset();
208 if (offset
== previousOffset
) {
212 m_layouter
->setScrollOffset(offset
);
213 m_animation
->setScrollOffset(offset
);
215 // Don't check whether the m_layoutTimer is active: Changing the
216 // scroll offset must always trigger a synchronous layout, otherwise
217 // the smooth-scrolling might get jerky.
218 doLayout(NoAnimation
);
219 onScrollOffsetChanged(offset
, previousOffset
);
222 qreal
KItemListView::scrollOffset() const
224 return m_layouter
->scrollOffset();
227 qreal
KItemListView::maximumScrollOffset() const
229 return m_layouter
->maximumScrollOffset();
232 void KItemListView::setItemOffset(qreal offset
)
234 if (m_layouter
->itemOffset() == offset
) {
238 m_layouter
->setItemOffset(offset
);
239 if (m_headerWidget
->isVisible()) {
240 m_headerWidget
->setPos(-offset
, 0);
243 // Don't check whether the m_layoutTimer is active: Changing the
244 // item offset must always trigger a synchronous layout, otherwise
245 // the smooth-scrolling might get jerky.
246 doLayout(NoAnimation
);
249 qreal
KItemListView::itemOffset() const
251 return m_layouter
->itemOffset();
254 qreal
KItemListView::maximumItemOffset() const
256 return m_layouter
->maximumItemOffset();
259 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
261 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
262 m_visibleRoles
= roles
;
264 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
265 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
266 (roles
.count() <= 1 && previousRoles
.count() > 1));
268 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
269 while (it
.hasNext()) {
271 KItemListWidget
* widget
= it
.value();
272 widget
->setVisibleRoles(roles
);
273 updateWidgetColumnWidths(widget
);
274 if (alternateBackgroundsChanged
) {
275 updateAlternateBackgroundForWidget(widget
);
279 m_sizeHintResolver
->clearCache();
280 m_layouter
->markAsDirty();
282 if (m_headerWidget
->isVisible()) {
283 m_headerWidget
->setColumns(roles
);
286 if (m_itemSize
.isEmpty()) {
287 updatePreferredColumnWidths();
288 if (!m_headerWidget
->automaticColumnResizing()) {
289 applyColumnWidthsFromHeader();
293 doLayout(NoAnimation
);
295 onVisibleRolesChanged(roles
, previousRoles
);
298 QList
<QByteArray
> KItemListView::visibleRoles() const
300 return m_visibleRoles
;
303 void KItemListView::setAutoScroll(bool enabled
)
305 if (enabled
&& !m_autoScrollTimer
) {
306 m_autoScrollTimer
= new QTimer(this);
307 m_autoScrollTimer
->setSingleShot(true);
308 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
309 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
310 } else if (!enabled
&& m_autoScrollTimer
) {
311 delete m_autoScrollTimer
;
312 m_autoScrollTimer
= 0;
316 bool KItemListView::autoScroll() const
318 return m_autoScrollTimer
!= 0;
321 void KItemListView::setEnabledSelectionToggles(bool enabled
)
323 if (m_enabledSelectionToggles
!= enabled
) {
324 m_enabledSelectionToggles
= enabled
;
326 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
327 while (it
.hasNext()) {
329 it
.value()->setEnabledSelectionToggle(enabled
);
334 bool KItemListView::enabledSelectionToggles() const
336 return m_enabledSelectionToggles
;
339 KItemListController
* KItemListView::controller() const
344 KItemModelBase
* KItemListView::model() const
349 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
351 m_widgetCreator
= widgetCreator
;
354 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
356 return m_widgetCreator
;
359 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
361 m_groupHeaderCreator
= groupHeaderCreator
;
364 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
366 return m_groupHeaderCreator
;
369 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
371 const KItemListStyleOption previousOption
= m_styleOption
;
372 m_styleOption
= option
;
375 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
376 if (margin
!= m_layouter
->itemMargin()) {
377 // Skip animations when the number of rows or columns
378 // are changed in the grid layout. Although the animation
379 // engine can handle this usecase, it looks obtrusive.
380 animate
= !changesItemGridLayout(m_layouter
->size(),
381 m_layouter
->itemSize(),
383 m_layouter
->setItemMargin(margin
);
387 updateGroupHeaderHeight();
390 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
391 while (it
.hasNext()) {
393 it
.value()->setStyleOption(option
);
396 m_sizeHintResolver
->clearCache();
397 doLayout(animate
? Animation
: NoAnimation
);
399 onStyleOptionChanged(option
, previousOption
);
402 const KItemListStyleOption
& KItemListView::styleOption() const
404 return m_styleOption
;
407 void KItemListView::setGeometry(const QRectF
& rect
)
409 QGraphicsWidget::setGeometry(rect
);
415 const QSizeF newSize
= rect
.size();
416 if (m_itemSize
.isEmpty()) {
417 if (m_headerWidget
->automaticColumnResizing()) {
418 resizeColumnWidths();
420 const qreal requiredWidth
= columnWidthsSum();
421 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
422 m_itemSize
.height());
423 m_layouter
->setItemSize(dynamicItemSize
);
424 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
427 // Triggering a synchronous layout is fine from a performance point of view,
428 // as with dynamic item sizes no moving animation must be done.
429 m_layouter
->setSize(newSize
);
430 doLayout(NoAnimation
);
432 const bool animate
= !changesItemGridLayout(newSize
,
433 m_layouter
->itemSize(),
434 m_layouter
->itemMargin());
435 m_layouter
->setSize(newSize
);
438 // Trigger an asynchronous relayout with m_layoutTimer to prevent
439 // performance bottlenecks. If the timer is exceeded, an animated layout
440 // will be triggered.
441 if (!m_layoutTimer
->isActive()) {
442 m_layoutTimer
->start();
445 m_layoutTimer
->stop();
446 doLayout(NoAnimation
);
451 int KItemListView::itemAt(const QPointF
& pos
) const
453 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
454 while (it
.hasNext()) {
457 const KItemListWidget
* widget
= it
.value();
458 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
459 if (widget
->contains(mappedPos
)) {
467 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
469 if (!m_enabledSelectionToggles
) {
473 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
475 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
476 if (!selectionToggleRect
.isEmpty()) {
477 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
478 return selectionToggleRect
.contains(mappedPos
);
484 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
486 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
488 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
489 if (!expansionToggleRect
.isEmpty()) {
490 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
491 return expansionToggleRect
.contains(mappedPos
);
497 int KItemListView::firstVisibleIndex() const
499 return m_layouter
->firstVisibleIndex();
502 int KItemListView::lastVisibleIndex() const
504 return m_layouter
->lastVisibleIndex();
507 QSizeF
KItemListView::itemSizeHint(int index
) const
513 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
515 Q_UNUSED(itemRanges
);
516 return QHash
<QByteArray
, qreal
>();
519 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
521 if (m_supportsItemExpanding
!= supportsExpanding
) {
522 m_supportsItemExpanding
= supportsExpanding
;
523 updateSiblingsInformation();
524 onSupportsItemExpandingChanged(supportsExpanding
);
528 bool KItemListView::supportsItemExpanding() const
530 return m_supportsItemExpanding
;
533 QRectF
KItemListView::itemRect(int index
) const
535 return m_layouter
->itemRect(index
);
538 QRectF
KItemListView::itemContextRect(int index
) const
542 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
544 contextRect
= widget
->iconRect() | widget
->textRect();
545 contextRect
.translate(itemRect(index
).topLeft());
551 void KItemListView::scrollToItem(int index
)
553 QRectF viewGeometry
= geometry();
554 if (m_headerWidget
->isVisible()) {
555 const qreal headerHeight
= m_headerWidget
->size().height();
556 viewGeometry
.adjust(0, headerHeight
, 0, 0);
558 const QRectF currentRect
= itemRect(index
);
560 if (!viewGeometry
.contains(currentRect
)) {
561 qreal newOffset
= scrollOffset();
562 if (scrollOrientation() == Qt::Vertical
) {
563 if (currentRect
.top() < viewGeometry
.top()) {
564 newOffset
+= currentRect
.top() - viewGeometry
.top();
565 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
566 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
569 if (currentRect
.left() < viewGeometry
.left()) {
570 newOffset
+= currentRect
.left() - viewGeometry
.left();
571 } else if (currentRect
.right() > viewGeometry
.right()) {
572 newOffset
+= currentRect
.right() - viewGeometry
.right();
576 if (newOffset
!= scrollOffset()) {
577 emit
scrollTo(newOffset
);
582 void KItemListView::beginTransaction()
584 ++m_activeTransactions
;
585 if (m_activeTransactions
== 1) {
586 onTransactionBegin();
590 void KItemListView::endTransaction()
592 --m_activeTransactions
;
593 if (m_activeTransactions
< 0) {
594 m_activeTransactions
= 0;
595 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
598 if (m_activeTransactions
== 0) {
600 doLayout(m_endTransactionAnimationHint
);
601 m_endTransactionAnimationHint
= Animation
;
605 bool KItemListView::isTransactionActive() const
607 return m_activeTransactions
> 0;
610 void KItemListView::setHeaderVisible(bool visible
)
612 if (visible
&& !m_headerWidget
->isVisible()) {
613 m_headerWidget
->setPos(0, 0);
614 m_headerWidget
->setModel(m_model
);
615 m_headerWidget
->setColumns(m_visibleRoles
);
616 m_headerWidget
->setZValue(1);
618 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
619 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
620 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
621 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
622 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
623 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
624 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
625 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
627 m_layouter
->setHeaderHeight(m_headerWidget
->size().height());
628 m_headerWidget
->setVisible(true);
629 } else if (!visible
&& m_headerWidget
->isVisible()) {
630 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
631 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
632 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
633 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
634 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
635 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
636 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
637 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
639 m_layouter
->setHeaderHeight(0);
640 m_headerWidget
->setVisible(false);
644 bool KItemListView::isHeaderVisible() const
646 return m_headerWidget
->isVisible();
649 KItemListHeader
* KItemListView::header() const
654 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
660 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
662 QGraphicsWidget::paint(painter
, option
, widget
);
664 if (m_rubberBand
->isActive()) {
665 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
666 m_rubberBand
->endPosition()).normalized();
668 const QPointF topLeft
= rubberBandRect
.topLeft();
669 if (scrollOrientation() == Qt::Vertical
) {
670 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
672 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
675 QStyleOptionRubberBand opt
;
676 opt
.initFrom(widget
);
677 opt
.shape
= QRubberBand::Rectangle
;
679 opt
.rect
= rubberBandRect
.toRect();
680 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
684 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
689 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
691 Q_UNUSED(changedRoles
);
695 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
701 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
707 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
713 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
719 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
725 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
731 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
737 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
739 Q_UNUSED(supportsExpanding
);
742 void KItemListView::onTransactionBegin()
746 void KItemListView::onTransactionEnd()
750 bool KItemListView::event(QEvent
* event
)
752 // Forward all events to the controller and handle them there
753 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
757 return QGraphicsWidget::event(event
);
760 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
762 m_mousePos
= transform().map(event
->pos());
766 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
768 QGraphicsWidget::mouseMoveEvent(event
);
770 m_mousePos
= transform().map(event
->pos());
771 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
772 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
776 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
778 event
->setAccepted(true);
782 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
784 QGraphicsWidget::dragMoveEvent(event
);
786 m_mousePos
= transform().map(event
->pos());
787 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
788 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
792 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
794 QGraphicsWidget::dragLeaveEvent(event
);
795 setAutoScroll(false);
798 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
800 QGraphicsWidget::dropEvent(event
);
801 setAutoScroll(false);
804 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
806 return m_visibleItems
.values();
809 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
811 if (m_itemSize
.isEmpty()) {
812 updatePreferredColumnWidths(itemRanges
);
815 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
816 if (hasMultipleRanges
) {
820 m_layouter
->markAsDirty();
822 int previouslyInsertedCount
= 0;
823 foreach (const KItemRange
& range
, itemRanges
) {
824 // range.index is related to the model before anything has been inserted.
825 // As in each loop the current item-range gets inserted the index must
826 // be increased by the already previously inserted items.
827 const int index
= range
.index
+ previouslyInsertedCount
;
828 const int count
= range
.count
;
829 if (index
< 0 || count
<= 0) {
830 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
833 previouslyInsertedCount
+= count
;
835 m_sizeHintResolver
->itemsInserted(index
, count
);
837 // Determine which visible items must be moved
838 QList
<int> itemsToMove
;
839 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
840 while (it
.hasNext()) {
842 const int visibleItemIndex
= it
.key();
843 if (visibleItemIndex
>= index
) {
844 itemsToMove
.append(visibleItemIndex
);
848 // Update the indexes of all KItemListWidget instances that are located
849 // after the inserted items. It is important to adjust the indexes in the order
850 // from the highest index to the lowest index to prevent overlaps when setting the new index.
852 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
853 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
855 const int newIndex
= widget
->index() + count
;
856 if (hasMultipleRanges
) {
857 setWidgetIndex(widget
, newIndex
);
859 // Try to animate the moving of the item
860 moveWidgetToIndex(widget
, newIndex
);
864 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
865 // Check whether a scrollbar is required to show the inserted items. In this case
866 // the size of the layouter will be decreased before calling doLayout(): This prevents
867 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
868 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
869 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
870 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
871 if (decreaseLayouterSize
) {
872 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
873 QSizeF layouterSize
= m_layouter
->size();
874 if (verticalScrollOrientation
) {
875 layouterSize
.rwidth() -= scrollBarExtent
;
877 layouterSize
.rheight() -= scrollBarExtent
;
879 m_layouter
->setSize(layouterSize
);
883 if (!hasMultipleRanges
) {
884 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
885 updateSiblingsInformation();
890 m_controller
->selectionManager()->itemsInserted(itemRanges
);
893 if (hasMultipleRanges
) {
895 // Important: Don't read any m_layouter-property inside the for-loop in case if
896 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
897 // updated in each loop-cycle and has only a consistent state after the loop.
898 Q_ASSERT(m_layouter
->isDirty());
900 m_endTransactionAnimationHint
= NoAnimation
;
902 updateSiblingsInformation();
905 if (useAlternateBackgrounds()) {
906 updateAlternateBackgrounds();
910 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
912 if (m_itemSize
.isEmpty()) {
913 updatePreferredColumnWidths();
916 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
917 if (hasMultipleRanges
) {
921 m_layouter
->markAsDirty();
923 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
924 const KItemRange
& range
= itemRanges
.at(i
);
925 const int index
= range
.index
;
926 const int count
= range
.count
;
927 if (index
< 0 || count
<= 0) {
928 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
932 m_sizeHintResolver
->itemsRemoved(index
, count
);
934 const int firstRemovedIndex
= index
;
935 const int lastRemovedIndex
= index
+ count
- 1;
936 const int lastIndex
= m_model
->count() + count
- 1;
938 // Remove all KItemListWidget instances that got deleted
939 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
940 KItemListWidget
* widget
= m_visibleItems
.value(i
);
945 m_animation
->stop(widget
);
946 // Stopping the animation might lead to recycling the widget if
947 // it is invisible (see slotAnimationFinished()).
948 // Check again whether it is still visible:
949 if (!m_visibleItems
.contains(i
)) {
953 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
954 // Remove the widget without animation
955 recycleWidget(widget
);
957 // Animate the removing of the items. Special case: When removing an item there
958 // is no valid model index available anymore. For the
959 // remove-animation the item gets removed from m_visibleItems but the widget
960 // will stay alive until the animation has been finished and will
961 // be recycled (deleted) in KItemListView::slotAnimationFinished().
962 m_visibleItems
.remove(i
);
963 widget
->setIndex(-1);
964 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
968 // Update the indexes of all KItemListWidget instances that are located
969 // after the deleted items
970 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
971 KItemListWidget
* widget
= m_visibleItems
.value(i
);
973 const int newIndex
= i
- count
;
974 if (hasMultipleRanges
) {
975 setWidgetIndex(widget
, newIndex
);
977 // Try to animate the moving of the item
978 moveWidgetToIndex(widget
, newIndex
);
983 if (!hasMultipleRanges
) {
984 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
985 // assumes an updated geometry. If items are removed during an active transaction,
986 // the transaction will be temporary deactivated so that doLayout() triggers a
987 // geometry update if necessary.
988 const int activeTransactions
= m_activeTransactions
;
989 m_activeTransactions
= 0;
990 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
991 m_activeTransactions
= activeTransactions
;
992 updateSiblingsInformation();
997 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1000 if (hasMultipleRanges
) {
1002 // Important: Don't read any m_layouter-property inside the for-loop in case if
1003 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1004 // updated in each loop-cycle and has only a consistent state after the loop.
1005 Q_ASSERT(m_layouter
->isDirty());
1007 m_endTransactionAnimationHint
= NoAnimation
;
1009 updateSiblingsInformation();
1012 if (useAlternateBackgrounds()) {
1013 updateAlternateBackgrounds();
1017 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1019 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1020 m_layouter
->markAsDirty();
1023 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1026 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1027 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1029 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1030 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1032 updateWidgetProperties(widget
, index
);
1033 initializeItemListWidget(widget
);
1037 doLayout(NoAnimation
);
1038 updateSiblingsInformation();
1041 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1042 const QSet
<QByteArray
>& roles
)
1044 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1045 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1046 updatePreferredColumnWidths(itemRanges
);
1049 foreach (const KItemRange
& itemRange
, itemRanges
) {
1050 const int index
= itemRange
.index
;
1051 const int count
= itemRange
.count
;
1053 if (updateSizeHints
) {
1054 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1055 m_layouter
->markAsDirty();
1057 if (!m_layoutTimer
->isActive()) {
1058 m_layoutTimer
->start();
1062 // Apply the changed roles to the visible item-widgets
1063 const int lastIndex
= index
+ count
- 1;
1064 for (int i
= index
; i
<= lastIndex
; ++i
) {
1065 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1067 widget
->setData(m_model
->data(i
), roles
);
1071 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1072 // The sort-role has been changed which might result
1073 // in modified group headers
1074 updateVisibleGroupHeaders();
1075 doLayout(NoAnimation
);
1080 void KItemListView::slotGroupedSortingChanged(bool current
)
1082 m_grouped
= current
;
1083 m_layouter
->markAsDirty();
1086 updateGroupHeaderHeight();
1088 // Clear all visible headers
1089 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1090 while (it
.hasNext()) {
1092 recycleGroupHeaderForWidget(it
.key());
1094 Q_ASSERT(m_visibleGroups
.isEmpty());
1097 if (useAlternateBackgrounds()) {
1098 // Changing the group mode requires to update the alternate backgrounds
1099 // as with the enabled group mode the altering is done on base of the first
1101 updateAlternateBackgrounds();
1103 updateSiblingsInformation();
1104 doLayout(NoAnimation
);
1107 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1112 updateVisibleGroupHeaders();
1113 doLayout(NoAnimation
);
1117 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1122 updateVisibleGroupHeaders();
1123 doLayout(NoAnimation
);
1127 void KItemListView::slotCurrentChanged(int current
, int previous
)
1131 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1132 if (previousWidget
) {
1133 previousWidget
->setCurrent(false);
1136 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1137 if (currentWidget
) {
1138 currentWidget
->setCurrent(true);
1142 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1146 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1147 while (it
.hasNext()) {
1149 const int index
= it
.key();
1150 KItemListWidget
* widget
= it
.value();
1151 widget
->setSelected(current
.contains(index
));
1155 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1156 KItemListViewAnimation::AnimationType type
)
1158 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1159 Q_ASSERT(itemListWidget
);
1162 case KItemListViewAnimation::DeleteAnimation
: {
1163 // As we recycle the widget in this case it is important to assure that no
1164 // other animation has been started. This is a convention in KItemListView and
1165 // not a requirement defined by KItemListViewAnimation.
1166 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1168 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1169 // by m_visibleWidgets and must be deleted manually after the animation has
1171 recycleGroupHeaderForWidget(itemListWidget
);
1172 m_widgetCreator
->recycle(itemListWidget
);
1176 case KItemListViewAnimation::CreateAnimation
:
1177 case KItemListViewAnimation::MovingAnimation
:
1178 case KItemListViewAnimation::ResizeAnimation
: {
1179 const int index
= itemListWidget
->index();
1180 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1181 (index
> m_layouter
->lastVisibleIndex());
1182 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1183 recycleWidget(itemListWidget
);
1192 void KItemListView::slotLayoutTimerFinished()
1194 m_layouter
->setSize(geometry().size());
1195 doLayout(Animation
);
1198 void KItemListView::slotRubberBandPosChanged()
1203 void KItemListView::slotRubberBandActivationChanged(bool active
)
1206 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1207 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1208 m_skipAutoScrollForRubberBand
= true;
1210 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1211 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1212 m_skipAutoScrollForRubberBand
= false;
1218 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1220 qreal previousWidth
)
1223 Q_UNUSED(currentWidth
);
1224 Q_UNUSED(previousWidth
);
1226 m_headerWidget
->setAutomaticColumnResizing(false);
1227 applyColumnWidthsFromHeader();
1230 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1234 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1236 const QList
<QByteArray
> previous
= m_visibleRoles
;
1238 QList
<QByteArray
> current
= m_visibleRoles
;
1239 current
.removeAt(previousIndex
);
1240 current
.insert(currentIndex
, role
);
1242 setVisibleRoles(current
);
1244 emit
visibleRolesChanged(current
, previous
);
1247 void KItemListView::triggerAutoScrolling()
1249 if (!m_autoScrollTimer
) {
1254 int visibleSize
= 0;
1255 if (scrollOrientation() == Qt::Vertical
) {
1256 pos
= m_mousePos
.y();
1257 visibleSize
= size().height();
1259 pos
= m_mousePos
.x();
1260 visibleSize
= size().width();
1263 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1264 m_autoScrollIncrement
= 0;
1267 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1268 if (m_autoScrollIncrement
== 0) {
1269 // The mouse position is not above an autoscroll margin (the autoscroll timer
1270 // will be restarted in mouseMoveEvent())
1271 m_autoScrollTimer
->stop();
1275 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1276 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1277 // if the direction of the rubberband is similar to the autoscroll direction. This
1278 // prevents that starting to create a rubberband within the autoscroll margins starts
1279 // an autoscrolling.
1281 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1282 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1283 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1284 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1285 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1286 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1287 // been moved up although the autoscroll direction might be down)
1288 m_autoScrollTimer
->stop();
1293 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1294 // the autoscrolling may not get skipped anymore until a new rubberband is created
1295 m_skipAutoScrollForRubberBand
= false;
1297 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1298 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1299 setScrollOffset(newScrollOffset
);
1301 // Trigger the autoscroll timer which will periodically call
1302 // triggerAutoScrolling()
1303 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1306 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1308 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1310 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1311 Q_ASSERT(groupHeader
);
1312 updateGroupHeaderLayout(widget
);
1315 void KItemListView::setController(KItemListController
* controller
)
1317 if (m_controller
!= controller
) {
1318 KItemListController
* previous
= m_controller
;
1320 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1321 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1322 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1325 m_controller
= controller
;
1328 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1329 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1330 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1333 onControllerChanged(controller
, previous
);
1337 void KItemListView::setModel(KItemModelBase
* model
)
1339 if (m_model
== model
) {
1343 KItemModelBase
* previous
= m_model
;
1346 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1347 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1348 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1349 this, SLOT(slotItemsInserted(KItemRangeList
)));
1350 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1351 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1352 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1353 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1354 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1355 this, SLOT(slotGroupedSortingChanged(bool)));
1356 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1357 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1358 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1359 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1363 m_layouter
->setModel(model
);
1364 m_grouped
= model
->groupedSorting();
1367 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1368 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1369 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1370 this, SLOT(slotItemsInserted(KItemRangeList
)));
1371 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1372 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1373 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1374 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1375 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1376 this, SLOT(slotGroupedSortingChanged(bool)));
1377 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1378 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1379 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1380 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1383 onModelChanged(model
, previous
);
1386 KItemListRubberBand
* KItemListView::rubberBand() const
1388 return m_rubberBand
;
1391 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1393 if (m_layoutTimer
->isActive()) {
1394 m_layoutTimer
->stop();
1397 if (m_activeTransactions
> 0) {
1398 if (hint
== NoAnimation
) {
1399 // As soon as at least one property change should be done without animation,
1400 // the whole transaction will be marked as not animated.
1401 m_endTransactionAnimationHint
= NoAnimation
;
1406 if (!m_model
|| m_model
->count() < 0) {
1410 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1411 if (firstVisibleIndex
< 0) {
1412 emitOffsetChanges();
1416 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1417 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1418 // is still shown if the maximum offset got decreased.
1419 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1420 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1421 if (scrollOffset() > maxOffsetToShowFullRange
) {
1422 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1423 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1426 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1428 int firstSibblingIndex
= -1;
1429 int lastSibblingIndex
= -1;
1430 const bool supportsExpanding
= supportsItemExpanding();
1432 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1434 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1435 // instances from invisible items are reused. If no reusable items are
1436 // found then new KItemListWidget instances get created.
1437 const bool animate
= (hint
== Animation
);
1438 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1439 bool applyNewPos
= true;
1440 bool wasHidden
= false;
1442 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1443 const QPointF newPos
= itemBounds
.topLeft();
1444 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1447 if (!reusableItems
.isEmpty()) {
1448 // Reuse a KItemListWidget instance from an invisible item
1449 const int oldIndex
= reusableItems
.takeLast();
1450 widget
= m_visibleItems
.value(oldIndex
);
1451 setWidgetIndex(widget
, i
);
1452 updateWidgetProperties(widget
, i
);
1453 initializeItemListWidget(widget
);
1455 // No reusable KItemListWidget instance is available, create a new one
1456 widget
= createWidget(i
);
1458 widget
->resize(itemBounds
.size());
1460 if (animate
&& changedCount
< 0) {
1461 // Items have been deleted, move the created item to the
1462 // imaginary old position. They will get animated to the new position
1464 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1465 if (itemRect
.isEmpty()) {
1466 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1467 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1468 widget
->setPos(invisibleOldPos
);
1470 widget
->setPos(itemRect
.topLeft());
1472 applyNewPos
= false;
1475 if (supportsExpanding
&& changedCount
== 0) {
1476 if (firstSibblingIndex
< 0) {
1477 firstSibblingIndex
= i
;
1479 lastSibblingIndex
= i
;
1484 const bool itemsRemoved
= (changedCount
< 0);
1485 const bool itemsInserted
= (changedCount
> 0);
1486 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1487 // The item is located after the removed items. Animate the moving of the position.
1488 applyNewPos
= !moveWidget(widget
, newPos
);
1489 } else if (itemsInserted
&& i
>= changedIndex
) {
1490 // The item is located after the first inserted item
1491 if (i
<= changedIndex
+ changedCount
- 1) {
1492 // The item is an inserted item. Animate the appearing of the item.
1493 // For performance reasons no animation is done when changedCount is equal
1494 // to all available items.
1495 if (changedCount
< m_model
->count()) {
1496 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1498 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1499 // The item was already there before, so animate the moving of the position.
1500 // No moving animation is done if the item is animated by a create animation: This
1501 // prevents a "move animation mess" when inserting several ranges in parallel.
1502 applyNewPos
= !moveWidget(widget
, newPos
);
1504 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1505 // The size of the view might have been changed. Animate the moving of the position.
1506 applyNewPos
= !moveWidget(widget
, newPos
);
1509 m_animation
->stop(widget
);
1513 widget
->setPos(newPos
);
1516 Q_ASSERT(widget
->index() == i
);
1517 widget
->setVisible(true);
1519 if (widget
->size() != itemBounds
.size()) {
1520 // Resize the widget for the item to the changed size.
1522 // If a dynamic item size is used then no animation is done in the direction
1523 // of the dynamic size.
1524 if (m_itemSize
.width() <= 0) {
1525 // The width is dynamic, apply the new width without animation.
1526 widget
->resize(itemBounds
.width(), widget
->size().height());
1527 } else if (m_itemSize
.height() <= 0) {
1528 // The height is dynamic, apply the new height without animation.
1529 widget
->resize(widget
->size().width(), itemBounds
.height());
1531 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1533 widget
->resize(itemBounds
.size());
1537 // Updating the cell-information must be done as last step: The decision whether the
1538 // moving-animation should be started at all is based on the previous cell-information.
1539 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1540 m_visibleCells
.insert(i
, cell
);
1543 // Delete invisible KItemListWidget instances that have not been reused
1544 foreach (int index
, reusableItems
) {
1545 recycleWidget(m_visibleItems
.value(index
));
1548 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1549 Q_ASSERT(lastSibblingIndex
>= 0);
1550 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1554 // Update the layout of all visible group headers
1555 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1556 while (it
.hasNext()) {
1558 updateGroupHeaderLayout(it
.key());
1562 emitOffsetChanges();
1565 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1566 int lastVisibleIndex
,
1567 LayoutAnimationHint hint
)
1569 // Determine all items that are completely invisible and might be
1570 // reused for items that just got (at least partly) visible. If the
1571 // animation hint is set to 'Animation' items that do e.g. an animated
1572 // moving of their position are not marked as invisible: This assures
1573 // that a scrolling inside the view can be done without breaking an animation.
1577 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1578 while (it
.hasNext()) {
1581 KItemListWidget
* widget
= it
.value();
1582 const int index
= widget
->index();
1583 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1586 if (m_animation
->isStarted(widget
)) {
1587 if (hint
== NoAnimation
) {
1588 // Stopping the animation will call KItemListView::slotAnimationFinished()
1589 // and the widget will be recycled if necessary there.
1590 m_animation
->stop(widget
);
1593 widget
->setVisible(false);
1594 items
.append(index
);
1597 recycleGroupHeaderForWidget(widget
);
1606 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1608 if (widget
->pos() == newPos
) {
1612 bool startMovingAnim
= false;
1614 // When having a grid the moving-animation should only be started, if it is done within
1615 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1616 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1617 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1618 const int index
= widget
->index();
1619 const Cell cell
= m_visibleCells
.value(index
);
1620 if (cell
.column
>= 0 && cell
.row
>= 0) {
1621 if (scrollOrientation() == Qt::Vertical
) {
1622 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1624 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1628 if (startMovingAnim
) {
1629 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1633 m_animation
->stop(widget
);
1634 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1638 void KItemListView::emitOffsetChanges()
1640 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1641 if (m_oldScrollOffset
!= newScrollOffset
) {
1642 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1643 m_oldScrollOffset
= newScrollOffset
;
1646 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1647 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1648 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1649 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1652 const qreal newItemOffset
= m_layouter
->itemOffset();
1653 if (m_oldItemOffset
!= newItemOffset
) {
1654 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1655 m_oldItemOffset
= newItemOffset
;
1658 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1659 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1660 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1661 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1665 KItemListWidget
* KItemListView::createWidget(int index
)
1667 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1668 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1670 m_visibleItems
.insert(index
, widget
);
1671 m_visibleCells
.insert(index
, Cell());
1672 updateWidgetProperties(widget
, index
);
1673 initializeItemListWidget(widget
);
1677 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1680 recycleGroupHeaderForWidget(widget
);
1683 const int index
= widget
->index();
1684 m_visibleItems
.remove(index
);
1685 m_visibleCells
.remove(index
);
1687 m_widgetCreator
->recycle(widget
);
1690 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1692 const int oldIndex
= widget
->index();
1693 m_visibleItems
.remove(oldIndex
);
1694 m_visibleCells
.remove(oldIndex
);
1696 m_visibleItems
.insert(index
, widget
);
1697 m_visibleCells
.insert(index
, Cell());
1699 widget
->setIndex(index
);
1702 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1704 const int oldIndex
= widget
->index();
1705 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1707 setWidgetIndex(widget
, index
);
1709 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1710 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1711 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1712 (!vertical
&& oldCell
.column
== newCell
.column
);
1714 m_visibleCells
.insert(index
, newCell
);
1718 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1721 case LayouterSize
: m_layouter
->setSize(size
); break;
1722 case ItemSize
: m_layouter
->setItemSize(size
); break;
1727 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1729 widget
->setVisibleRoles(m_visibleRoles
);
1730 updateWidgetColumnWidths(widget
);
1731 widget
->setStyleOption(m_styleOption
);
1733 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1734 widget
->setCurrent(index
== selectionManager
->currentItem());
1735 widget
->setSelected(selectionManager
->isSelected(index
));
1736 widget
->setHovered(false);
1737 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1738 widget
->setIndex(index
);
1739 widget
->setData(m_model
->data(index
));
1740 widget
->setSiblingsInformation(QBitArray());
1741 updateAlternateBackgroundForWidget(widget
);
1744 updateGroupHeaderForWidget(widget
);
1748 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1750 Q_ASSERT(m_grouped
);
1752 const int index
= widget
->index();
1753 if (!m_layouter
->isFirstGroupItem(index
)) {
1754 // The widget does not represent the first item of a group
1755 // and hence requires no header
1756 recycleGroupHeaderForWidget(widget
);
1760 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1761 if (groups
.isEmpty()) {
1765 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1767 groupHeader
= m_groupHeaderCreator
->create(this);
1768 groupHeader
->setParentItem(widget
);
1769 m_visibleGroups
.insert(widget
, groupHeader
);
1770 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1772 Q_ASSERT(groupHeader
->parentItem() == widget
);
1774 const int groupIndex
= groupIndexForItem(index
);
1775 Q_ASSERT(groupIndex
>= 0);
1776 groupHeader
->setData(groups
.at(groupIndex
).second
);
1777 groupHeader
->setRole(model()->sortRole());
1778 groupHeader
->setStyleOption(m_styleOption
);
1779 groupHeader
->setScrollOrientation(scrollOrientation());
1780 groupHeader
->setItemIndex(index
);
1782 groupHeader
->show();
1785 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1787 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1788 Q_ASSERT(groupHeader
);
1790 const int index
= widget
->index();
1791 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1792 const QRectF itemRect
= m_layouter
->itemRect(index
);
1794 // The group-header is a child of the itemlist widget. Translate the
1795 // group header position to the relative position.
1796 if (scrollOrientation() == Qt::Vertical
) {
1797 // In the vertical scroll orientation the group header should always span
1798 // the whole width no matter which temporary position the parent widget
1799 // has. In this case the x-position and width will be adjusted manually.
1800 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1801 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1803 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1804 groupHeader
->resize(groupHeaderRect
.size());
1808 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1810 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1812 header
->setParentItem(0);
1813 m_groupHeaderCreator
->recycle(header
);
1814 m_visibleGroups
.remove(widget
);
1815 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1819 void KItemListView::updateVisibleGroupHeaders()
1821 Q_ASSERT(m_grouped
);
1822 m_layouter
->markAsDirty();
1824 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1825 while (it
.hasNext()) {
1827 updateGroupHeaderForWidget(it
.value());
1831 int KItemListView::groupIndexForItem(int index
) const
1833 Q_ASSERT(m_grouped
);
1835 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1836 if (groups
.isEmpty()) {
1841 int max
= groups
.count() - 1;
1844 mid
= (min
+ max
) / 2;
1845 if (index
> groups
[mid
].first
) {
1850 } while (groups
[mid
].first
!= index
&& min
<= max
);
1853 while (groups
[mid
].first
> index
&& mid
> 0) {
1861 void KItemListView::updateAlternateBackgrounds()
1863 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1864 while (it
.hasNext()) {
1866 updateAlternateBackgroundForWidget(it
.value());
1870 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1872 bool enabled
= useAlternateBackgrounds();
1874 const int index
= widget
->index();
1875 enabled
= (index
& 0x1) > 0;
1877 const int groupIndex
= groupIndexForItem(index
);
1878 if (groupIndex
>= 0) {
1879 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1880 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1881 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1882 enabled
= (relativeIndex
& 0x1) > 0;
1886 widget
->setAlternateBackground(enabled
);
1889 bool KItemListView::useAlternateBackgrounds() const
1891 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1894 void KItemListView::applyColumnWidthsFromHeader()
1896 // Apply the new size to the layouter
1897 const qreal requiredWidth
= columnWidthsSum();
1898 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
1899 m_itemSize
.height());
1900 m_layouter
->setItemSize(dynamicItemSize
);
1901 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
1903 // Update the role sizes for all visible widgets
1904 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1905 while (it
.hasNext()) {
1907 updateWidgetColumnWidths(it
.value());
1911 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
1913 foreach (const QByteArray
& role
, m_visibleRoles
) {
1914 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
1918 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
1920 Q_ASSERT(m_itemSize
.isEmpty());
1922 const int itemCount
= m_model
->count();
1923 int rangesItemCount
= 0;
1924 foreach (const KItemRange
& range
, itemRanges
) {
1925 rangesItemCount
+= range
.count
;
1928 if (itemCount
== rangesItemCount
) {
1929 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
1930 foreach (const QByteArray
& role
, m_visibleRoles
) {
1931 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
1934 // Only a sub range of the roles need to be determined.
1935 // The chances are good that the widths of the sub ranges
1936 // already fit into the available widths and hence no
1937 // expensive update might be required.
1938 bool updateRequired
= false;
1940 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
1941 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
1942 while (it
.hasNext()) {
1944 const QByteArray
& role
= it
.key();
1945 const qreal updatedWidth
= it
.value();
1946 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
1947 if (updatedWidth
> currentWidth
) {
1948 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
1949 updateRequired
= true;
1953 if (!updateRequired
) {
1954 // All the updated sizes are smaller than the current sizes and no change
1955 // of the stretched roles-widths is required
1960 if (m_header
->automaticColumnResizing()) {
1961 resizeColumnWidths();
1965 void KItemListView::updatePreferredColumnWidths()
1971 const int itemCount
= m_model
->count();
1972 if (itemCount
> 0) {
1973 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, itemCount
));
1977 void KItemListView::resizeColumnWidths()
1979 Q_ASSERT(m_itemSize
.isEmpty());
1980 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
1982 // Calculate the maximum size of an item by considering the
1983 // visible role sizes and apply them to the layouter. If the
1984 // size does not use the available view-size the size of the
1985 // first role will get stretched.
1987 foreach (const QByteArray
& role
, m_visibleRoles
) {
1988 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
1989 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
1992 const QByteArray firstRole
= m_visibleRoles
.first();
1993 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
1994 QSizeF dynamicItemSize
= m_itemSize
;
1996 qreal requiredWidth
= columnWidthsSum();
1997 const qreal availableWidth
= size().width();
1998 if (requiredWidth
< availableWidth
) {
1999 // Stretch the first column to use the whole remaining width
2000 firstColumnWidth
+= availableWidth
- requiredWidth
;
2001 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2002 } else if (requiredWidth
> availableWidth
) {
2003 // Shrink the first column to be able to show as much other
2004 // columns as possible
2005 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2007 // TODO: A proper calculation of the minimum width depends on the implementation
2008 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2010 const qreal minWidth
= m_styleOption
.iconSize
* 2 + 200;
2011 if (shrinkedFirstColumnWidth
< minWidth
) {
2012 shrinkedFirstColumnWidth
= minWidth
;
2015 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2016 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2019 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2021 m_layouter
->setItemSize(dynamicItemSize
);
2022 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
2024 // Update the role sizes for all visible widgets
2025 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2026 while (it
.hasNext()) {
2028 updateWidgetColumnWidths(it
.value());
2032 qreal
KItemListView::columnWidthsSum() const
2034 qreal widthsSum
= 0;
2035 foreach (const QByteArray
& role
, m_visibleRoles
) {
2036 widthsSum
+= m_headerWidget
->columnWidth(role
);
2041 QRectF
KItemListView::headerBoundaries() const
2043 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2046 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2047 const QSizeF
& newItemSize
,
2048 const QSizeF
& newItemMargin
) const
2050 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2054 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2055 const qreal itemWidth
= m_layouter
->itemSize().width();
2056 if (itemWidth
> 0) {
2057 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2058 newItemSize
.width(),
2059 newItemMargin
.width());
2060 if (m_model
->count() > newColumnCount
) {
2061 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2063 m_layouter
->itemMargin().width());
2064 return oldColumnCount
!= newColumnCount
;
2068 const qreal itemHeight
= m_layouter
->itemSize().height();
2069 if (itemHeight
> 0) {
2070 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2071 newItemSize
.height(),
2072 newItemMargin
.height());
2073 if (m_model
->count() > newRowCount
) {
2074 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2076 m_layouter
->itemMargin().height());
2077 return oldRowCount
!= newRowCount
;
2085 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2087 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2091 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2092 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2093 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2094 // Only animate if up to 2/3 of a row or column are inserted or removed
2095 return changedItemCount
<= maximum
* 2 / 3;
2099 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2101 const QSizeF oldSize
= m_layouter
->size();
2103 m_layouter
->setSize(size
);
2104 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2105 m_layouter
->setSize(oldSize
);
2107 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2108 : maxOffset
> size
.width();
2111 void KItemListView::updateGroupHeaderHeight()
2113 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2114 qreal groupHeaderMargin
= 0;
2116 if (scrollOrientation() == Qt::Horizontal
) {
2117 // The vertical margin above and below the header should be
2118 // equal to the horizontal margin, not the vertical margin
2119 // from m_styleOption.
2120 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2121 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2122 } else if (m_itemSize
.isEmpty()){
2123 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2124 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2126 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2127 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2129 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2130 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2132 updateVisibleGroupHeaders();
2135 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2137 if (!supportsItemExpanding() || !m_model
) {
2141 if (firstIndex
< 0 || lastIndex
< 0) {
2142 firstIndex
= m_layouter
->firstVisibleIndex();
2143 lastIndex
= m_layouter
->lastVisibleIndex();
2145 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2146 lastIndex
>= m_layouter
->firstVisibleIndex());
2147 if (!isRangeVisible
) {
2152 int previousParents
= 0;
2153 QBitArray previousSiblings
;
2155 // The rootIndex describes the first index where the siblings get
2156 // calculated from. For the calculation the upper most parent item
2157 // is required. For performance reasons it is checked first whether
2158 // the visible items before or after the current range already
2159 // contain a siblings information which can be used as base.
2160 int rootIndex
= firstIndex
;
2162 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2164 // There is no visible widget before the range, check whether there
2165 // is one after the range:
2166 widget
= m_visibleItems
.value(lastIndex
+ 1);
2168 // The sibling information of the widget may only be used if
2169 // all items of the range have the same number of parents.
2170 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2171 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2172 if (m_model
->expandedParentsCount(i
) != parents
) {
2181 // Performance optimization: Use the sibling information of the visible
2182 // widget beside the given range.
2183 previousSiblings
= widget
->siblingsInformation();
2184 if (previousSiblings
.isEmpty()) {
2187 previousParents
= previousSiblings
.count() - 1;
2188 previousSiblings
.truncate(previousParents
);
2190 // Potentially slow path: Go back to the upper most parent of firstIndex
2191 // to be able to calculate the initial value for the siblings.
2192 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2197 Q_ASSERT(previousParents
>= 0);
2198 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2199 // Update the parent-siblings in case if the current item represents
2200 // a child or an upper parent.
2201 const int currentParents
= m_model
->expandedParentsCount(i
);
2202 Q_ASSERT(currentParents
>= 0);
2203 if (previousParents
< currentParents
) {
2204 previousParents
= currentParents
;
2205 previousSiblings
.resize(currentParents
);
2206 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2207 } else if (previousParents
> currentParents
) {
2208 previousParents
= currentParents
;
2209 previousSiblings
.truncate(currentParents
);
2212 if (i
>= firstIndex
) {
2213 // The index represents a visible item. Apply the parent-siblings
2214 // and update the sibling of the current item.
2215 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2220 QBitArray siblings
= previousSiblings
;
2221 siblings
.resize(siblings
.count() + 1);
2222 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2224 widget
->setSiblingsInformation(siblings
);
2229 bool KItemListView::hasSiblingSuccessor(int index
) const
2231 bool hasSuccessor
= false;
2232 const int parentsCount
= m_model
->expandedParentsCount(index
);
2233 int successorIndex
= index
+ 1;
2235 // Search the next sibling
2236 const int itemCount
= m_model
->count();
2237 while (successorIndex
< itemCount
) {
2238 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2239 if (currentParentsCount
== parentsCount
) {
2240 hasSuccessor
= true;
2242 } else if (currentParentsCount
< parentsCount
) {
2248 if (m_grouped
&& hasSuccessor
) {
2249 // If the sibling is part of another group, don't mark it as
2250 // successor as the group header is between the sibling connections.
2251 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2252 if (m_layouter
->isFirstGroupItem(i
)) {
2253 hasSuccessor
= false;
2259 return hasSuccessor
;
2262 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2266 const int minSpeed
= 4;
2267 const int maxSpeed
= 128;
2268 const int speedLimiter
= 96;
2269 const int autoScrollBorder
= 64;
2271 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2272 // This assures that the autoscrolling speed grows gradually.
2273 const int incLimiter
= 1;
2275 if (pos
< autoScrollBorder
) {
2276 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2277 inc
= qMax(inc
, -maxSpeed
);
2278 inc
= qMax(inc
, oldInc
- incLimiter
);
2279 } else if (pos
> range
- autoScrollBorder
) {
2280 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2281 inc
= qMin(inc
, maxSpeed
);
2282 inc
= qMin(inc
, oldInc
+ incLimiter
);
2288 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2290 const qreal availableSize
= size
- itemMargin
;
2291 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2297 KItemListCreatorBase::~KItemListCreatorBase()
2299 qDeleteAll(m_recycleableWidgets
);
2300 qDeleteAll(m_createdWidgets
);
2303 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2305 m_createdWidgets
.insert(widget
);
2308 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2310 Q_ASSERT(m_createdWidgets
.contains(widget
));
2311 m_createdWidgets
.remove(widget
);
2313 if (m_recycleableWidgets
.count() < 100) {
2314 m_recycleableWidgets
.append(widget
);
2315 widget
->setVisible(false);
2321 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2323 if (m_recycleableWidgets
.isEmpty()) {
2327 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2328 m_createdWidgets
.insert(widget
);
2332 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2336 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2338 widget
->setParentItem(0);
2339 widget
->setOpacity(1.0);
2340 pushRecycleableWidget(widget
);
2343 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2347 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2349 header
->setOpacity(1.0);
2350 pushRecycleableWidget(header
);
2353 #include "kitemlistview.moc"