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
;
263 onVisibleRolesChanged(roles
, previousRoles
);
265 m_sizeHintResolver
->clearCache();
266 m_layouter
->markAsDirty();
268 if (m_itemSize
.isEmpty()) {
269 m_headerWidget
->setColumns(roles
);
270 updatePreferredColumnWidths();
271 if (!m_headerWidget
->automaticColumnResizing()) {
272 // The column-width of new roles are still 0. Apply the preferred
273 // column-width as default with.
274 foreach (const QByteArray
& role
, m_visibleRoles
) {
275 if (m_headerWidget
->columnWidth(role
) == 0) {
276 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
277 m_headerWidget
->setColumnWidth(role
, width
);
281 applyColumnWidthsFromHeader();
285 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
286 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
287 (roles
.count() <= 1 && previousRoles
.count() > 1));
289 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
290 while (it
.hasNext()) {
292 KItemListWidget
* widget
= it
.value();
293 widget
->setVisibleRoles(roles
);
294 if (alternateBackgroundsChanged
) {
295 updateAlternateBackgroundForWidget(widget
);
299 doLayout(NoAnimation
);
302 QList
<QByteArray
> KItemListView::visibleRoles() const
304 return m_visibleRoles
;
307 void KItemListView::setAutoScroll(bool enabled
)
309 if (enabled
&& !m_autoScrollTimer
) {
310 m_autoScrollTimer
= new QTimer(this);
311 m_autoScrollTimer
->setSingleShot(true);
312 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
313 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
314 } else if (!enabled
&& m_autoScrollTimer
) {
315 delete m_autoScrollTimer
;
316 m_autoScrollTimer
= 0;
320 bool KItemListView::autoScroll() const
322 return m_autoScrollTimer
!= 0;
325 void KItemListView::setEnabledSelectionToggles(bool enabled
)
327 if (m_enabledSelectionToggles
!= enabled
) {
328 m_enabledSelectionToggles
= enabled
;
330 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
331 while (it
.hasNext()) {
333 it
.value()->setEnabledSelectionToggle(enabled
);
338 bool KItemListView::enabledSelectionToggles() const
340 return m_enabledSelectionToggles
;
343 KItemListController
* KItemListView::controller() const
348 KItemModelBase
* KItemListView::model() const
353 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
355 m_widgetCreator
= widgetCreator
;
358 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
360 return m_widgetCreator
;
363 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
365 m_groupHeaderCreator
= groupHeaderCreator
;
368 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
370 return m_groupHeaderCreator
;
373 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
375 const KItemListStyleOption previousOption
= m_styleOption
;
376 m_styleOption
= option
;
379 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
380 if (margin
!= m_layouter
->itemMargin()) {
381 // Skip animations when the number of rows or columns
382 // are changed in the grid layout. Although the animation
383 // engine can handle this usecase, it looks obtrusive.
384 animate
= !changesItemGridLayout(m_layouter
->size(),
385 m_layouter
->itemSize(),
387 m_layouter
->setItemMargin(margin
);
391 updateGroupHeaderHeight();
394 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
395 while (it
.hasNext()) {
397 it
.value()->setStyleOption(option
);
400 m_sizeHintResolver
->clearCache();
401 doLayout(animate
? Animation
: NoAnimation
);
403 onStyleOptionChanged(option
, previousOption
);
406 const KItemListStyleOption
& KItemListView::styleOption() const
408 return m_styleOption
;
411 void KItemListView::setGeometry(const QRectF
& rect
)
413 QGraphicsWidget::setGeometry(rect
);
419 const QSizeF newSize
= rect
.size();
420 if (m_itemSize
.isEmpty()) {
421 if (m_headerWidget
->automaticColumnResizing()) {
422 applyAutomaticColumnWidths();
424 const qreal requiredWidth
= columnWidthsSum();
425 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
426 m_itemSize
.height());
427 m_layouter
->setItemSize(dynamicItemSize
);
428 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
431 // Triggering a synchronous layout is fine from a performance point of view,
432 // as with dynamic item sizes no moving animation must be done.
433 m_layouter
->setSize(newSize
);
434 doLayout(NoAnimation
);
436 const bool animate
= !changesItemGridLayout(newSize
,
437 m_layouter
->itemSize(),
438 m_layouter
->itemMargin());
439 m_layouter
->setSize(newSize
);
442 // Trigger an asynchronous relayout with m_layoutTimer to prevent
443 // performance bottlenecks. If the timer is exceeded, an animated layout
444 // will be triggered.
445 if (!m_layoutTimer
->isActive()) {
446 m_layoutTimer
->start();
449 m_layoutTimer
->stop();
450 doLayout(NoAnimation
);
455 int KItemListView::itemAt(const QPointF
& pos
) const
457 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
458 while (it
.hasNext()) {
461 const KItemListWidget
* widget
= it
.value();
462 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
463 if (widget
->contains(mappedPos
)) {
471 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
473 if (!m_enabledSelectionToggles
) {
477 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
479 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
480 if (!selectionToggleRect
.isEmpty()) {
481 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
482 return selectionToggleRect
.contains(mappedPos
);
488 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
490 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
492 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
493 if (!expansionToggleRect
.isEmpty()) {
494 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
495 return expansionToggleRect
.contains(mappedPos
);
501 int KItemListView::firstVisibleIndex() const
503 return m_layouter
->firstVisibleIndex();
506 int KItemListView::lastVisibleIndex() const
508 return m_layouter
->lastVisibleIndex();
511 QSizeF
KItemListView::itemSizeHint(int index
) const
517 qreal
KItemListView::preferredRoleColumnWidth(const QByteArray
& role
, int index
) const
524 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
526 if (m_supportsItemExpanding
!= supportsExpanding
) {
527 m_supportsItemExpanding
= supportsExpanding
;
528 updateSiblingsInformation();
529 onSupportsItemExpandingChanged(supportsExpanding
);
533 bool KItemListView::supportsItemExpanding() const
535 return m_supportsItemExpanding
;
538 QRectF
KItemListView::itemRect(int index
) const
540 return m_layouter
->itemRect(index
);
543 QRectF
KItemListView::itemContextRect(int index
) const
547 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
549 contextRect
= widget
->iconRect() | widget
->textRect();
550 contextRect
.translate(itemRect(index
).topLeft());
556 void KItemListView::scrollToItem(int index
)
558 QRectF viewGeometry
= geometry();
559 if (m_headerWidget
->isVisible()) {
560 const qreal headerHeight
= m_headerWidget
->size().height();
561 viewGeometry
.adjust(0, headerHeight
, 0, 0);
563 const QRectF currentRect
= itemRect(index
);
565 if (!viewGeometry
.contains(currentRect
)) {
566 qreal newOffset
= scrollOffset();
567 if (scrollOrientation() == Qt::Vertical
) {
568 if (currentRect
.top() < viewGeometry
.top()) {
569 newOffset
+= currentRect
.top() - viewGeometry
.top();
570 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
571 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
574 if (currentRect
.left() < viewGeometry
.left()) {
575 newOffset
+= currentRect
.left() - viewGeometry
.left();
576 } else if (currentRect
.right() > viewGeometry
.right()) {
577 newOffset
+= currentRect
.right() - viewGeometry
.right();
581 if (newOffset
!= scrollOffset()) {
582 emit
scrollTo(newOffset
);
587 void KItemListView::beginTransaction()
589 ++m_activeTransactions
;
590 if (m_activeTransactions
== 1) {
591 onTransactionBegin();
595 void KItemListView::endTransaction()
597 --m_activeTransactions
;
598 if (m_activeTransactions
< 0) {
599 m_activeTransactions
= 0;
600 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
603 if (m_activeTransactions
== 0) {
605 doLayout(m_endTransactionAnimationHint
);
606 m_endTransactionAnimationHint
= Animation
;
610 bool KItemListView::isTransactionActive() const
612 return m_activeTransactions
> 0;
615 void KItemListView::setHeaderVisible(bool visible
)
617 if (visible
&& !m_headerWidget
->isVisible()) {
618 m_headerWidget
->setPos(0, 0);
619 m_headerWidget
->setModel(m_model
);
620 m_headerWidget
->setColumns(m_visibleRoles
);
621 m_headerWidget
->setZValue(1);
623 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
624 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
625 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
626 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
627 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
628 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
629 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
630 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
632 m_layouter
->setHeaderHeight(m_headerWidget
->size().height());
633 m_headerWidget
->setVisible(true);
634 } else if (!visible
&& m_headerWidget
->isVisible()) {
635 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
636 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
637 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
638 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
639 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
640 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
641 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
642 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
644 m_layouter
->setHeaderHeight(0);
645 m_headerWidget
->setVisible(false);
649 bool KItemListView::isHeaderVisible() const
651 return m_headerWidget
->isVisible();
654 KItemListHeader
* KItemListView::header() const
659 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
665 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
667 QGraphicsWidget::paint(painter
, option
, widget
);
669 if (m_rubberBand
->isActive()) {
670 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
671 m_rubberBand
->endPosition()).normalized();
673 const QPointF topLeft
= rubberBandRect
.topLeft();
674 if (scrollOrientation() == Qt::Vertical
) {
675 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
677 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
680 QStyleOptionRubberBand opt
;
681 opt
.initFrom(widget
);
682 opt
.shape
= QRubberBand::Rectangle
;
684 opt
.rect
= rubberBandRect
.toRect();
685 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
689 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
694 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
696 Q_UNUSED(changedRoles
);
700 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
706 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
712 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
718 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
724 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
730 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
736 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
742 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
744 Q_UNUSED(supportsExpanding
);
747 void KItemListView::onTransactionBegin()
751 void KItemListView::onTransactionEnd()
755 bool KItemListView::event(QEvent
* event
)
757 // Forward all events to the controller and handle them there
758 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
762 return QGraphicsWidget::event(event
);
765 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
767 m_mousePos
= transform().map(event
->pos());
771 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
773 QGraphicsWidget::mouseMoveEvent(event
);
775 m_mousePos
= transform().map(event
->pos());
776 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
777 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
781 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
783 event
->setAccepted(true);
787 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
789 QGraphicsWidget::dragMoveEvent(event
);
791 m_mousePos
= transform().map(event
->pos());
792 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
793 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
797 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
799 QGraphicsWidget::dragLeaveEvent(event
);
800 setAutoScroll(false);
803 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
805 QGraphicsWidget::dropEvent(event
);
806 setAutoScroll(false);
809 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
811 return m_visibleItems
.values();
814 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
816 if (m_itemSize
.isEmpty()) {
817 updatePreferredColumnWidths(itemRanges
);
820 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
821 if (hasMultipleRanges
) {
825 m_layouter
->markAsDirty();
827 int previouslyInsertedCount
= 0;
828 foreach (const KItemRange
& range
, itemRanges
) {
829 // range.index is related to the model before anything has been inserted.
830 // As in each loop the current item-range gets inserted the index must
831 // be increased by the already previously inserted items.
832 const int index
= range
.index
+ previouslyInsertedCount
;
833 const int count
= range
.count
;
834 if (index
< 0 || count
<= 0) {
835 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
838 previouslyInsertedCount
+= count
;
840 m_sizeHintResolver
->itemsInserted(index
, count
);
842 // Determine which visible items must be moved
843 QList
<int> itemsToMove
;
844 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
845 while (it
.hasNext()) {
847 const int visibleItemIndex
= it
.key();
848 if (visibleItemIndex
>= index
) {
849 itemsToMove
.append(visibleItemIndex
);
853 // Update the indexes of all KItemListWidget instances that are located
854 // after the inserted items. It is important to adjust the indexes in the order
855 // from the highest index to the lowest index to prevent overlaps when setting the new index.
857 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
858 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
860 const int newIndex
= widget
->index() + count
;
861 if (hasMultipleRanges
) {
862 setWidgetIndex(widget
, newIndex
);
864 // Try to animate the moving of the item
865 moveWidgetToIndex(widget
, newIndex
);
869 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
870 // Check whether a scrollbar is required to show the inserted items. In this case
871 // the size of the layouter will be decreased before calling doLayout(): This prevents
872 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
873 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
874 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
875 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
876 if (decreaseLayouterSize
) {
877 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
878 QSizeF layouterSize
= m_layouter
->size();
879 if (verticalScrollOrientation
) {
880 layouterSize
.rwidth() -= scrollBarExtent
;
882 layouterSize
.rheight() -= scrollBarExtent
;
884 m_layouter
->setSize(layouterSize
);
888 if (!hasMultipleRanges
) {
889 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
890 updateSiblingsInformation();
895 m_controller
->selectionManager()->itemsInserted(itemRanges
);
898 if (hasMultipleRanges
) {
900 // Important: Don't read any m_layouter-property inside the for-loop in case if
901 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
902 // updated in each loop-cycle and has only a consistent state after the loop.
903 Q_ASSERT(m_layouter
->isDirty());
905 m_endTransactionAnimationHint
= NoAnimation
;
907 updateSiblingsInformation();
910 if (useAlternateBackgrounds()) {
911 updateAlternateBackgrounds();
915 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
917 if (m_itemSize
.isEmpty()) {
918 // Don't pass the item-range: The preferred column-widths of
919 // all items must be adjusted when removing items.
920 updatePreferredColumnWidths();
923 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
924 if (hasMultipleRanges
) {
928 m_layouter
->markAsDirty();
930 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
931 const KItemRange
& range
= itemRanges
.at(i
);
932 const int index
= range
.index
;
933 const int count
= range
.count
;
934 if (index
< 0 || count
<= 0) {
935 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
939 m_sizeHintResolver
->itemsRemoved(index
, count
);
941 const int firstRemovedIndex
= index
;
942 const int lastRemovedIndex
= index
+ count
- 1;
943 const int lastIndex
= m_model
->count() + count
- 1;
945 // Remove all KItemListWidget instances that got deleted
946 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
947 KItemListWidget
* widget
= m_visibleItems
.value(i
);
952 m_animation
->stop(widget
);
953 // Stopping the animation might lead to recycling the widget if
954 // it is invisible (see slotAnimationFinished()).
955 // Check again whether it is still visible:
956 if (!m_visibleItems
.contains(i
)) {
960 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
961 // Remove the widget without animation
962 recycleWidget(widget
);
964 // Animate the removing of the items. Special case: When removing an item there
965 // is no valid model index available anymore. For the
966 // remove-animation the item gets removed from m_visibleItems but the widget
967 // will stay alive until the animation has been finished and will
968 // be recycled (deleted) in KItemListView::slotAnimationFinished().
969 m_visibleItems
.remove(i
);
970 widget
->setIndex(-1);
971 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
975 // Update the indexes of all KItemListWidget instances that are located
976 // after the deleted items
977 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
978 KItemListWidget
* widget
= m_visibleItems
.value(i
);
980 const int newIndex
= i
- count
;
981 if (hasMultipleRanges
) {
982 setWidgetIndex(widget
, newIndex
);
984 // Try to animate the moving of the item
985 moveWidgetToIndex(widget
, newIndex
);
990 if (!hasMultipleRanges
) {
991 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
992 // assumes an updated geometry. If items are removed during an active transaction,
993 // the transaction will be temporary deactivated so that doLayout() triggers a
994 // geometry update if necessary.
995 const int activeTransactions
= m_activeTransactions
;
996 m_activeTransactions
= 0;
997 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
998 m_activeTransactions
= activeTransactions
;
999 updateSiblingsInformation();
1004 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1007 if (hasMultipleRanges
) {
1009 // Important: Don't read any m_layouter-property inside the for-loop in case if
1010 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1011 // updated in each loop-cycle and has only a consistent state after the loop.
1012 Q_ASSERT(m_layouter
->isDirty());
1014 m_endTransactionAnimationHint
= NoAnimation
;
1016 updateSiblingsInformation();
1019 if (useAlternateBackgrounds()) {
1020 updateAlternateBackgrounds();
1024 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1026 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1027 m_layouter
->markAsDirty();
1030 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1033 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1034 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1036 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1037 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1039 updateWidgetProperties(widget
, index
);
1040 initializeItemListWidget(widget
);
1044 doLayout(NoAnimation
);
1045 updateSiblingsInformation();
1048 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1049 const QSet
<QByteArray
>& roles
)
1051 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1052 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1053 updatePreferredColumnWidths(itemRanges
);
1056 foreach (const KItemRange
& itemRange
, itemRanges
) {
1057 const int index
= itemRange
.index
;
1058 const int count
= itemRange
.count
;
1060 if (updateSizeHints
) {
1061 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1062 m_layouter
->markAsDirty();
1064 if (!m_layoutTimer
->isActive()) {
1065 m_layoutTimer
->start();
1069 // Apply the changed roles to the visible item-widgets
1070 const int lastIndex
= index
+ count
- 1;
1071 for (int i
= index
; i
<= lastIndex
; ++i
) {
1072 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1074 widget
->setData(m_model
->data(i
), roles
);
1078 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1079 // The sort-role has been changed which might result
1080 // in modified group headers
1081 updateVisibleGroupHeaders();
1082 doLayout(NoAnimation
);
1087 void KItemListView::slotGroupedSortingChanged(bool current
)
1089 m_grouped
= current
;
1090 m_layouter
->markAsDirty();
1093 updateGroupHeaderHeight();
1095 // Clear all visible headers
1096 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1097 while (it
.hasNext()) {
1099 recycleGroupHeaderForWidget(it
.key());
1101 Q_ASSERT(m_visibleGroups
.isEmpty());
1104 if (useAlternateBackgrounds()) {
1105 // Changing the group mode requires to update the alternate backgrounds
1106 // as with the enabled group mode the altering is done on base of the first
1108 updateAlternateBackgrounds();
1110 updateSiblingsInformation();
1111 doLayout(NoAnimation
);
1114 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1119 updateVisibleGroupHeaders();
1120 doLayout(NoAnimation
);
1124 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1129 updateVisibleGroupHeaders();
1130 doLayout(NoAnimation
);
1134 void KItemListView::slotCurrentChanged(int current
, int previous
)
1138 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1139 if (previousWidget
) {
1140 previousWidget
->setCurrent(false);
1143 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1144 if (currentWidget
) {
1145 currentWidget
->setCurrent(true);
1149 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1153 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1154 while (it
.hasNext()) {
1156 const int index
= it
.key();
1157 KItemListWidget
* widget
= it
.value();
1158 widget
->setSelected(current
.contains(index
));
1162 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1163 KItemListViewAnimation::AnimationType type
)
1165 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1166 Q_ASSERT(itemListWidget
);
1169 case KItemListViewAnimation::DeleteAnimation
: {
1170 // As we recycle the widget in this case it is important to assure that no
1171 // other animation has been started. This is a convention in KItemListView and
1172 // not a requirement defined by KItemListViewAnimation.
1173 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1175 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1176 // by m_visibleWidgets and must be deleted manually after the animation has
1178 recycleGroupHeaderForWidget(itemListWidget
);
1179 m_widgetCreator
->recycle(itemListWidget
);
1183 case KItemListViewAnimation::CreateAnimation
:
1184 case KItemListViewAnimation::MovingAnimation
:
1185 case KItemListViewAnimation::ResizeAnimation
: {
1186 const int index
= itemListWidget
->index();
1187 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1188 (index
> m_layouter
->lastVisibleIndex());
1189 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1190 recycleWidget(itemListWidget
);
1199 void KItemListView::slotLayoutTimerFinished()
1201 m_layouter
->setSize(geometry().size());
1202 doLayout(Animation
);
1205 void KItemListView::slotRubberBandPosChanged()
1210 void KItemListView::slotRubberBandActivationChanged(bool active
)
1213 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1214 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1215 m_skipAutoScrollForRubberBand
= true;
1217 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1218 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1219 m_skipAutoScrollForRubberBand
= false;
1225 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1227 qreal previousWidth
)
1230 Q_UNUSED(currentWidth
);
1231 Q_UNUSED(previousWidth
);
1233 m_headerWidget
->setAutomaticColumnResizing(false);
1234 applyColumnWidthsFromHeader();
1235 doLayout(NoAnimation
);
1238 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1242 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1244 const QList
<QByteArray
> previous
= m_visibleRoles
;
1246 QList
<QByteArray
> current
= m_visibleRoles
;
1247 current
.removeAt(previousIndex
);
1248 current
.insert(currentIndex
, role
);
1250 setVisibleRoles(current
);
1252 emit
visibleRolesChanged(current
, previous
);
1255 void KItemListView::triggerAutoScrolling()
1257 if (!m_autoScrollTimer
) {
1262 int visibleSize
= 0;
1263 if (scrollOrientation() == Qt::Vertical
) {
1264 pos
= m_mousePos
.y();
1265 visibleSize
= size().height();
1267 pos
= m_mousePos
.x();
1268 visibleSize
= size().width();
1271 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1272 m_autoScrollIncrement
= 0;
1275 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1276 if (m_autoScrollIncrement
== 0) {
1277 // The mouse position is not above an autoscroll margin (the autoscroll timer
1278 // will be restarted in mouseMoveEvent())
1279 m_autoScrollTimer
->stop();
1283 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1284 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1285 // if the direction of the rubberband is similar to the autoscroll direction. This
1286 // prevents that starting to create a rubberband within the autoscroll margins starts
1287 // an autoscrolling.
1289 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1290 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1291 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1292 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1293 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1294 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1295 // been moved up although the autoscroll direction might be down)
1296 m_autoScrollTimer
->stop();
1301 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1302 // the autoscrolling may not get skipped anymore until a new rubberband is created
1303 m_skipAutoScrollForRubberBand
= false;
1305 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1306 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1307 setScrollOffset(newScrollOffset
);
1309 // Trigger the autoscroll timer which will periodically call
1310 // triggerAutoScrolling()
1311 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1314 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1316 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1318 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1319 Q_ASSERT(groupHeader
);
1320 updateGroupHeaderLayout(widget
);
1323 void KItemListView::setController(KItemListController
* controller
)
1325 if (m_controller
!= controller
) {
1326 KItemListController
* previous
= m_controller
;
1328 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1329 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1330 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1333 m_controller
= controller
;
1336 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1337 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1338 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1341 onControllerChanged(controller
, previous
);
1345 void KItemListView::setModel(KItemModelBase
* model
)
1347 if (m_model
== model
) {
1351 KItemModelBase
* previous
= m_model
;
1354 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1355 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1356 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1357 this, SLOT(slotItemsInserted(KItemRangeList
)));
1358 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1359 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1360 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1361 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1362 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1363 this, SLOT(slotGroupedSortingChanged(bool)));
1364 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1365 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1366 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1367 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1371 m_layouter
->setModel(model
);
1372 m_grouped
= model
->groupedSorting();
1375 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1376 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1377 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1378 this, SLOT(slotItemsInserted(KItemRangeList
)));
1379 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1380 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1381 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1382 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1383 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1384 this, SLOT(slotGroupedSortingChanged(bool)));
1385 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1386 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1387 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1388 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1391 onModelChanged(model
, previous
);
1394 KItemListRubberBand
* KItemListView::rubberBand() const
1396 return m_rubberBand
;
1399 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1401 if (m_layoutTimer
->isActive()) {
1402 m_layoutTimer
->stop();
1405 if (m_activeTransactions
> 0) {
1406 if (hint
== NoAnimation
) {
1407 // As soon as at least one property change should be done without animation,
1408 // the whole transaction will be marked as not animated.
1409 m_endTransactionAnimationHint
= NoAnimation
;
1414 if (!m_model
|| m_model
->count() < 0) {
1418 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1419 if (firstVisibleIndex
< 0) {
1420 emitOffsetChanges();
1424 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1425 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1426 // is still shown if the maximum offset got decreased.
1427 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1428 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1429 if (scrollOffset() > maxOffsetToShowFullRange
) {
1430 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1431 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1434 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1436 int firstSibblingIndex
= -1;
1437 int lastSibblingIndex
= -1;
1438 const bool supportsExpanding
= supportsItemExpanding();
1440 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1442 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1443 // instances from invisible items are reused. If no reusable items are
1444 // found then new KItemListWidget instances get created.
1445 const bool animate
= (hint
== Animation
);
1446 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1447 bool applyNewPos
= true;
1448 bool wasHidden
= false;
1450 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1451 const QPointF newPos
= itemBounds
.topLeft();
1452 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1455 if (!reusableItems
.isEmpty()) {
1456 // Reuse a KItemListWidget instance from an invisible item
1457 const int oldIndex
= reusableItems
.takeLast();
1458 widget
= m_visibleItems
.value(oldIndex
);
1459 setWidgetIndex(widget
, i
);
1460 updateWidgetProperties(widget
, i
);
1461 initializeItemListWidget(widget
);
1463 // No reusable KItemListWidget instance is available, create a new one
1464 widget
= createWidget(i
);
1466 widget
->resize(itemBounds
.size());
1468 if (animate
&& changedCount
< 0) {
1469 // Items have been deleted, move the created item to the
1470 // imaginary old position. They will get animated to the new position
1472 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1473 if (itemRect
.isEmpty()) {
1474 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1475 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1476 widget
->setPos(invisibleOldPos
);
1478 widget
->setPos(itemRect
.topLeft());
1480 applyNewPos
= false;
1483 if (supportsExpanding
&& changedCount
== 0) {
1484 if (firstSibblingIndex
< 0) {
1485 firstSibblingIndex
= i
;
1487 lastSibblingIndex
= i
;
1492 const bool itemsRemoved
= (changedCount
< 0);
1493 const bool itemsInserted
= (changedCount
> 0);
1494 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1495 // The item is located after the removed items. Animate the moving of the position.
1496 applyNewPos
= !moveWidget(widget
, newPos
);
1497 } else if (itemsInserted
&& i
>= changedIndex
) {
1498 // The item is located after the first inserted item
1499 if (i
<= changedIndex
+ changedCount
- 1) {
1500 // The item is an inserted item. Animate the appearing of the item.
1501 // For performance reasons no animation is done when changedCount is equal
1502 // to all available items.
1503 if (changedCount
< m_model
->count()) {
1504 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1506 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1507 // The item was already there before, so animate the moving of the position.
1508 // No moving animation is done if the item is animated by a create animation: This
1509 // prevents a "move animation mess" when inserting several ranges in parallel.
1510 applyNewPos
= !moveWidget(widget
, newPos
);
1512 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1513 // The size of the view might have been changed. Animate the moving of the position.
1514 applyNewPos
= !moveWidget(widget
, newPos
);
1517 m_animation
->stop(widget
);
1521 widget
->setPos(newPos
);
1524 Q_ASSERT(widget
->index() == i
);
1525 widget
->setVisible(true);
1527 if (widget
->size() != itemBounds
.size()) {
1528 // Resize the widget for the item to the changed size.
1530 // If a dynamic item size is used then no animation is done in the direction
1531 // of the dynamic size.
1532 if (m_itemSize
.width() <= 0) {
1533 // The width is dynamic, apply the new width without animation.
1534 widget
->resize(itemBounds
.width(), widget
->size().height());
1535 } else if (m_itemSize
.height() <= 0) {
1536 // The height is dynamic, apply the new height without animation.
1537 widget
->resize(widget
->size().width(), itemBounds
.height());
1539 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1541 widget
->resize(itemBounds
.size());
1545 // Updating the cell-information must be done as last step: The decision whether the
1546 // moving-animation should be started at all is based on the previous cell-information.
1547 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1548 m_visibleCells
.insert(i
, cell
);
1551 // Delete invisible KItemListWidget instances that have not been reused
1552 foreach (int index
, reusableItems
) {
1553 recycleWidget(m_visibleItems
.value(index
));
1556 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1557 Q_ASSERT(lastSibblingIndex
>= 0);
1558 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1562 // Update the layout of all visible group headers
1563 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1564 while (it
.hasNext()) {
1566 updateGroupHeaderLayout(it
.key());
1570 emitOffsetChanges();
1573 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1574 int lastVisibleIndex
,
1575 LayoutAnimationHint hint
)
1577 // Determine all items that are completely invisible and might be
1578 // reused for items that just got (at least partly) visible. If the
1579 // animation hint is set to 'Animation' items that do e.g. an animated
1580 // moving of their position are not marked as invisible: This assures
1581 // that a scrolling inside the view can be done without breaking an animation.
1585 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1586 while (it
.hasNext()) {
1589 KItemListWidget
* widget
= it
.value();
1590 const int index
= widget
->index();
1591 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1594 if (m_animation
->isStarted(widget
)) {
1595 if (hint
== NoAnimation
) {
1596 // Stopping the animation will call KItemListView::slotAnimationFinished()
1597 // and the widget will be recycled if necessary there.
1598 m_animation
->stop(widget
);
1601 widget
->setVisible(false);
1602 items
.append(index
);
1605 recycleGroupHeaderForWidget(widget
);
1614 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1616 if (widget
->pos() == newPos
) {
1620 bool startMovingAnim
= false;
1622 // When having a grid the moving-animation should only be started, if it is done within
1623 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1624 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1625 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1626 const int index
= widget
->index();
1627 const Cell cell
= m_visibleCells
.value(index
);
1628 if (cell
.column
>= 0 && cell
.row
>= 0) {
1629 if (scrollOrientation() == Qt::Vertical
) {
1630 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1632 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1636 if (startMovingAnim
) {
1637 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1641 m_animation
->stop(widget
);
1642 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1646 void KItemListView::emitOffsetChanges()
1648 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1649 if (m_oldScrollOffset
!= newScrollOffset
) {
1650 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1651 m_oldScrollOffset
= newScrollOffset
;
1654 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1655 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1656 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1657 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1660 const qreal newItemOffset
= m_layouter
->itemOffset();
1661 if (m_oldItemOffset
!= newItemOffset
) {
1662 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1663 m_oldItemOffset
= newItemOffset
;
1666 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1667 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1668 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1669 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1673 KItemListWidget
* KItemListView::createWidget(int index
)
1675 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1676 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1678 m_visibleItems
.insert(index
, widget
);
1679 m_visibleCells
.insert(index
, Cell());
1680 updateWidgetProperties(widget
, index
);
1681 initializeItemListWidget(widget
);
1685 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1688 recycleGroupHeaderForWidget(widget
);
1691 const int index
= widget
->index();
1692 m_visibleItems
.remove(index
);
1693 m_visibleCells
.remove(index
);
1695 m_widgetCreator
->recycle(widget
);
1698 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1700 const int oldIndex
= widget
->index();
1701 m_visibleItems
.remove(oldIndex
);
1702 m_visibleCells
.remove(oldIndex
);
1704 m_visibleItems
.insert(index
, widget
);
1705 m_visibleCells
.insert(index
, Cell());
1707 widget
->setIndex(index
);
1710 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1712 const int oldIndex
= widget
->index();
1713 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1715 setWidgetIndex(widget
, index
);
1717 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1718 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1719 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1720 (!vertical
&& oldCell
.column
== newCell
.column
);
1722 m_visibleCells
.insert(index
, newCell
);
1726 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1729 case LayouterSize
: m_layouter
->setSize(size
); break;
1730 case ItemSize
: m_layouter
->setItemSize(size
); break;
1735 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1737 widget
->setVisibleRoles(m_visibleRoles
);
1738 updateWidgetColumnWidths(widget
);
1739 widget
->setStyleOption(m_styleOption
);
1741 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1742 widget
->setCurrent(index
== selectionManager
->currentItem());
1743 widget
->setSelected(selectionManager
->isSelected(index
));
1744 widget
->setHovered(false);
1745 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1746 widget
->setIndex(index
);
1747 widget
->setData(m_model
->data(index
));
1748 widget
->setSiblingsInformation(QBitArray());
1749 updateAlternateBackgroundForWidget(widget
);
1752 updateGroupHeaderForWidget(widget
);
1756 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1758 Q_ASSERT(m_grouped
);
1760 const int index
= widget
->index();
1761 if (!m_layouter
->isFirstGroupItem(index
)) {
1762 // The widget does not represent the first item of a group
1763 // and hence requires no header
1764 recycleGroupHeaderForWidget(widget
);
1768 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1769 if (groups
.isEmpty()) {
1773 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1775 groupHeader
= m_groupHeaderCreator
->create(this);
1776 groupHeader
->setParentItem(widget
);
1777 m_visibleGroups
.insert(widget
, groupHeader
);
1778 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1780 Q_ASSERT(groupHeader
->parentItem() == widget
);
1782 const int groupIndex
= groupIndexForItem(index
);
1783 Q_ASSERT(groupIndex
>= 0);
1784 groupHeader
->setData(groups
.at(groupIndex
).second
);
1785 groupHeader
->setRole(model()->sortRole());
1786 groupHeader
->setStyleOption(m_styleOption
);
1787 groupHeader
->setScrollOrientation(scrollOrientation());
1788 groupHeader
->setItemIndex(index
);
1790 groupHeader
->show();
1793 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1795 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1796 Q_ASSERT(groupHeader
);
1798 const int index
= widget
->index();
1799 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1800 const QRectF itemRect
= m_layouter
->itemRect(index
);
1802 // The group-header is a child of the itemlist widget. Translate the
1803 // group header position to the relative position.
1804 if (scrollOrientation() == Qt::Vertical
) {
1805 // In the vertical scroll orientation the group header should always span
1806 // the whole width no matter which temporary position the parent widget
1807 // has. In this case the x-position and width will be adjusted manually.
1808 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1809 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1811 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1812 groupHeader
->resize(groupHeaderRect
.size());
1816 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1818 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1820 header
->setParentItem(0);
1821 m_groupHeaderCreator
->recycle(header
);
1822 m_visibleGroups
.remove(widget
);
1823 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1827 void KItemListView::updateVisibleGroupHeaders()
1829 Q_ASSERT(m_grouped
);
1830 m_layouter
->markAsDirty();
1832 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1833 while (it
.hasNext()) {
1835 updateGroupHeaderForWidget(it
.value());
1839 int KItemListView::groupIndexForItem(int index
) const
1841 Q_ASSERT(m_grouped
);
1843 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1844 if (groups
.isEmpty()) {
1849 int max
= groups
.count() - 1;
1852 mid
= (min
+ max
) / 2;
1853 if (index
> groups
[mid
].first
) {
1858 } while (groups
[mid
].first
!= index
&& min
<= max
);
1861 while (groups
[mid
].first
> index
&& mid
> 0) {
1869 void KItemListView::updateAlternateBackgrounds()
1871 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1872 while (it
.hasNext()) {
1874 updateAlternateBackgroundForWidget(it
.value());
1878 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1880 bool enabled
= useAlternateBackgrounds();
1882 const int index
= widget
->index();
1883 enabled
= (index
& 0x1) > 0;
1885 const int groupIndex
= groupIndexForItem(index
);
1886 if (groupIndex
>= 0) {
1887 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1888 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1889 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1890 enabled
= (relativeIndex
& 0x1) > 0;
1894 widget
->setAlternateBackground(enabled
);
1897 bool KItemListView::useAlternateBackgrounds() const
1899 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1902 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
1904 QElapsedTimer timer
;
1907 QHash
<QByteArray
, qreal
> widths
;
1909 int calculatedItemCount
= 0;
1910 bool maxTimeExceeded
= false;
1911 foreach (const KItemRange
& itemRange
, itemRanges
) {
1912 const int startIndex
= itemRange
.index
;
1913 const int endIndex
= startIndex
+ itemRange
.count
- 1;
1915 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
1916 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
1917 qreal maxWidth
= widths
.value(visibleRole
, 0);
1918 const qreal width
= preferredRoleColumnWidth(visibleRole
, i
);
1919 maxWidth
= qMax(width
, maxWidth
);
1920 widths
.insert(visibleRole
, maxWidth
);
1923 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
1924 // When having several thousands of items calculating the sizes can get
1925 // very expensive. We accept a possibly too small role-size in favour
1926 // of having no blocking user interface.
1927 maxTimeExceeded
= true;
1930 ++calculatedItemCount
;
1932 if (maxTimeExceeded
) {
1940 void KItemListView::applyColumnWidthsFromHeader()
1942 // Apply the new size to the layouter
1943 const qreal requiredWidth
= columnWidthsSum();
1944 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
1945 m_itemSize
.height());
1946 m_layouter
->setItemSize(dynamicItemSize
);
1947 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
1949 // Update the role sizes for all visible widgets
1950 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1951 while (it
.hasNext()) {
1953 updateWidgetColumnWidths(it
.value());
1957 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
1959 foreach (const QByteArray
& role
, m_visibleRoles
) {
1960 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
1964 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
1966 Q_ASSERT(m_itemSize
.isEmpty());
1967 const int itemCount
= m_model
->count();
1968 int rangesItemCount
= 0;
1969 foreach (const KItemRange
& range
, itemRanges
) {
1970 rangesItemCount
+= range
.count
;
1973 if (itemCount
== rangesItemCount
) {
1974 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
1975 foreach (const QByteArray
& role
, m_visibleRoles
) {
1976 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
1979 // Only a sub range of the roles need to be determined.
1980 // The chances are good that the widths of the sub ranges
1981 // already fit into the available widths and hence no
1982 // expensive update might be required.
1983 bool changed
= false;
1985 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
1986 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
1987 while (it
.hasNext()) {
1989 const QByteArray
& role
= it
.key();
1990 const qreal updatedWidth
= it
.value();
1991 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
1992 if (updatedWidth
> currentWidth
) {
1993 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
1999 // All the updated sizes are smaller than the current sizes and no change
2000 // of the stretched roles-widths is required
2005 if (m_headerWidget
->automaticColumnResizing()) {
2006 applyAutomaticColumnWidths();
2010 void KItemListView::updatePreferredColumnWidths()
2016 const int itemCount
= m_model
->count();
2017 if (itemCount
> 0) {
2018 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, itemCount
));
2022 void KItemListView::applyAutomaticColumnWidths()
2024 Q_ASSERT(m_itemSize
.isEmpty());
2025 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2027 // Calculate the maximum size of an item by considering the
2028 // visible role sizes and apply them to the layouter. If the
2029 // size does not use the available view-size the size of the
2030 // first role will get stretched.
2032 foreach (const QByteArray
& role
, m_visibleRoles
) {
2033 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2034 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2037 const QByteArray firstRole
= m_visibleRoles
.first();
2038 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2039 QSizeF dynamicItemSize
= m_itemSize
;
2041 qreal requiredWidth
= columnWidthsSum();
2042 const qreal availableWidth
= size().width();
2043 if (requiredWidth
< availableWidth
) {
2044 // Stretch the first column to use the whole remaining width
2045 firstColumnWidth
+= availableWidth
- requiredWidth
;
2046 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2047 } else if (requiredWidth
> availableWidth
) {
2048 // Shrink the first column to be able to show as much other
2049 // columns as possible
2050 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2052 // TODO: A proper calculation of the minimum width depends on the implementation
2053 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2055 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2056 if (shrinkedFirstColumnWidth
< minWidth
) {
2057 shrinkedFirstColumnWidth
= minWidth
;
2060 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2061 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2064 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2066 m_layouter
->setItemSize(dynamicItemSize
);
2067 m_headerWidget
->resize(dynamicItemSize
.width(), m_headerWidget
->size().height());
2069 // Update the role sizes for all visible widgets
2070 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2071 while (it
.hasNext()) {
2073 updateWidgetColumnWidths(it
.value());
2077 qreal
KItemListView::columnWidthsSum() const
2079 qreal widthsSum
= 0;
2080 foreach (const QByteArray
& role
, m_visibleRoles
) {
2081 widthsSum
+= m_headerWidget
->columnWidth(role
);
2086 QRectF
KItemListView::headerBoundaries() const
2088 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2091 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2092 const QSizeF
& newItemSize
,
2093 const QSizeF
& newItemMargin
) const
2095 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2099 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2100 const qreal itemWidth
= m_layouter
->itemSize().width();
2101 if (itemWidth
> 0) {
2102 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2103 newItemSize
.width(),
2104 newItemMargin
.width());
2105 if (m_model
->count() > newColumnCount
) {
2106 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2108 m_layouter
->itemMargin().width());
2109 return oldColumnCount
!= newColumnCount
;
2113 const qreal itemHeight
= m_layouter
->itemSize().height();
2114 if (itemHeight
> 0) {
2115 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2116 newItemSize
.height(),
2117 newItemMargin
.height());
2118 if (m_model
->count() > newRowCount
) {
2119 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2121 m_layouter
->itemMargin().height());
2122 return oldRowCount
!= newRowCount
;
2130 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2132 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2136 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2137 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2138 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2139 // Only animate if up to 2/3 of a row or column are inserted or removed
2140 return changedItemCount
<= maximum
* 2 / 3;
2144 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2146 const QSizeF oldSize
= m_layouter
->size();
2148 m_layouter
->setSize(size
);
2149 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2150 m_layouter
->setSize(oldSize
);
2152 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2153 : maxOffset
> size
.width();
2156 void KItemListView::updateGroupHeaderHeight()
2158 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2159 qreal groupHeaderMargin
= 0;
2161 if (scrollOrientation() == Qt::Horizontal
) {
2162 // The vertical margin above and below the header should be
2163 // equal to the horizontal margin, not the vertical margin
2164 // from m_styleOption.
2165 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2166 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2167 } else if (m_itemSize
.isEmpty()){
2168 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2169 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2171 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2172 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2174 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2175 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2177 updateVisibleGroupHeaders();
2180 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2182 if (!supportsItemExpanding() || !m_model
) {
2186 if (firstIndex
< 0 || lastIndex
< 0) {
2187 firstIndex
= m_layouter
->firstVisibleIndex();
2188 lastIndex
= m_layouter
->lastVisibleIndex();
2190 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2191 lastIndex
>= m_layouter
->firstVisibleIndex());
2192 if (!isRangeVisible
) {
2197 int previousParents
= 0;
2198 QBitArray previousSiblings
;
2200 // The rootIndex describes the first index where the siblings get
2201 // calculated from. For the calculation the upper most parent item
2202 // is required. For performance reasons it is checked first whether
2203 // the visible items before or after the current range already
2204 // contain a siblings information which can be used as base.
2205 int rootIndex
= firstIndex
;
2207 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2209 // There is no visible widget before the range, check whether there
2210 // is one after the range:
2211 widget
= m_visibleItems
.value(lastIndex
+ 1);
2213 // The sibling information of the widget may only be used if
2214 // all items of the range have the same number of parents.
2215 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2216 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2217 if (m_model
->expandedParentsCount(i
) != parents
) {
2226 // Performance optimization: Use the sibling information of the visible
2227 // widget beside the given range.
2228 previousSiblings
= widget
->siblingsInformation();
2229 if (previousSiblings
.isEmpty()) {
2232 previousParents
= previousSiblings
.count() - 1;
2233 previousSiblings
.truncate(previousParents
);
2235 // Potentially slow path: Go back to the upper most parent of firstIndex
2236 // to be able to calculate the initial value for the siblings.
2237 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2242 Q_ASSERT(previousParents
>= 0);
2243 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2244 // Update the parent-siblings in case if the current item represents
2245 // a child or an upper parent.
2246 const int currentParents
= m_model
->expandedParentsCount(i
);
2247 Q_ASSERT(currentParents
>= 0);
2248 if (previousParents
< currentParents
) {
2249 previousParents
= currentParents
;
2250 previousSiblings
.resize(currentParents
);
2251 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2252 } else if (previousParents
> currentParents
) {
2253 previousParents
= currentParents
;
2254 previousSiblings
.truncate(currentParents
);
2257 if (i
>= firstIndex
) {
2258 // The index represents a visible item. Apply the parent-siblings
2259 // and update the sibling of the current item.
2260 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2265 QBitArray siblings
= previousSiblings
;
2266 siblings
.resize(siblings
.count() + 1);
2267 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2269 widget
->setSiblingsInformation(siblings
);
2274 bool KItemListView::hasSiblingSuccessor(int index
) const
2276 bool hasSuccessor
= false;
2277 const int parentsCount
= m_model
->expandedParentsCount(index
);
2278 int successorIndex
= index
+ 1;
2280 // Search the next sibling
2281 const int itemCount
= m_model
->count();
2282 while (successorIndex
< itemCount
) {
2283 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2284 if (currentParentsCount
== parentsCount
) {
2285 hasSuccessor
= true;
2287 } else if (currentParentsCount
< parentsCount
) {
2293 if (m_grouped
&& hasSuccessor
) {
2294 // If the sibling is part of another group, don't mark it as
2295 // successor as the group header is between the sibling connections.
2296 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2297 if (m_layouter
->isFirstGroupItem(i
)) {
2298 hasSuccessor
= false;
2304 return hasSuccessor
;
2307 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2311 const int minSpeed
= 4;
2312 const int maxSpeed
= 128;
2313 const int speedLimiter
= 96;
2314 const int autoScrollBorder
= 64;
2316 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2317 // This assures that the autoscrolling speed grows gradually.
2318 const int incLimiter
= 1;
2320 if (pos
< autoScrollBorder
) {
2321 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2322 inc
= qMax(inc
, -maxSpeed
);
2323 inc
= qMax(inc
, oldInc
- incLimiter
);
2324 } else if (pos
> range
- autoScrollBorder
) {
2325 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2326 inc
= qMin(inc
, maxSpeed
);
2327 inc
= qMin(inc
, oldInc
+ incLimiter
);
2333 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2335 const qreal availableSize
= size
- itemMargin
;
2336 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2342 KItemListCreatorBase::~KItemListCreatorBase()
2344 qDeleteAll(m_recycleableWidgets
);
2345 qDeleteAll(m_createdWidgets
);
2348 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2350 m_createdWidgets
.insert(widget
);
2353 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2355 Q_ASSERT(m_createdWidgets
.contains(widget
));
2356 m_createdWidgets
.remove(widget
);
2358 if (m_recycleableWidgets
.count() < 100) {
2359 m_recycleableWidgets
.append(widget
);
2360 widget
->setVisible(false);
2366 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2368 if (m_recycleableWidgets
.isEmpty()) {
2372 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2373 m_createdWidgets
.insert(widget
);
2377 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2381 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2383 widget
->setParentItem(0);
2384 widget
->setOpacity(1.0);
2385 pushRecycleableWidget(widget
);
2388 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2392 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2394 header
->setOpacity(1.0);
2395 pushRecycleableWidget(header
);
2398 #include "kitemlistview.moc"