1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "kitemlistcontroller.h"
26 #include "kitemlistheader.h"
27 #include "kitemlistselectionmanager.h"
28 #include "kitemlistwidget.h"
30 #include "private/kitemlistheaderwidget.h"
31 #include "private/kitemlistrubberband.h"
32 #include "private/kitemlistsizehintresolver.h"
33 #include "private/kitemlistviewlayouter.h"
34 #include "private/kitemlistviewanimation.h"
39 #include <QGraphicsSceneMouseEvent>
41 #include <QPropertyAnimation>
43 #include <QStyleOptionRubberBand>
47 // Time in ms until reaching the autoscroll margin triggers
48 // an initial autoscrolling
49 const int InitialAutoScrollDelay
= 700;
51 // Delay in ms for triggering the next autoscroll
52 const int RepeatingAutoScrollDelay
= 1000 / 60;
55 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
56 QGraphicsWidget(parent
),
57 m_enabledSelectionToggles(false),
59 m_supportsItemExpanding(false),
60 m_activeTransactions(0),
61 m_endTransactionAnimationHint(Animation
),
67 m_groupHeaderCreator(0),
72 m_sizeHintResolver(0),
77 m_oldMaximumScrollOffset(0),
79 m_oldMaximumItemOffset(0),
80 m_skipAutoScrollForRubberBand(false),
83 m_autoScrollIncrement(0),
88 setAcceptHoverEvents(true);
90 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
92 m_layouter
= new KItemListViewLayouter(this);
93 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
95 m_animation
= new KItemListViewAnimation(this);
96 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
97 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
99 m_layoutTimer
= new QTimer(this);
100 m_layoutTimer
->setInterval(300);
101 m_layoutTimer
->setSingleShot(true);
102 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
104 m_rubberBand
= new KItemListRubberBand(this);
105 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
107 m_headerWidget
= new KItemListHeaderWidget(this);
108 m_headerWidget
->setVisible(false);
110 m_header
= new KItemListHeader(this);
113 KItemListView::~KItemListView()
115 delete m_sizeHintResolver
;
116 m_sizeHintResolver
= 0;
119 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
121 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
122 if (orientation
== previousOrientation
) {
126 m_layouter
->setScrollOrientation(orientation
);
127 m_animation
->setScrollOrientation(orientation
);
128 m_sizeHintResolver
->clearCache();
131 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
132 while (it
.hasNext()) {
134 it
.value()->setScrollOrientation(orientation
);
136 updateGroupHeaderHeight();
140 doLayout(NoAnimation
);
142 onScrollOrientationChanged(orientation
, previousOrientation
);
143 emit
scrollOrientationChanged(orientation
, previousOrientation
);
146 Qt::Orientation
KItemListView::scrollOrientation() const
148 return m_layouter
->scrollOrientation();
151 void KItemListView::setItemSize(const QSizeF
& size
)
153 const QSizeF previousSize
= m_itemSize
;
154 if (size
== previousSize
) {
158 // Skip animations when the number of rows or columns
159 // are changed in the grid layout. Although the animation
160 // engine can handle this usecase, it looks obtrusive.
161 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
163 m_layouter
->itemMargin());
165 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
166 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
167 (!m_itemSize
.isEmpty() && size
.isEmpty()));
171 if (alternateBackgroundsChanged
) {
172 // For an empty item size alternate backgrounds are drawn if more than
173 // one role is shown. Assure that the backgrounds for visible items are
174 // updated when changing the size in this context.
175 updateAlternateBackgrounds();
178 if (size
.isEmpty()) {
179 if (m_headerWidget
->automaticColumnResizing()) {
180 updatePreferredColumnWidths();
182 // Only apply the changed height and respect the header widths
184 const qreal currentWidth
= m_layouter
->itemSize().width();
185 const QSizeF
newSize(currentWidth
, size
.height());
186 m_layouter
->setItemSize(newSize
);
189 m_layouter
->setItemSize(size
);
192 m_sizeHintResolver
->clearCache();
193 doLayout(animate
? Animation
: NoAnimation
);
194 onItemSizeChanged(size
, previousSize
);
197 QSizeF
KItemListView::itemSize() const
202 void KItemListView::setScrollOffset(qreal offset
)
208 const qreal previousOffset
= m_layouter
->scrollOffset();
209 if (offset
== previousOffset
) {
213 m_layouter
->setScrollOffset(offset
);
214 m_animation
->setScrollOffset(offset
);
216 // Don't check whether the m_layoutTimer is active: Changing the
217 // scroll offset must always trigger a synchronous layout, otherwise
218 // the smooth-scrolling might get jerky.
219 doLayout(NoAnimation
);
220 onScrollOffsetChanged(offset
, previousOffset
);
223 qreal
KItemListView::scrollOffset() const
225 return m_layouter
->scrollOffset();
228 qreal
KItemListView::maximumScrollOffset() const
230 return m_layouter
->maximumScrollOffset();
233 void KItemListView::setItemOffset(qreal offset
)
235 if (m_layouter
->itemOffset() == offset
) {
239 m_layouter
->setItemOffset(offset
);
240 if (m_headerWidget
->isVisible()) {
241 m_headerWidget
->setOffset(offset
);
244 // Don't check whether the m_layoutTimer is active: Changing the
245 // item offset must always trigger a synchronous layout, otherwise
246 // the smooth-scrolling might get jerky.
247 doLayout(NoAnimation
);
250 qreal
KItemListView::itemOffset() const
252 return m_layouter
->itemOffset();
255 qreal
KItemListView::maximumItemOffset() const
257 return m_layouter
->maximumItemOffset();
260 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
262 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
263 m_visibleRoles
= roles
;
264 onVisibleRolesChanged(roles
, previousRoles
);
266 m_sizeHintResolver
->clearCache();
267 m_layouter
->markAsDirty();
269 if (m_itemSize
.isEmpty()) {
270 m_headerWidget
->setColumns(roles
);
271 updatePreferredColumnWidths();
272 if (!m_headerWidget
->automaticColumnResizing()) {
273 // The column-width of new roles are still 0. Apply the preferred
274 // column-width as default with.
275 foreach (const QByteArray
& role
, m_visibleRoles
) {
276 if (m_headerWidget
->columnWidth(role
) == 0) {
277 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
278 m_headerWidget
->setColumnWidth(role
, width
);
282 applyColumnWidthsFromHeader();
286 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
287 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
288 (roles
.count() <= 1 && previousRoles
.count() > 1));
290 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
291 while (it
.hasNext()) {
293 KItemListWidget
* widget
= it
.value();
294 widget
->setVisibleRoles(roles
);
295 if (alternateBackgroundsChanged
) {
296 updateAlternateBackgroundForWidget(widget
);
300 doLayout(NoAnimation
);
303 QList
<QByteArray
> KItemListView::visibleRoles() const
305 return m_visibleRoles
;
308 void KItemListView::setAutoScroll(bool enabled
)
310 if (enabled
&& !m_autoScrollTimer
) {
311 m_autoScrollTimer
= new QTimer(this);
312 m_autoScrollTimer
->setSingleShot(true);
313 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
314 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
315 } else if (!enabled
&& m_autoScrollTimer
) {
316 delete m_autoScrollTimer
;
317 m_autoScrollTimer
= 0;
321 bool KItemListView::autoScroll() const
323 return m_autoScrollTimer
!= 0;
326 void KItemListView::setEnabledSelectionToggles(bool enabled
)
328 if (m_enabledSelectionToggles
!= enabled
) {
329 m_enabledSelectionToggles
= enabled
;
331 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
332 while (it
.hasNext()) {
334 it
.value()->setEnabledSelectionToggle(enabled
);
339 bool KItemListView::enabledSelectionToggles() const
341 return m_enabledSelectionToggles
;
344 KItemListController
* KItemListView::controller() const
349 KItemModelBase
* KItemListView::model() const
354 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
356 m_widgetCreator
= widgetCreator
;
359 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
361 return m_widgetCreator
;
364 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
366 m_groupHeaderCreator
= groupHeaderCreator
;
369 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
371 return m_groupHeaderCreator
;
374 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
376 const KItemListStyleOption previousOption
= m_styleOption
;
377 m_styleOption
= option
;
380 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
381 if (margin
!= m_layouter
->itemMargin()) {
382 // Skip animations when the number of rows or columns
383 // are changed in the grid layout. Although the animation
384 // engine can handle this usecase, it looks obtrusive.
385 animate
= !changesItemGridLayout(m_layouter
->size(),
386 m_layouter
->itemSize(),
388 m_layouter
->setItemMargin(margin
);
392 updateGroupHeaderHeight();
395 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
396 // Animating a change of the maximum text size just results in expensive
397 // temporary eliding and clipping operations and does not look good visually.
401 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
402 while (it
.hasNext()) {
404 it
.value()->setStyleOption(option
);
407 m_sizeHintResolver
->clearCache();
408 m_layouter
->markAsDirty();
409 doLayout(animate
? Animation
: NoAnimation
);
411 onStyleOptionChanged(option
, previousOption
);
414 const KItemListStyleOption
& KItemListView::styleOption() const
416 return m_styleOption
;
419 void KItemListView::setGeometry(const QRectF
& rect
)
421 QGraphicsWidget::setGeometry(rect
);
427 const QSizeF newSize
= rect
.size();
428 if (m_itemSize
.isEmpty()) {
429 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
430 if (m_headerWidget
->automaticColumnResizing()) {
431 applyAutomaticColumnWidths();
433 const qreal requiredWidth
= columnWidthsSum();
434 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
435 m_itemSize
.height());
436 m_layouter
->setItemSize(dynamicItemSize
);
439 // Triggering a synchronous layout is fine from a performance point of view,
440 // as with dynamic item sizes no moving animation must be done.
441 m_layouter
->setSize(newSize
);
442 doLayout(NoAnimation
);
444 const bool animate
= !changesItemGridLayout(newSize
,
445 m_layouter
->itemSize(),
446 m_layouter
->itemMargin());
447 m_layouter
->setSize(newSize
);
450 // Trigger an asynchronous relayout with m_layoutTimer to prevent
451 // performance bottlenecks. If the timer is exceeded, an animated layout
452 // will be triggered.
453 if (!m_layoutTimer
->isActive()) {
454 m_layoutTimer
->start();
457 m_layoutTimer
->stop();
458 doLayout(NoAnimation
);
463 int KItemListView::itemAt(const QPointF
& pos
) const
465 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
466 while (it
.hasNext()) {
469 const KItemListWidget
* widget
= it
.value();
470 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
471 if (widget
->contains(mappedPos
)) {
479 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
481 if (!m_enabledSelectionToggles
) {
485 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
487 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
488 if (!selectionToggleRect
.isEmpty()) {
489 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
490 return selectionToggleRect
.contains(mappedPos
);
496 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
498 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
500 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
501 if (!expansionToggleRect
.isEmpty()) {
502 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
503 return expansionToggleRect
.contains(mappedPos
);
509 int KItemListView::firstVisibleIndex() const
511 return m_layouter
->firstVisibleIndex();
514 int KItemListView::lastVisibleIndex() const
516 return m_layouter
->lastVisibleIndex();
519 QSizeF
KItemListView::itemSizeHint(int index
) const
521 return m_widgetCreator
->itemSizeHint(index
, this);
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 QStyleOptionHeader option
;
619 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
622 m_headerWidget
->setPos(0, 0);
623 m_headerWidget
->resize(size().width(), headerSize
.height());
624 m_headerWidget
->setModel(m_model
);
625 m_headerWidget
->setColumns(m_visibleRoles
);
626 m_headerWidget
->setZValue(1);
628 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
629 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
630 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
631 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
632 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
633 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
634 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
635 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
637 m_layouter
->setHeaderHeight(headerSize
.height());
638 m_headerWidget
->setVisible(true);
639 } else if (!visible
&& m_headerWidget
->isVisible()) {
640 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
641 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
642 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
643 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
644 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
645 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
646 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
647 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
649 m_layouter
->setHeaderHeight(0);
650 m_headerWidget
->setVisible(false);
654 bool KItemListView::isHeaderVisible() const
656 return m_headerWidget
->isVisible();
659 KItemListHeader
* KItemListView::header() const
664 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
670 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
672 QGraphicsWidget::paint(painter
, option
, widget
);
674 if (m_rubberBand
->isActive()) {
675 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
676 m_rubberBand
->endPosition()).normalized();
678 const QPointF topLeft
= rubberBandRect
.topLeft();
679 if (scrollOrientation() == Qt::Vertical
) {
680 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
682 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
685 QStyleOptionRubberBand opt
;
686 opt
.initFrom(widget
);
687 opt
.shape
= QRubberBand::Rectangle
;
689 opt
.rect
= rubberBandRect
.toRect();
690 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
694 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
699 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
701 Q_UNUSED(changedRoles
);
705 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
711 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
717 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
723 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
729 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
735 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
741 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
747 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
749 Q_UNUSED(supportsExpanding
);
752 void KItemListView::onTransactionBegin()
756 void KItemListView::onTransactionEnd()
760 bool KItemListView::event(QEvent
* event
)
762 // Forward all events to the controller and handle them there
763 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
767 return QGraphicsWidget::event(event
);
770 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
772 m_mousePos
= transform().map(event
->pos());
776 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
778 QGraphicsWidget::mouseMoveEvent(event
);
780 m_mousePos
= transform().map(event
->pos());
781 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
782 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
786 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
788 event
->setAccepted(true);
792 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
794 QGraphicsWidget::dragMoveEvent(event
);
796 m_mousePos
= transform().map(event
->pos());
797 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
798 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
802 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
804 QGraphicsWidget::dragLeaveEvent(event
);
805 setAutoScroll(false);
808 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
810 QGraphicsWidget::dropEvent(event
);
811 setAutoScroll(false);
814 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
816 return m_visibleItems
.values();
819 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
821 if (m_itemSize
.isEmpty()) {
822 updatePreferredColumnWidths(itemRanges
);
825 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
826 if (hasMultipleRanges
) {
830 m_layouter
->markAsDirty();
832 int previouslyInsertedCount
= 0;
833 foreach (const KItemRange
& range
, itemRanges
) {
834 // range.index is related to the model before anything has been inserted.
835 // As in each loop the current item-range gets inserted the index must
836 // be increased by the already previously inserted items.
837 const int index
= range
.index
+ previouslyInsertedCount
;
838 const int count
= range
.count
;
839 if (index
< 0 || count
<= 0) {
840 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
843 previouslyInsertedCount
+= count
;
845 m_sizeHintResolver
->itemsInserted(index
, count
);
847 // Determine which visible items must be moved
848 QList
<int> itemsToMove
;
849 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
850 while (it
.hasNext()) {
852 const int visibleItemIndex
= it
.key();
853 if (visibleItemIndex
>= index
) {
854 itemsToMove
.append(visibleItemIndex
);
858 // Update the indexes of all KItemListWidget instances that are located
859 // after the inserted items. It is important to adjust the indexes in the order
860 // from the highest index to the lowest index to prevent overlaps when setting the new index.
862 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
863 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
865 const int newIndex
= widget
->index() + count
;
866 if (hasMultipleRanges
) {
867 setWidgetIndex(widget
, newIndex
);
869 // Try to animate the moving of the item
870 moveWidgetToIndex(widget
, newIndex
);
874 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
875 // Check whether a scrollbar is required to show the inserted items. In this case
876 // the size of the layouter will be decreased before calling doLayout(): This prevents
877 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
878 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
879 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
880 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
881 if (decreaseLayouterSize
) {
882 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
883 QSizeF layouterSize
= m_layouter
->size();
884 if (verticalScrollOrientation
) {
885 layouterSize
.rwidth() -= scrollBarExtent
;
887 layouterSize
.rheight() -= scrollBarExtent
;
889 m_layouter
->setSize(layouterSize
);
893 if (!hasMultipleRanges
) {
894 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
895 updateSiblingsInformation();
900 m_controller
->selectionManager()->itemsInserted(itemRanges
);
903 if (hasMultipleRanges
) {
905 // Important: Don't read any m_layouter-property inside the for-loop in case if
906 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
907 // updated in each loop-cycle and has only a consistent state after the loop.
908 Q_ASSERT(m_layouter
->isDirty());
910 m_endTransactionAnimationHint
= NoAnimation
;
912 updateSiblingsInformation();
915 if (useAlternateBackgrounds()) {
916 updateAlternateBackgrounds();
920 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
922 if (m_itemSize
.isEmpty()) {
923 // Don't pass the item-range: The preferred column-widths of
924 // all items must be adjusted when removing items.
925 updatePreferredColumnWidths();
928 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
929 if (hasMultipleRanges
) {
933 m_layouter
->markAsDirty();
935 int removedItemsCount
= 0;
936 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
937 removedItemsCount
+= itemRanges
[i
].count
;
940 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
941 const KItemRange
& range
= itemRanges
[i
];
942 const int index
= range
.index
;
943 const int count
= range
.count
;
944 if (index
< 0 || count
<= 0) {
945 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
949 m_sizeHintResolver
->itemsRemoved(index
, count
);
951 const int firstRemovedIndex
= index
;
952 const int lastRemovedIndex
= index
+ count
- 1;
953 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
954 removedItemsCount
-= count
;
956 // Remove all KItemListWidget instances that got deleted
957 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
958 KItemListWidget
* widget
= m_visibleItems
.value(i
);
963 m_animation
->stop(widget
);
964 // Stopping the animation might lead to recycling the widget if
965 // it is invisible (see slotAnimationFinished()).
966 // Check again whether it is still visible:
967 if (!m_visibleItems
.contains(i
)) {
971 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
972 // Remove the widget without animation
973 recycleWidget(widget
);
975 // Animate the removing of the items. Special case: When removing an item there
976 // is no valid model index available anymore. For the
977 // remove-animation the item gets removed from m_visibleItems but the widget
978 // will stay alive until the animation has been finished and will
979 // be recycled (deleted) in KItemListView::slotAnimationFinished().
980 m_visibleItems
.remove(i
);
981 widget
->setIndex(-1);
982 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
986 // Update the indexes of all KItemListWidget instances that are located
987 // after the deleted items
988 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
989 KItemListWidget
* widget
= m_visibleItems
.value(i
);
991 const int newIndex
= i
- count
;
992 if (hasMultipleRanges
) {
993 setWidgetIndex(widget
, newIndex
);
995 // Try to animate the moving of the item
996 moveWidgetToIndex(widget
, newIndex
);
1001 if (!hasMultipleRanges
) {
1002 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1003 // assumes an updated geometry. If items are removed during an active transaction,
1004 // the transaction will be temporary deactivated so that doLayout() triggers a
1005 // geometry update if necessary.
1006 const int activeTransactions
= m_activeTransactions
;
1007 m_activeTransactions
= 0;
1008 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1009 m_activeTransactions
= activeTransactions
;
1010 updateSiblingsInformation();
1015 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1018 if (hasMultipleRanges
) {
1020 // Important: Don't read any m_layouter-property inside the for-loop in case if
1021 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1022 // updated in each loop-cycle and has only a consistent state after the loop.
1023 Q_ASSERT(m_layouter
->isDirty());
1025 m_endTransactionAnimationHint
= NoAnimation
;
1027 updateSiblingsInformation();
1030 if (useAlternateBackgrounds()) {
1031 updateAlternateBackgrounds();
1035 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1037 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1038 m_layouter
->markAsDirty();
1041 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1044 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1045 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1047 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1048 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1050 updateWidgetProperties(widget
, index
);
1051 initializeItemListWidget(widget
);
1055 doLayout(NoAnimation
);
1056 updateSiblingsInformation();
1059 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1060 const QSet
<QByteArray
>& roles
)
1062 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1063 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1064 updatePreferredColumnWidths(itemRanges
);
1067 foreach (const KItemRange
& itemRange
, itemRanges
) {
1068 const int index
= itemRange
.index
;
1069 const int count
= itemRange
.count
;
1071 if (updateSizeHints
) {
1072 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1073 m_layouter
->markAsDirty();
1075 if (!m_layoutTimer
->isActive()) {
1076 m_layoutTimer
->start();
1080 // Apply the changed roles to the visible item-widgets
1081 const int lastIndex
= index
+ count
- 1;
1082 for (int i
= index
; i
<= lastIndex
; ++i
) {
1083 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1085 widget
->setData(m_model
->data(i
), roles
);
1089 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1090 // The sort-role has been changed which might result
1091 // in modified group headers
1092 updateVisibleGroupHeaders();
1093 doLayout(NoAnimation
);
1098 void KItemListView::slotGroupedSortingChanged(bool current
)
1100 m_grouped
= current
;
1101 m_layouter
->markAsDirty();
1104 updateGroupHeaderHeight();
1106 // Clear all visible headers
1107 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1108 while (it
.hasNext()) {
1110 recycleGroupHeaderForWidget(it
.key());
1112 Q_ASSERT(m_visibleGroups
.isEmpty());
1115 if (useAlternateBackgrounds()) {
1116 // Changing the group mode requires to update the alternate backgrounds
1117 // as with the enabled group mode the altering is done on base of the first
1119 updateAlternateBackgrounds();
1121 updateSiblingsInformation();
1122 doLayout(NoAnimation
);
1125 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1130 updateVisibleGroupHeaders();
1131 doLayout(NoAnimation
);
1135 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1140 updateVisibleGroupHeaders();
1141 doLayout(NoAnimation
);
1145 void KItemListView::slotCurrentChanged(int current
, int previous
)
1149 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1150 if (previousWidget
) {
1151 previousWidget
->setCurrent(false);
1154 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1155 if (currentWidget
) {
1156 currentWidget
->setCurrent(true);
1160 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1164 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1165 while (it
.hasNext()) {
1167 const int index
= it
.key();
1168 KItemListWidget
* widget
= it
.value();
1169 widget
->setSelected(current
.contains(index
));
1173 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1174 KItemListViewAnimation::AnimationType type
)
1176 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1177 Q_ASSERT(itemListWidget
);
1180 case KItemListViewAnimation::DeleteAnimation
: {
1181 // As we recycle the widget in this case it is important to assure that no
1182 // other animation has been started. This is a convention in KItemListView and
1183 // not a requirement defined by KItemListViewAnimation.
1184 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1186 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1187 // by m_visibleWidgets and must be deleted manually after the animation has
1189 recycleGroupHeaderForWidget(itemListWidget
);
1190 m_widgetCreator
->recycle(itemListWidget
);
1194 case KItemListViewAnimation::CreateAnimation
:
1195 case KItemListViewAnimation::MovingAnimation
:
1196 case KItemListViewAnimation::ResizeAnimation
: {
1197 const int index
= itemListWidget
->index();
1198 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1199 (index
> m_layouter
->lastVisibleIndex());
1200 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1201 recycleWidget(itemListWidget
);
1210 void KItemListView::slotLayoutTimerFinished()
1212 m_layouter
->setSize(geometry().size());
1213 doLayout(Animation
);
1216 void KItemListView::slotRubberBandPosChanged()
1221 void KItemListView::slotRubberBandActivationChanged(bool active
)
1224 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1225 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1226 m_skipAutoScrollForRubberBand
= true;
1228 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1229 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1230 m_skipAutoScrollForRubberBand
= false;
1236 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1238 qreal previousWidth
)
1241 Q_UNUSED(currentWidth
);
1242 Q_UNUSED(previousWidth
);
1244 m_headerWidget
->setAutomaticColumnResizing(false);
1245 applyColumnWidthsFromHeader();
1246 doLayout(NoAnimation
);
1249 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1253 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1255 const QList
<QByteArray
> previous
= m_visibleRoles
;
1257 QList
<QByteArray
> current
= m_visibleRoles
;
1258 current
.removeAt(previousIndex
);
1259 current
.insert(currentIndex
, role
);
1261 setVisibleRoles(current
);
1263 emit
visibleRolesChanged(current
, previous
);
1266 void KItemListView::triggerAutoScrolling()
1268 if (!m_autoScrollTimer
) {
1273 int visibleSize
= 0;
1274 if (scrollOrientation() == Qt::Vertical
) {
1275 pos
= m_mousePos
.y();
1276 visibleSize
= size().height();
1278 pos
= m_mousePos
.x();
1279 visibleSize
= size().width();
1282 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1283 m_autoScrollIncrement
= 0;
1286 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1287 if (m_autoScrollIncrement
== 0) {
1288 // The mouse position is not above an autoscroll margin (the autoscroll timer
1289 // will be restarted in mouseMoveEvent())
1290 m_autoScrollTimer
->stop();
1294 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1295 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1296 // if the direction of the rubberband is similar to the autoscroll direction. This
1297 // prevents that starting to create a rubberband within the autoscroll margins starts
1298 // an autoscrolling.
1300 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1301 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1302 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1303 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1304 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1305 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1306 // been moved up although the autoscroll direction might be down)
1307 m_autoScrollTimer
->stop();
1312 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1313 // the autoscrolling may not get skipped anymore until a new rubberband is created
1314 m_skipAutoScrollForRubberBand
= false;
1316 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1317 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1318 setScrollOffset(newScrollOffset
);
1320 // Trigger the autoscroll timer which will periodically call
1321 // triggerAutoScrolling()
1322 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1325 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1327 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1329 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1330 Q_ASSERT(groupHeader
);
1331 updateGroupHeaderLayout(widget
);
1334 void KItemListView::setController(KItemListController
* controller
)
1336 if (m_controller
!= controller
) {
1337 KItemListController
* previous
= m_controller
;
1339 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1340 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1341 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1344 m_controller
= controller
;
1347 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1348 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1349 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1352 onControllerChanged(controller
, previous
);
1356 void KItemListView::setModel(KItemModelBase
* model
)
1358 if (m_model
== model
) {
1362 KItemModelBase
* previous
= m_model
;
1365 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1366 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1367 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1368 this, SLOT(slotItemsInserted(KItemRangeList
)));
1369 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1370 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1371 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1372 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1373 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1374 this, SLOT(slotGroupedSortingChanged(bool)));
1375 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1376 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1377 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1378 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1382 m_layouter
->setModel(model
);
1383 m_grouped
= model
->groupedSorting();
1386 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1387 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1388 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1389 this, SLOT(slotItemsInserted(KItemRangeList
)));
1390 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1391 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1392 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1393 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1394 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1395 this, SLOT(slotGroupedSortingChanged(bool)));
1396 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1397 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1398 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1399 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1402 onModelChanged(model
, previous
);
1405 KItemListRubberBand
* KItemListView::rubberBand() const
1407 return m_rubberBand
;
1410 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1412 if (m_layoutTimer
->isActive()) {
1413 m_layoutTimer
->stop();
1416 if (m_activeTransactions
> 0) {
1417 if (hint
== NoAnimation
) {
1418 // As soon as at least one property change should be done without animation,
1419 // the whole transaction will be marked as not animated.
1420 m_endTransactionAnimationHint
= NoAnimation
;
1425 if (!m_model
|| m_model
->count() < 0) {
1429 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1430 if (firstVisibleIndex
< 0) {
1431 emitOffsetChanges();
1435 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1436 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1437 // is still shown if the maximum offset got decreased.
1438 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1439 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1440 if (scrollOffset() > maxOffsetToShowFullRange
) {
1441 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1442 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1445 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1447 int firstSibblingIndex
= -1;
1448 int lastSibblingIndex
= -1;
1449 const bool supportsExpanding
= supportsItemExpanding();
1451 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1453 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1454 // instances from invisible items are reused. If no reusable items are
1455 // found then new KItemListWidget instances get created.
1456 const bool animate
= (hint
== Animation
);
1457 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1458 bool applyNewPos
= true;
1459 bool wasHidden
= false;
1461 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1462 const QPointF newPos
= itemBounds
.topLeft();
1463 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1466 if (!reusableItems
.isEmpty()) {
1467 // Reuse a KItemListWidget instance from an invisible item
1468 const int oldIndex
= reusableItems
.takeLast();
1469 widget
= m_visibleItems
.value(oldIndex
);
1470 setWidgetIndex(widget
, i
);
1471 updateWidgetProperties(widget
, i
);
1472 initializeItemListWidget(widget
);
1474 // No reusable KItemListWidget instance is available, create a new one
1475 widget
= createWidget(i
);
1477 widget
->resize(itemBounds
.size());
1479 if (animate
&& changedCount
< 0) {
1480 // Items have been deleted, move the created item to the
1481 // imaginary old position. They will get animated to the new position
1483 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1484 if (itemRect
.isEmpty()) {
1485 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1486 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1487 widget
->setPos(invisibleOldPos
);
1489 widget
->setPos(itemRect
.topLeft());
1491 applyNewPos
= false;
1494 if (supportsExpanding
&& changedCount
== 0) {
1495 if (firstSibblingIndex
< 0) {
1496 firstSibblingIndex
= i
;
1498 lastSibblingIndex
= i
;
1503 const bool itemsRemoved
= (changedCount
< 0);
1504 const bool itemsInserted
= (changedCount
> 0);
1505 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1506 // The item is located after the removed items. Animate the moving of the position.
1507 applyNewPos
= !moveWidget(widget
, newPos
);
1508 } else if (itemsInserted
&& i
>= changedIndex
) {
1509 // The item is located after the first inserted item
1510 if (i
<= changedIndex
+ changedCount
- 1) {
1511 // The item is an inserted item. Animate the appearing of the item.
1512 // For performance reasons no animation is done when changedCount is equal
1513 // to all available items.
1514 if (changedCount
< m_model
->count()) {
1515 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1517 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1518 // The item was already there before, so animate the moving of the position.
1519 // No moving animation is done if the item is animated by a create animation: This
1520 // prevents a "move animation mess" when inserting several ranges in parallel.
1521 applyNewPos
= !moveWidget(widget
, newPos
);
1523 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1524 // The size of the view might have been changed. Animate the moving of the position.
1525 applyNewPos
= !moveWidget(widget
, newPos
);
1528 m_animation
->stop(widget
);
1532 widget
->setPos(newPos
);
1535 Q_ASSERT(widget
->index() == i
);
1536 widget
->setVisible(true);
1538 if (widget
->size() != itemBounds
.size()) {
1539 // Resize the widget for the item to the changed size.
1541 // If a dynamic item size is used then no animation is done in the direction
1542 // of the dynamic size.
1543 if (m_itemSize
.width() <= 0) {
1544 // The width is dynamic, apply the new width without animation.
1545 widget
->resize(itemBounds
.width(), widget
->size().height());
1546 } else if (m_itemSize
.height() <= 0) {
1547 // The height is dynamic, apply the new height without animation.
1548 widget
->resize(widget
->size().width(), itemBounds
.height());
1550 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1552 widget
->resize(itemBounds
.size());
1556 // Updating the cell-information must be done as last step: The decision whether the
1557 // moving-animation should be started at all is based on the previous cell-information.
1558 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1559 m_visibleCells
.insert(i
, cell
);
1562 // Delete invisible KItemListWidget instances that have not been reused
1563 foreach (int index
, reusableItems
) {
1564 recycleWidget(m_visibleItems
.value(index
));
1567 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1568 Q_ASSERT(lastSibblingIndex
>= 0);
1569 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1573 // Update the layout of all visible group headers
1574 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1575 while (it
.hasNext()) {
1577 updateGroupHeaderLayout(it
.key());
1581 emitOffsetChanges();
1584 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1585 int lastVisibleIndex
,
1586 LayoutAnimationHint hint
)
1588 // Determine all items that are completely invisible and might be
1589 // reused for items that just got (at least partly) visible. If the
1590 // animation hint is set to 'Animation' items that do e.g. an animated
1591 // moving of their position are not marked as invisible: This assures
1592 // that a scrolling inside the view can be done without breaking an animation.
1596 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1597 while (it
.hasNext()) {
1600 KItemListWidget
* widget
= it
.value();
1601 const int index
= widget
->index();
1602 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1605 if (m_animation
->isStarted(widget
)) {
1606 if (hint
== NoAnimation
) {
1607 // Stopping the animation will call KItemListView::slotAnimationFinished()
1608 // and the widget will be recycled if necessary there.
1609 m_animation
->stop(widget
);
1612 widget
->setVisible(false);
1613 items
.append(index
);
1616 recycleGroupHeaderForWidget(widget
);
1625 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1627 if (widget
->pos() == newPos
) {
1631 bool startMovingAnim
= false;
1633 // When having a grid the moving-animation should only be started, if it is done within
1634 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1635 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1636 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1637 const int index
= widget
->index();
1638 const Cell cell
= m_visibleCells
.value(index
);
1639 if (cell
.column
>= 0 && cell
.row
>= 0) {
1640 if (scrollOrientation() == Qt::Vertical
) {
1641 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1643 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1647 if (startMovingAnim
) {
1648 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1652 m_animation
->stop(widget
);
1653 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1657 void KItemListView::emitOffsetChanges()
1659 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1660 if (m_oldScrollOffset
!= newScrollOffset
) {
1661 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1662 m_oldScrollOffset
= newScrollOffset
;
1665 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1666 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1667 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1668 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1671 const qreal newItemOffset
= m_layouter
->itemOffset();
1672 if (m_oldItemOffset
!= newItemOffset
) {
1673 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1674 m_oldItemOffset
= newItemOffset
;
1677 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1678 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1679 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1680 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1684 KItemListWidget
* KItemListView::createWidget(int index
)
1686 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1687 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1689 m_visibleItems
.insert(index
, widget
);
1690 m_visibleCells
.insert(index
, Cell());
1691 updateWidgetProperties(widget
, index
);
1692 initializeItemListWidget(widget
);
1696 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1699 recycleGroupHeaderForWidget(widget
);
1702 const int index
= widget
->index();
1703 m_visibleItems
.remove(index
);
1704 m_visibleCells
.remove(index
);
1706 m_widgetCreator
->recycle(widget
);
1709 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1711 const int oldIndex
= widget
->index();
1712 m_visibleItems
.remove(oldIndex
);
1713 m_visibleCells
.remove(oldIndex
);
1715 m_visibleItems
.insert(index
, widget
);
1716 m_visibleCells
.insert(index
, Cell());
1718 widget
->setIndex(index
);
1721 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1723 const int oldIndex
= widget
->index();
1724 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1726 setWidgetIndex(widget
, index
);
1728 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1729 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1730 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1731 (!vertical
&& oldCell
.column
== newCell
.column
);
1733 m_visibleCells
.insert(index
, newCell
);
1737 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1740 case LayouterSize
: m_layouter
->setSize(size
); break;
1741 case ItemSize
: m_layouter
->setItemSize(size
); break;
1746 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1748 widget
->setVisibleRoles(m_visibleRoles
);
1749 updateWidgetColumnWidths(widget
);
1750 widget
->setStyleOption(m_styleOption
);
1752 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1753 widget
->setCurrent(index
== selectionManager
->currentItem());
1754 widget
->setSelected(selectionManager
->isSelected(index
));
1755 widget
->setHovered(false);
1756 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1757 widget
->setIndex(index
);
1758 widget
->setData(m_model
->data(index
));
1759 widget
->setSiblingsInformation(QBitArray());
1760 updateAlternateBackgroundForWidget(widget
);
1763 updateGroupHeaderForWidget(widget
);
1767 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1769 Q_ASSERT(m_grouped
);
1771 const int index
= widget
->index();
1772 if (!m_layouter
->isFirstGroupItem(index
)) {
1773 // The widget does not represent the first item of a group
1774 // and hence requires no header
1775 recycleGroupHeaderForWidget(widget
);
1779 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1780 if (groups
.isEmpty()) {
1784 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1786 groupHeader
= m_groupHeaderCreator
->create(this);
1787 groupHeader
->setParentItem(widget
);
1788 m_visibleGroups
.insert(widget
, groupHeader
);
1789 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1791 Q_ASSERT(groupHeader
->parentItem() == widget
);
1793 const int groupIndex
= groupIndexForItem(index
);
1794 Q_ASSERT(groupIndex
>= 0);
1795 groupHeader
->setData(groups
.at(groupIndex
).second
);
1796 groupHeader
->setRole(model()->sortRole());
1797 groupHeader
->setStyleOption(m_styleOption
);
1798 groupHeader
->setScrollOrientation(scrollOrientation());
1799 groupHeader
->setItemIndex(index
);
1801 groupHeader
->show();
1804 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1806 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1807 Q_ASSERT(groupHeader
);
1809 const int index
= widget
->index();
1810 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1811 const QRectF itemRect
= m_layouter
->itemRect(index
);
1813 // The group-header is a child of the itemlist widget. Translate the
1814 // group header position to the relative position.
1815 if (scrollOrientation() == Qt::Vertical
) {
1816 // In the vertical scroll orientation the group header should always span
1817 // the whole width no matter which temporary position the parent widget
1818 // has. In this case the x-position and width will be adjusted manually.
1819 groupHeader
->setPos(-widget
->x(), -groupHeaderRect
.height());
1820 groupHeader
->resize(size().width(), groupHeaderRect
.size().height());
1822 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1823 groupHeader
->resize(groupHeaderRect
.size());
1827 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1829 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1831 header
->setParentItem(0);
1832 m_groupHeaderCreator
->recycle(header
);
1833 m_visibleGroups
.remove(widget
);
1834 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1838 void KItemListView::updateVisibleGroupHeaders()
1840 Q_ASSERT(m_grouped
);
1841 m_layouter
->markAsDirty();
1843 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1844 while (it
.hasNext()) {
1846 updateGroupHeaderForWidget(it
.value());
1850 int KItemListView::groupIndexForItem(int index
) const
1852 Q_ASSERT(m_grouped
);
1854 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1855 if (groups
.isEmpty()) {
1860 int max
= groups
.count() - 1;
1863 mid
= (min
+ max
) / 2;
1864 if (index
> groups
[mid
].first
) {
1869 } while (groups
[mid
].first
!= index
&& min
<= max
);
1872 while (groups
[mid
].first
> index
&& mid
> 0) {
1880 void KItemListView::updateAlternateBackgrounds()
1882 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1883 while (it
.hasNext()) {
1885 updateAlternateBackgroundForWidget(it
.value());
1889 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1891 bool enabled
= useAlternateBackgrounds();
1893 const int index
= widget
->index();
1894 enabled
= (index
& 0x1) > 0;
1896 const int groupIndex
= groupIndexForItem(index
);
1897 if (groupIndex
>= 0) {
1898 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1899 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1900 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1901 enabled
= (relativeIndex
& 0x1) > 0;
1905 widget
->setAlternateBackground(enabled
);
1908 bool KItemListView::useAlternateBackgrounds() const
1910 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
1913 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
1915 QElapsedTimer timer
;
1918 QHash
<QByteArray
, qreal
> widths
;
1920 // Calculate the minimum width for each column that is required
1921 // to show the headline unclipped.
1922 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
1923 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
1924 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
1925 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
1926 const QString headerText
= m_model
->roleDescription(visibleRole
);
1927 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
1928 widths
.insert(visibleRole
, headerWidth
);
1931 // Calculate the preferred column withs for each item and ignore values
1932 // smaller than the width for showing the headline unclipped.
1933 int calculatedItemCount
= 0;
1934 bool maxTimeExceeded
= false;
1935 foreach (const KItemRange
& itemRange
, itemRanges
) {
1936 const int startIndex
= itemRange
.index
;
1937 const int endIndex
= startIndex
+ itemRange
.count
- 1;
1939 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
1940 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
1941 qreal maxWidth
= widths
.value(visibleRole
, 0);
1942 const qreal width
= m_widgetCreator
->preferredRoleColumnWidth(visibleRole
, i
, this);
1943 maxWidth
= qMax(width
, maxWidth
);
1944 widths
.insert(visibleRole
, maxWidth
);
1947 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
1948 // When having several thousands of items calculating the sizes can get
1949 // very expensive. We accept a possibly too small role-size in favour
1950 // of having no blocking user interface.
1951 maxTimeExceeded
= true;
1954 ++calculatedItemCount
;
1956 if (maxTimeExceeded
) {
1964 void KItemListView::applyColumnWidthsFromHeader()
1966 // Apply the new size to the layouter
1967 const qreal requiredWidth
= columnWidthsSum();
1968 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
1969 m_itemSize
.height());
1970 m_layouter
->setItemSize(dynamicItemSize
);
1972 // Update the role sizes for all visible widgets
1973 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1974 while (it
.hasNext()) {
1976 updateWidgetColumnWidths(it
.value());
1980 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
1982 foreach (const QByteArray
& role
, m_visibleRoles
) {
1983 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
1987 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
1989 Q_ASSERT(m_itemSize
.isEmpty());
1990 const int itemCount
= m_model
->count();
1991 int rangesItemCount
= 0;
1992 foreach (const KItemRange
& range
, itemRanges
) {
1993 rangesItemCount
+= range
.count
;
1996 if (itemCount
== rangesItemCount
) {
1997 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
1998 foreach (const QByteArray
& role
, m_visibleRoles
) {
1999 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2002 // Only a sub range of the roles need to be determined.
2003 // The chances are good that the widths of the sub ranges
2004 // already fit into the available widths and hence no
2005 // expensive update might be required.
2006 bool changed
= false;
2008 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2009 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2010 while (it
.hasNext()) {
2012 const QByteArray
& role
= it
.key();
2013 const qreal updatedWidth
= it
.value();
2014 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2015 if (updatedWidth
> currentWidth
) {
2016 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2022 // All the updated sizes are smaller than the current sizes and no change
2023 // of the stretched roles-widths is required
2028 if (m_headerWidget
->automaticColumnResizing()) {
2029 applyAutomaticColumnWidths();
2033 void KItemListView::updatePreferredColumnWidths()
2036 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2040 void KItemListView::applyAutomaticColumnWidths()
2042 Q_ASSERT(m_itemSize
.isEmpty());
2043 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2045 // Calculate the maximum size of an item by considering the
2046 // visible role sizes and apply them to the layouter. If the
2047 // size does not use the available view-size the size of the
2048 // first role will get stretched.
2050 foreach (const QByteArray
& role
, m_visibleRoles
) {
2051 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2052 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2055 const QByteArray firstRole
= m_visibleRoles
.first();
2056 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2057 QSizeF dynamicItemSize
= m_itemSize
;
2059 qreal requiredWidth
= columnWidthsSum();
2060 const qreal availableWidth
= size().width();
2061 if (requiredWidth
< availableWidth
) {
2062 // Stretch the first column to use the whole remaining width
2063 firstColumnWidth
+= availableWidth
- requiredWidth
;
2064 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2065 } else if (requiredWidth
> availableWidth
) {
2066 // Shrink the first column to be able to show as much other
2067 // columns as possible
2068 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2070 // TODO: A proper calculation of the minimum width depends on the implementation
2071 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2073 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2074 if (shrinkedFirstColumnWidth
< minWidth
) {
2075 shrinkedFirstColumnWidth
= minWidth
;
2078 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2079 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2082 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2084 m_layouter
->setItemSize(dynamicItemSize
);
2086 // Update the role sizes for all visible widgets
2087 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2088 while (it
.hasNext()) {
2090 updateWidgetColumnWidths(it
.value());
2094 qreal
KItemListView::columnWidthsSum() const
2096 qreal widthsSum
= 0;
2097 foreach (const QByteArray
& role
, m_visibleRoles
) {
2098 widthsSum
+= m_headerWidget
->columnWidth(role
);
2103 QRectF
KItemListView::headerBoundaries() const
2105 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2108 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2109 const QSizeF
& newItemSize
,
2110 const QSizeF
& newItemMargin
) const
2112 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2116 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2117 const qreal itemWidth
= m_layouter
->itemSize().width();
2118 if (itemWidth
> 0) {
2119 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2120 newItemSize
.width(),
2121 newItemMargin
.width());
2122 if (m_model
->count() > newColumnCount
) {
2123 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2125 m_layouter
->itemMargin().width());
2126 return oldColumnCount
!= newColumnCount
;
2130 const qreal itemHeight
= m_layouter
->itemSize().height();
2131 if (itemHeight
> 0) {
2132 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2133 newItemSize
.height(),
2134 newItemMargin
.height());
2135 if (m_model
->count() > newRowCount
) {
2136 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2138 m_layouter
->itemMargin().height());
2139 return oldRowCount
!= newRowCount
;
2147 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2149 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2153 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2154 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2155 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2156 // Only animate if up to 2/3 of a row or column are inserted or removed
2157 return changedItemCount
<= maximum
* 2 / 3;
2161 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2163 const QSizeF oldSize
= m_layouter
->size();
2165 m_layouter
->setSize(size
);
2166 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2167 m_layouter
->setSize(oldSize
);
2169 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2170 : maxOffset
> size
.width();
2173 void KItemListView::updateGroupHeaderHeight()
2175 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2176 qreal groupHeaderMargin
= 0;
2178 if (scrollOrientation() == Qt::Horizontal
) {
2179 // The vertical margin above and below the header should be
2180 // equal to the horizontal margin, not the vertical margin
2181 // from m_styleOption.
2182 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2183 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2184 } else if (m_itemSize
.isEmpty()){
2185 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2186 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2188 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2189 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2191 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2192 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2194 updateVisibleGroupHeaders();
2197 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2199 if (!supportsItemExpanding() || !m_model
) {
2203 if (firstIndex
< 0 || lastIndex
< 0) {
2204 firstIndex
= m_layouter
->firstVisibleIndex();
2205 lastIndex
= m_layouter
->lastVisibleIndex();
2207 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2208 lastIndex
>= m_layouter
->firstVisibleIndex());
2209 if (!isRangeVisible
) {
2214 int previousParents
= 0;
2215 QBitArray previousSiblings
;
2217 // The rootIndex describes the first index where the siblings get
2218 // calculated from. For the calculation the upper most parent item
2219 // is required. For performance reasons it is checked first whether
2220 // the visible items before or after the current range already
2221 // contain a siblings information which can be used as base.
2222 int rootIndex
= firstIndex
;
2224 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2226 // There is no visible widget before the range, check whether there
2227 // is one after the range:
2228 widget
= m_visibleItems
.value(lastIndex
+ 1);
2230 // The sibling information of the widget may only be used if
2231 // all items of the range have the same number of parents.
2232 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2233 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2234 if (m_model
->expandedParentsCount(i
) != parents
) {
2243 // Performance optimization: Use the sibling information of the visible
2244 // widget beside the given range.
2245 previousSiblings
= widget
->siblingsInformation();
2246 if (previousSiblings
.isEmpty()) {
2249 previousParents
= previousSiblings
.count() - 1;
2250 previousSiblings
.truncate(previousParents
);
2252 // Potentially slow path: Go back to the upper most parent of firstIndex
2253 // to be able to calculate the initial value for the siblings.
2254 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2259 Q_ASSERT(previousParents
>= 0);
2260 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2261 // Update the parent-siblings in case if the current item represents
2262 // a child or an upper parent.
2263 const int currentParents
= m_model
->expandedParentsCount(i
);
2264 Q_ASSERT(currentParents
>= 0);
2265 if (previousParents
< currentParents
) {
2266 previousParents
= currentParents
;
2267 previousSiblings
.resize(currentParents
);
2268 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2269 } else if (previousParents
> currentParents
) {
2270 previousParents
= currentParents
;
2271 previousSiblings
.truncate(currentParents
);
2274 if (i
>= firstIndex
) {
2275 // The index represents a visible item. Apply the parent-siblings
2276 // and update the sibling of the current item.
2277 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2282 QBitArray siblings
= previousSiblings
;
2283 siblings
.resize(siblings
.count() + 1);
2284 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2286 widget
->setSiblingsInformation(siblings
);
2291 bool KItemListView::hasSiblingSuccessor(int index
) const
2293 bool hasSuccessor
= false;
2294 const int parentsCount
= m_model
->expandedParentsCount(index
);
2295 int successorIndex
= index
+ 1;
2297 // Search the next sibling
2298 const int itemCount
= m_model
->count();
2299 while (successorIndex
< itemCount
) {
2300 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2301 if (currentParentsCount
== parentsCount
) {
2302 hasSuccessor
= true;
2304 } else if (currentParentsCount
< parentsCount
) {
2310 if (m_grouped
&& hasSuccessor
) {
2311 // If the sibling is part of another group, don't mark it as
2312 // successor as the group header is between the sibling connections.
2313 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2314 if (m_layouter
->isFirstGroupItem(i
)) {
2315 hasSuccessor
= false;
2321 return hasSuccessor
;
2324 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2328 const int minSpeed
= 4;
2329 const int maxSpeed
= 128;
2330 const int speedLimiter
= 96;
2331 const int autoScrollBorder
= 64;
2333 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2334 // This assures that the autoscrolling speed grows gradually.
2335 const int incLimiter
= 1;
2337 if (pos
< autoScrollBorder
) {
2338 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2339 inc
= qMax(inc
, -maxSpeed
);
2340 inc
= qMax(inc
, oldInc
- incLimiter
);
2341 } else if (pos
> range
- autoScrollBorder
) {
2342 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2343 inc
= qMin(inc
, maxSpeed
);
2344 inc
= qMin(inc
, oldInc
+ incLimiter
);
2350 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2352 const qreal availableSize
= size
- itemMargin
;
2353 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2359 KItemListCreatorBase::~KItemListCreatorBase()
2361 qDeleteAll(m_recycleableWidgets
);
2362 qDeleteAll(m_createdWidgets
);
2365 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2367 m_createdWidgets
.insert(widget
);
2370 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2372 Q_ASSERT(m_createdWidgets
.contains(widget
));
2373 m_createdWidgets
.remove(widget
);
2375 if (m_recycleableWidgets
.count() < 100) {
2376 m_recycleableWidgets
.append(widget
);
2377 widget
->setVisible(false);
2383 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2385 if (m_recycleableWidgets
.isEmpty()) {
2389 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2390 m_createdWidgets
.insert(widget
);
2394 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2398 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2400 widget
->setParentItem(0);
2401 widget
->setOpacity(1.0);
2402 pushRecycleableWidget(widget
);
2405 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2409 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2411 header
->setOpacity(1.0);
2412 pushRecycleableWidget(header
);
2415 #include "kitemlistview.moc"