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"
26 #include "kitemlistcontroller.h"
27 #include "kitemlistheader.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistwidget.h"
31 #include "private/kitemlistheaderwidget.h"
32 #include "private/kitemlistrubberband.h"
33 #include "private/kitemlistsizehintresolver.h"
34 #include "private/kitemlistviewlayouter.h"
35 #include "private/kitemlistviewanimation.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),
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 // The group headers are children of the widgets created by
116 // widgetCreator(). So it is mandatory to delete the group headers
118 delete m_groupHeaderCreator
;
119 m_groupHeaderCreator
= 0;
121 delete m_widgetCreator
;
124 delete m_sizeHintResolver
;
125 m_sizeHintResolver
= 0;
128 void KItemListView::setScrollOffset(qreal offset
)
134 const qreal previousOffset
= m_layouter
->scrollOffset();
135 if (offset
== previousOffset
) {
139 m_layouter
->setScrollOffset(offset
);
140 m_animation
->setScrollOffset(offset
);
142 // Don't check whether the m_layoutTimer is active: Changing the
143 // scroll offset must always trigger a synchronous layout, otherwise
144 // the smooth-scrolling might get jerky.
145 doLayout(NoAnimation
);
146 onScrollOffsetChanged(offset
, previousOffset
);
149 qreal
KItemListView::scrollOffset() const
151 return m_layouter
->scrollOffset();
154 qreal
KItemListView::maximumScrollOffset() const
156 return m_layouter
->maximumScrollOffset();
159 void KItemListView::setItemOffset(qreal offset
)
161 if (m_layouter
->itemOffset() == offset
) {
165 m_layouter
->setItemOffset(offset
);
166 if (m_headerWidget
->isVisible()) {
167 m_headerWidget
->setOffset(offset
);
170 // Don't check whether the m_layoutTimer is active: Changing the
171 // item offset must always trigger a synchronous layout, otherwise
172 // the smooth-scrolling might get jerky.
173 doLayout(NoAnimation
);
176 qreal
KItemListView::itemOffset() const
178 return m_layouter
->itemOffset();
181 qreal
KItemListView::maximumItemOffset() const
183 return m_layouter
->maximumItemOffset();
186 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
188 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
189 m_visibleRoles
= roles
;
190 onVisibleRolesChanged(roles
, previousRoles
);
192 m_sizeHintResolver
->clearCache();
193 m_layouter
->markAsDirty();
195 if (m_itemSize
.isEmpty()) {
196 m_headerWidget
->setColumns(roles
);
197 updatePreferredColumnWidths();
198 if (!m_headerWidget
->automaticColumnResizing()) {
199 // The column-width of new roles are still 0. Apply the preferred
200 // column-width as default with.
201 foreach (const QByteArray
& role
, m_visibleRoles
) {
202 if (m_headerWidget
->columnWidth(role
) == 0) {
203 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
204 m_headerWidget
->setColumnWidth(role
, width
);
208 applyColumnWidthsFromHeader();
212 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
213 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
214 (roles
.count() <= 1 && previousRoles
.count() > 1));
216 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
217 while (it
.hasNext()) {
219 KItemListWidget
* widget
= it
.value();
220 widget
->setVisibleRoles(roles
);
221 if (alternateBackgroundsChanged
) {
222 updateAlternateBackgroundForWidget(widget
);
226 doLayout(NoAnimation
);
229 QList
<QByteArray
> KItemListView::visibleRoles() const
231 return m_visibleRoles
;
234 void KItemListView::setAutoScroll(bool enabled
)
236 if (enabled
&& !m_autoScrollTimer
) {
237 m_autoScrollTimer
= new QTimer(this);
238 m_autoScrollTimer
->setSingleShot(true);
239 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
240 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
241 } else if (!enabled
&& m_autoScrollTimer
) {
242 delete m_autoScrollTimer
;
243 m_autoScrollTimer
= 0;
247 bool KItemListView::autoScroll() const
249 return m_autoScrollTimer
!= 0;
252 void KItemListView::setEnabledSelectionToggles(bool enabled
)
254 if (m_enabledSelectionToggles
!= enabled
) {
255 m_enabledSelectionToggles
= enabled
;
257 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
258 while (it
.hasNext()) {
260 it
.value()->setEnabledSelectionToggle(enabled
);
265 bool KItemListView::enabledSelectionToggles() const
267 return m_enabledSelectionToggles
;
270 KItemListController
* KItemListView::controller() const
275 KItemModelBase
* KItemListView::model() const
280 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
282 if (m_widgetCreator
) {
283 delete m_widgetCreator
;
285 m_widgetCreator
= widgetCreator
;
288 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
290 if (!m_widgetCreator
) {
291 m_widgetCreator
= defaultWidgetCreator();
293 return m_widgetCreator
;
296 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
298 if (m_groupHeaderCreator
) {
299 delete m_groupHeaderCreator
;
301 m_groupHeaderCreator
= groupHeaderCreator
;
304 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
306 if (!m_groupHeaderCreator
) {
307 m_groupHeaderCreator
= defaultGroupHeaderCreator();
309 return m_groupHeaderCreator
;
312 QSizeF
KItemListView::itemSize() const
317 const KItemListStyleOption
& KItemListView::styleOption() const
319 return m_styleOption
;
322 void KItemListView::setGeometry(const QRectF
& rect
)
324 QGraphicsWidget::setGeometry(rect
);
330 const QSizeF newSize
= rect
.size();
331 if (m_itemSize
.isEmpty()) {
332 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
333 if (m_headerWidget
->automaticColumnResizing()) {
334 applyAutomaticColumnWidths();
336 const qreal requiredWidth
= columnWidthsSum();
337 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
338 m_itemSize
.height());
339 m_layouter
->setItemSize(dynamicItemSize
);
342 // Triggering a synchronous layout is fine from a performance point of view,
343 // as with dynamic item sizes no moving animation must be done.
344 m_layouter
->setSize(newSize
);
345 doLayout(NoAnimation
);
347 const bool animate
= !changesItemGridLayout(newSize
,
348 m_layouter
->itemSize(),
349 m_layouter
->itemMargin());
350 m_layouter
->setSize(newSize
);
353 // Trigger an asynchronous relayout with m_layoutTimer to prevent
354 // performance bottlenecks. If the timer is exceeded, an animated layout
355 // will be triggered.
356 if (!m_layoutTimer
->isActive()) {
357 m_layoutTimer
->start();
360 m_layoutTimer
->stop();
361 doLayout(NoAnimation
);
366 int KItemListView::itemAt(const QPointF
& pos
) const
368 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
369 while (it
.hasNext()) {
372 const KItemListWidget
* widget
= it
.value();
373 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
374 if (widget
->contains(mappedPos
)) {
382 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
384 if (!m_enabledSelectionToggles
) {
388 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
390 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
391 if (!selectionToggleRect
.isEmpty()) {
392 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
393 return selectionToggleRect
.contains(mappedPos
);
399 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
401 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
403 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
404 if (!expansionToggleRect
.isEmpty()) {
405 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
406 return expansionToggleRect
.contains(mappedPos
);
412 int KItemListView::firstVisibleIndex() const
414 return m_layouter
->firstVisibleIndex();
417 int KItemListView::lastVisibleIndex() const
419 return m_layouter
->lastVisibleIndex();
422 QSizeF
KItemListView::itemSizeHint(int index
) const
424 return widgetCreator()->itemSizeHint(index
, this);
427 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
429 if (m_supportsItemExpanding
!= supportsExpanding
) {
430 m_supportsItemExpanding
= supportsExpanding
;
431 updateSiblingsInformation();
432 onSupportsItemExpandingChanged(supportsExpanding
);
436 bool KItemListView::supportsItemExpanding() const
438 return m_supportsItemExpanding
;
441 QRectF
KItemListView::itemRect(int index
) const
443 return m_layouter
->itemRect(index
);
446 QRectF
KItemListView::itemContextRect(int index
) const
450 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
452 contextRect
= widget
->iconRect() | widget
->textRect();
453 contextRect
.translate(itemRect(index
).topLeft());
459 void KItemListView::scrollToItem(int index
)
461 QRectF viewGeometry
= geometry();
462 if (m_headerWidget
->isVisible()) {
463 const qreal headerHeight
= m_headerWidget
->size().height();
464 viewGeometry
.adjust(0, headerHeight
, 0, 0);
466 const QRectF currentRect
= itemRect(index
);
468 if (!viewGeometry
.contains(currentRect
)) {
469 qreal newOffset
= scrollOffset();
470 if (scrollOrientation() == Qt::Vertical
) {
471 if (currentRect
.top() < viewGeometry
.top()) {
472 newOffset
+= currentRect
.top() - viewGeometry
.top();
473 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
474 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
477 if (currentRect
.left() < viewGeometry
.left()) {
478 newOffset
+= currentRect
.left() - viewGeometry
.left();
479 } else if (currentRect
.right() > viewGeometry
.right()) {
480 newOffset
+= currentRect
.right() - viewGeometry
.right();
484 if (newOffset
!= scrollOffset()) {
485 emit
scrollTo(newOffset
);
490 void KItemListView::beginTransaction()
492 ++m_activeTransactions
;
493 if (m_activeTransactions
== 1) {
494 onTransactionBegin();
498 void KItemListView::endTransaction()
500 --m_activeTransactions
;
501 if (m_activeTransactions
< 0) {
502 m_activeTransactions
= 0;
503 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
506 if (m_activeTransactions
== 0) {
508 doLayout(m_endTransactionAnimationHint
);
509 m_endTransactionAnimationHint
= Animation
;
513 bool KItemListView::isTransactionActive() const
515 return m_activeTransactions
> 0;
518 void KItemListView::setHeaderVisible(bool visible
)
520 if (visible
&& !m_headerWidget
->isVisible()) {
521 QStyleOptionHeader option
;
522 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
525 m_headerWidget
->setPos(0, 0);
526 m_headerWidget
->resize(size().width(), headerSize
.height());
527 m_headerWidget
->setModel(m_model
);
528 m_headerWidget
->setColumns(m_visibleRoles
);
529 m_headerWidget
->setZValue(1);
531 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
532 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
533 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
534 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
535 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
536 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
537 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
538 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
540 m_layouter
->setHeaderHeight(headerSize
.height());
541 m_headerWidget
->setVisible(true);
542 } else if (!visible
&& m_headerWidget
->isVisible()) {
543 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
544 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
545 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
546 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
547 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
548 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
549 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
550 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
552 m_layouter
->setHeaderHeight(0);
553 m_headerWidget
->setVisible(false);
557 bool KItemListView::isHeaderVisible() const
559 return m_headerWidget
->isVisible();
562 KItemListHeader
* KItemListView::header() const
567 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
573 void KItemListView::editRole(int index
, const QByteArray
& role
)
575 KItemListWidget
* widget
= m_visibleItems
.value(index
);
576 if (!widget
|| m_editingRole
) {
580 m_editingRole
= true;
581 widget
->setEditedRole(role
);
583 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
584 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
585 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
586 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
589 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
591 QGraphicsWidget::paint(painter
, option
, widget
);
593 if (m_rubberBand
->isActive()) {
594 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
595 m_rubberBand
->endPosition()).normalized();
597 const QPointF topLeft
= rubberBandRect
.topLeft();
598 if (scrollOrientation() == Qt::Vertical
) {
599 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
601 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
604 QStyleOptionRubberBand opt
;
605 opt
.initFrom(widget
);
606 opt
.shape
= QRubberBand::Rectangle
;
608 opt
.rect
= rubberBandRect
.toRect();
609 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
613 void KItemListView::setItemSize(const QSizeF
& size
)
615 const QSizeF previousSize
= m_itemSize
;
616 if (size
== previousSize
) {
620 // Skip animations when the number of rows or columns
621 // are changed in the grid layout. Although the animation
622 // engine can handle this usecase, it looks obtrusive.
623 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
625 m_layouter
->itemMargin());
627 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
628 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
629 (!m_itemSize
.isEmpty() && size
.isEmpty()));
633 if (alternateBackgroundsChanged
) {
634 // For an empty item size alternate backgrounds are drawn if more than
635 // one role is shown. Assure that the backgrounds for visible items are
636 // updated when changing the size in this context.
637 updateAlternateBackgrounds();
640 if (size
.isEmpty()) {
641 if (m_headerWidget
->automaticColumnResizing()) {
642 updatePreferredColumnWidths();
644 // Only apply the changed height and respect the header widths
646 const qreal currentWidth
= m_layouter
->itemSize().width();
647 const QSizeF
newSize(currentWidth
, size
.height());
648 m_layouter
->setItemSize(newSize
);
651 m_layouter
->setItemSize(size
);
654 m_sizeHintResolver
->clearCache();
655 doLayout(animate
? Animation
: NoAnimation
);
656 onItemSizeChanged(size
, previousSize
);
659 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
661 const KItemListStyleOption previousOption
= m_styleOption
;
662 m_styleOption
= option
;
665 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
666 if (margin
!= m_layouter
->itemMargin()) {
667 // Skip animations when the number of rows or columns
668 // are changed in the grid layout. Although the animation
669 // engine can handle this usecase, it looks obtrusive.
670 animate
= !changesItemGridLayout(m_layouter
->size(),
671 m_layouter
->itemSize(),
673 m_layouter
->setItemMargin(margin
);
677 updateGroupHeaderHeight();
680 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
681 // Animating a change of the maximum text size just results in expensive
682 // temporary eliding and clipping operations and does not look good visually.
686 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
687 while (it
.hasNext()) {
689 it
.value()->setStyleOption(option
);
692 m_sizeHintResolver
->clearCache();
693 m_layouter
->markAsDirty();
694 doLayout(animate
? Animation
: NoAnimation
);
696 if (m_itemSize
.isEmpty()) {
697 updatePreferredColumnWidths();
700 onStyleOptionChanged(option
, previousOption
);
703 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
705 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
706 if (orientation
== previousOrientation
) {
710 m_layouter
->setScrollOrientation(orientation
);
711 m_animation
->setScrollOrientation(orientation
);
712 m_sizeHintResolver
->clearCache();
715 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
716 while (it
.hasNext()) {
718 it
.value()->setScrollOrientation(orientation
);
720 updateGroupHeaderHeight();
724 doLayout(NoAnimation
);
726 onScrollOrientationChanged(orientation
, previousOrientation
);
727 emit
scrollOrientationChanged(orientation
, previousOrientation
);
730 Qt::Orientation
KItemListView::scrollOrientation() const
732 return m_layouter
->scrollOrientation();
735 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
740 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
745 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
750 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
752 Q_UNUSED(changedRoles
);
756 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
762 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
768 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
774 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
780 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
786 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
792 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
798 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
800 Q_UNUSED(supportsExpanding
);
803 void KItemListView::onTransactionBegin()
807 void KItemListView::onTransactionEnd()
811 bool KItemListView::event(QEvent
* event
)
813 // Forward all events to the controller and handle them there
814 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
818 return QGraphicsWidget::event(event
);
821 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
823 m_mousePos
= transform().map(event
->pos());
827 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
829 QGraphicsWidget::mouseMoveEvent(event
);
831 m_mousePos
= transform().map(event
->pos());
832 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
833 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
837 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
839 event
->setAccepted(true);
843 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
845 QGraphicsWidget::dragMoveEvent(event
);
847 m_mousePos
= transform().map(event
->pos());
848 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
849 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
853 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
855 QGraphicsWidget::dragLeaveEvent(event
);
856 setAutoScroll(false);
859 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
861 QGraphicsWidget::dropEvent(event
);
862 setAutoScroll(false);
865 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
867 return m_visibleItems
.values();
870 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
872 if (m_itemSize
.isEmpty()) {
873 updatePreferredColumnWidths(itemRanges
);
876 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
877 if (hasMultipleRanges
) {
881 m_layouter
->markAsDirty();
883 int previouslyInsertedCount
= 0;
884 foreach (const KItemRange
& range
, itemRanges
) {
885 // range.index is related to the model before anything has been inserted.
886 // As in each loop the current item-range gets inserted the index must
887 // be increased by the already previously inserted items.
888 const int index
= range
.index
+ previouslyInsertedCount
;
889 const int count
= range
.count
;
890 if (index
< 0 || count
<= 0) {
891 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
894 previouslyInsertedCount
+= count
;
896 m_sizeHintResolver
->itemsInserted(index
, count
);
898 // Determine which visible items must be moved
899 QList
<int> itemsToMove
;
900 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
901 while (it
.hasNext()) {
903 const int visibleItemIndex
= it
.key();
904 if (visibleItemIndex
>= index
) {
905 itemsToMove
.append(visibleItemIndex
);
909 // Update the indexes of all KItemListWidget instances that are located
910 // after the inserted items. It is important to adjust the indexes in the order
911 // from the highest index to the lowest index to prevent overlaps when setting the new index.
913 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
914 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
916 const int newIndex
= widget
->index() + count
;
917 if (hasMultipleRanges
) {
918 setWidgetIndex(widget
, newIndex
);
920 // Try to animate the moving of the item
921 moveWidgetToIndex(widget
, newIndex
);
925 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
926 // Check whether a scrollbar is required to show the inserted items. In this case
927 // the size of the layouter will be decreased before calling doLayout(): This prevents
928 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
929 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
930 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
931 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
932 if (decreaseLayouterSize
) {
933 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
934 QSizeF layouterSize
= m_layouter
->size();
935 if (verticalScrollOrientation
) {
936 layouterSize
.rwidth() -= scrollBarExtent
;
938 layouterSize
.rheight() -= scrollBarExtent
;
940 m_layouter
->setSize(layouterSize
);
944 if (!hasMultipleRanges
) {
945 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
946 updateSiblingsInformation();
951 m_controller
->selectionManager()->itemsInserted(itemRanges
);
954 if (hasMultipleRanges
) {
956 // Important: Don't read any m_layouter-property inside the for-loop in case if
957 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
958 // updated in each loop-cycle and has only a consistent state after the loop.
959 Q_ASSERT(m_layouter
->isDirty());
961 m_endTransactionAnimationHint
= NoAnimation
;
964 updateSiblingsInformation();
967 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
968 // In case if items of the same group have been inserted before an item that
969 // currently represents the first item of the group, the group header of
970 // this item must be removed.
971 updateVisibleGroupHeaders();
974 if (useAlternateBackgrounds()) {
975 updateAlternateBackgrounds();
979 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
981 if (m_itemSize
.isEmpty()) {
982 // Don't pass the item-range: The preferred column-widths of
983 // all items must be adjusted when removing items.
984 updatePreferredColumnWidths();
987 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
988 if (hasMultipleRanges
) {
992 m_layouter
->markAsDirty();
994 int removedItemsCount
= 0;
995 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
996 removedItemsCount
+= itemRanges
[i
].count
;
999 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1000 const KItemRange
& range
= itemRanges
[i
];
1001 const int index
= range
.index
;
1002 const int count
= range
.count
;
1003 if (index
< 0 || count
<= 0) {
1004 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1008 m_sizeHintResolver
->itemsRemoved(index
, count
);
1010 const int firstRemovedIndex
= index
;
1011 const int lastRemovedIndex
= index
+ count
- 1;
1012 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1013 removedItemsCount
-= count
;
1015 // Remove all KItemListWidget instances that got deleted
1016 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1017 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1022 m_animation
->stop(widget
);
1023 // Stopping the animation might lead to recycling the widget if
1024 // it is invisible (see slotAnimationFinished()).
1025 // Check again whether it is still visible:
1026 if (!m_visibleItems
.contains(i
)) {
1030 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1031 // Remove the widget without animation
1032 recycleWidget(widget
);
1034 // Animate the removing of the items. Special case: When removing an item there
1035 // is no valid model index available anymore. For the
1036 // remove-animation the item gets removed from m_visibleItems but the widget
1037 // will stay alive until the animation has been finished and will
1038 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1039 m_visibleItems
.remove(i
);
1040 widget
->setIndex(-1);
1041 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1045 // Update the indexes of all KItemListWidget instances that are located
1046 // after the deleted items
1047 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1048 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1050 const int newIndex
= i
- count
;
1051 if (hasMultipleRanges
) {
1052 setWidgetIndex(widget
, newIndex
);
1054 // Try to animate the moving of the item
1055 moveWidgetToIndex(widget
, newIndex
);
1060 if (!hasMultipleRanges
) {
1061 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1062 // assumes an updated geometry. If items are removed during an active transaction,
1063 // the transaction will be temporary deactivated so that doLayout() triggers a
1064 // geometry update if necessary.
1065 const int activeTransactions
= m_activeTransactions
;
1066 m_activeTransactions
= 0;
1067 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1068 m_activeTransactions
= activeTransactions
;
1069 updateSiblingsInformation();
1074 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1077 if (hasMultipleRanges
) {
1079 // Important: Don't read any m_layouter-property inside the for-loop in case if
1080 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1081 // updated in each loop-cycle and has only a consistent state after the loop.
1082 Q_ASSERT(m_layouter
->isDirty());
1084 m_endTransactionAnimationHint
= NoAnimation
;
1086 updateSiblingsInformation();
1089 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1090 // In case if the first item of a group has been removed, the group header
1091 // must be applied to the next visible item.
1092 updateVisibleGroupHeaders();
1095 if (useAlternateBackgrounds()) {
1096 updateAlternateBackgrounds();
1100 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1102 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1103 m_layouter
->markAsDirty();
1106 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1109 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1110 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1112 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1113 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1115 updateWidgetProperties(widget
, index
);
1116 initializeItemListWidget(widget
);
1120 doLayout(NoAnimation
);
1121 updateSiblingsInformation();
1124 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1125 const QSet
<QByteArray
>& roles
)
1127 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1128 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1129 updatePreferredColumnWidths(itemRanges
);
1132 foreach (const KItemRange
& itemRange
, itemRanges
) {
1133 const int index
= itemRange
.index
;
1134 const int count
= itemRange
.count
;
1136 if (updateSizeHints
) {
1137 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1138 m_layouter
->markAsDirty();
1140 if (!m_layoutTimer
->isActive()) {
1141 m_layoutTimer
->start();
1145 // Apply the changed roles to the visible item-widgets
1146 const int lastIndex
= index
+ count
- 1;
1147 for (int i
= index
; i
<= lastIndex
; ++i
) {
1148 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1150 widget
->setData(m_model
->data(i
), roles
);
1154 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1155 // The sort-role has been changed which might result
1156 // in modified group headers
1157 updateVisibleGroupHeaders();
1158 doLayout(NoAnimation
);
1163 void KItemListView::slotGroupedSortingChanged(bool current
)
1165 m_grouped
= current
;
1166 m_layouter
->markAsDirty();
1169 updateGroupHeaderHeight();
1171 // Clear all visible headers
1172 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1173 while (it
.hasNext()) {
1175 recycleGroupHeaderForWidget(it
.key());
1177 Q_ASSERT(m_visibleGroups
.isEmpty());
1180 if (useAlternateBackgrounds()) {
1181 // Changing the group mode requires to update the alternate backgrounds
1182 // as with the enabled group mode the altering is done on base of the first
1184 updateAlternateBackgrounds();
1186 updateSiblingsInformation();
1187 doLayout(NoAnimation
);
1190 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1195 updateVisibleGroupHeaders();
1196 doLayout(NoAnimation
);
1200 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1205 updateVisibleGroupHeaders();
1206 doLayout(NoAnimation
);
1210 void KItemListView::slotCurrentChanged(int current
, int previous
)
1214 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1215 if (previousWidget
) {
1216 previousWidget
->setCurrent(false);
1219 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1220 if (currentWidget
) {
1221 currentWidget
->setCurrent(true);
1225 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1229 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1230 while (it
.hasNext()) {
1232 const int index
= it
.key();
1233 KItemListWidget
* widget
= it
.value();
1234 widget
->setSelected(current
.contains(index
));
1238 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1239 KItemListViewAnimation::AnimationType type
)
1241 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1242 Q_ASSERT(itemListWidget
);
1245 case KItemListViewAnimation::DeleteAnimation
: {
1246 // As we recycle the widget in this case it is important to assure that no
1247 // other animation has been started. This is a convention in KItemListView and
1248 // not a requirement defined by KItemListViewAnimation.
1249 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1251 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1252 // by m_visibleWidgets and must be deleted manually after the animation has
1254 recycleGroupHeaderForWidget(itemListWidget
);
1255 widgetCreator()->recycle(itemListWidget
);
1259 case KItemListViewAnimation::CreateAnimation
:
1260 case KItemListViewAnimation::MovingAnimation
:
1261 case KItemListViewAnimation::ResizeAnimation
: {
1262 const int index
= itemListWidget
->index();
1263 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1264 (index
> m_layouter
->lastVisibleIndex());
1265 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1266 recycleWidget(itemListWidget
);
1275 void KItemListView::slotLayoutTimerFinished()
1277 m_layouter
->setSize(geometry().size());
1278 doLayout(Animation
);
1281 void KItemListView::slotRubberBandPosChanged()
1286 void KItemListView::slotRubberBandActivationChanged(bool active
)
1289 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1290 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1291 m_skipAutoScrollForRubberBand
= true;
1293 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1294 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1295 m_skipAutoScrollForRubberBand
= false;
1301 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1303 qreal previousWidth
)
1306 Q_UNUSED(currentWidth
);
1307 Q_UNUSED(previousWidth
);
1309 m_headerWidget
->setAutomaticColumnResizing(false);
1310 applyColumnWidthsFromHeader();
1311 doLayout(NoAnimation
);
1314 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1318 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1320 const QList
<QByteArray
> previous
= m_visibleRoles
;
1322 QList
<QByteArray
> current
= m_visibleRoles
;
1323 current
.removeAt(previousIndex
);
1324 current
.insert(currentIndex
, role
);
1326 setVisibleRoles(current
);
1328 emit
visibleRolesChanged(current
, previous
);
1331 void KItemListView::triggerAutoScrolling()
1333 if (!m_autoScrollTimer
) {
1338 int visibleSize
= 0;
1339 if (scrollOrientation() == Qt::Vertical
) {
1340 pos
= m_mousePos
.y();
1341 visibleSize
= size().height();
1343 pos
= m_mousePos
.x();
1344 visibleSize
= size().width();
1347 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1348 m_autoScrollIncrement
= 0;
1351 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1352 if (m_autoScrollIncrement
== 0) {
1353 // The mouse position is not above an autoscroll margin (the autoscroll timer
1354 // will be restarted in mouseMoveEvent())
1355 m_autoScrollTimer
->stop();
1359 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1360 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1361 // if the direction of the rubberband is similar to the autoscroll direction. This
1362 // prevents that starting to create a rubberband within the autoscroll margins starts
1363 // an autoscrolling.
1365 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1366 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1367 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1368 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1369 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1370 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1371 // been moved up although the autoscroll direction might be down)
1372 m_autoScrollTimer
->stop();
1377 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1378 // the autoscrolling may not get skipped anymore until a new rubberband is created
1379 m_skipAutoScrollForRubberBand
= false;
1381 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1382 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1383 setScrollOffset(newScrollOffset
);
1385 // Trigger the autoscroll timer which will periodically call
1386 // triggerAutoScrolling()
1387 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1390 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1392 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1394 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1395 Q_ASSERT(groupHeader
);
1396 updateGroupHeaderLayout(widget
);
1399 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1401 emit
roleEditingCanceled(index
, role
, value
);
1402 m_editingRole
= false;
1405 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1407 emit
roleEditingFinished(index
, role
, value
);
1408 m_editingRole
= false;
1411 void KItemListView::setController(KItemListController
* controller
)
1413 if (m_controller
!= controller
) {
1414 KItemListController
* previous
= m_controller
;
1416 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1417 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1418 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1421 m_controller
= controller
;
1424 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1425 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1426 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1429 onControllerChanged(controller
, previous
);
1433 void KItemListView::setModel(KItemModelBase
* model
)
1435 if (m_model
== model
) {
1439 KItemModelBase
* previous
= m_model
;
1442 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1443 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1444 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1445 this, SLOT(slotItemsInserted(KItemRangeList
)));
1446 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1447 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1448 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1449 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1450 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1451 this, SLOT(slotGroupedSortingChanged(bool)));
1452 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1453 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1454 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1455 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1458 m_sizeHintResolver
->clearCache();
1461 m_layouter
->setModel(model
);
1462 m_grouped
= model
->groupedSorting();
1465 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1466 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1467 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1468 this, SLOT(slotItemsInserted(KItemRangeList
)));
1469 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1470 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1471 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1472 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1473 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1474 this, SLOT(slotGroupedSortingChanged(bool)));
1475 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1476 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1477 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1478 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1480 const int itemCount
= m_model
->count();
1481 if (itemCount
> 0) {
1482 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1483 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1487 onModelChanged(model
, previous
);
1490 KItemListRubberBand
* KItemListView::rubberBand() const
1492 return m_rubberBand
;
1495 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1497 if (m_layoutTimer
->isActive()) {
1498 m_layoutTimer
->stop();
1501 if (m_activeTransactions
> 0) {
1502 if (hint
== NoAnimation
) {
1503 // As soon as at least one property change should be done without animation,
1504 // the whole transaction will be marked as not animated.
1505 m_endTransactionAnimationHint
= NoAnimation
;
1510 if (!m_model
|| m_model
->count() < 0) {
1514 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1515 if (firstVisibleIndex
< 0) {
1516 emitOffsetChanges();
1520 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1521 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1522 // is still shown if the maximum offset got decreased.
1523 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1524 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1525 if (scrollOffset() > maxOffsetToShowFullRange
) {
1526 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1527 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1530 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1532 int firstSibblingIndex
= -1;
1533 int lastSibblingIndex
= -1;
1534 const bool supportsExpanding
= supportsItemExpanding();
1536 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1538 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1539 // instances from invisible items are reused. If no reusable items are
1540 // found then new KItemListWidget instances get created.
1541 const bool animate
= (hint
== Animation
);
1542 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1543 bool applyNewPos
= true;
1544 bool wasHidden
= false;
1546 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1547 const QPointF newPos
= itemBounds
.topLeft();
1548 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1551 if (!reusableItems
.isEmpty()) {
1552 // Reuse a KItemListWidget instance from an invisible item
1553 const int oldIndex
= reusableItems
.takeLast();
1554 widget
= m_visibleItems
.value(oldIndex
);
1555 setWidgetIndex(widget
, i
);
1556 updateWidgetProperties(widget
, i
);
1557 initializeItemListWidget(widget
);
1559 // No reusable KItemListWidget instance is available, create a new one
1560 widget
= createWidget(i
);
1562 widget
->resize(itemBounds
.size());
1564 if (animate
&& changedCount
< 0) {
1565 // Items have been deleted, move the created item to the
1566 // imaginary old position. They will get animated to the new position
1568 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1569 if (itemRect
.isEmpty()) {
1570 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1571 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1572 widget
->setPos(invisibleOldPos
);
1574 widget
->setPos(itemRect
.topLeft());
1576 applyNewPos
= false;
1579 if (supportsExpanding
&& changedCount
== 0) {
1580 if (firstSibblingIndex
< 0) {
1581 firstSibblingIndex
= i
;
1583 lastSibblingIndex
= i
;
1588 const bool itemsRemoved
= (changedCount
< 0);
1589 const bool itemsInserted
= (changedCount
> 0);
1590 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1591 // The item is located after the removed items. Animate the moving of the position.
1592 applyNewPos
= !moveWidget(widget
, newPos
);
1593 } else if (itemsInserted
&& i
>= changedIndex
) {
1594 // The item is located after the first inserted item
1595 if (i
<= changedIndex
+ changedCount
- 1) {
1596 // The item is an inserted item. Animate the appearing of the item.
1597 // For performance reasons no animation is done when changedCount is equal
1598 // to all available items.
1599 if (changedCount
< m_model
->count()) {
1600 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1602 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1603 // The item was already there before, so animate the moving of the position.
1604 // No moving animation is done if the item is animated by a create animation: This
1605 // prevents a "move animation mess" when inserting several ranges in parallel.
1606 applyNewPos
= !moveWidget(widget
, newPos
);
1608 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1609 // The size of the view might have been changed. Animate the moving of the position.
1610 applyNewPos
= !moveWidget(widget
, newPos
);
1613 m_animation
->stop(widget
);
1617 widget
->setPos(newPos
);
1620 Q_ASSERT(widget
->index() == i
);
1621 widget
->setVisible(true);
1623 if (widget
->size() != itemBounds
.size()) {
1624 // Resize the widget for the item to the changed size.
1626 // If a dynamic item size is used then no animation is done in the direction
1627 // of the dynamic size.
1628 if (m_itemSize
.width() <= 0) {
1629 // The width is dynamic, apply the new width without animation.
1630 widget
->resize(itemBounds
.width(), widget
->size().height());
1631 } else if (m_itemSize
.height() <= 0) {
1632 // The height is dynamic, apply the new height without animation.
1633 widget
->resize(widget
->size().width(), itemBounds
.height());
1635 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1637 widget
->resize(itemBounds
.size());
1641 // Updating the cell-information must be done as last step: The decision whether the
1642 // moving-animation should be started at all is based on the previous cell-information.
1643 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1644 m_visibleCells
.insert(i
, cell
);
1647 // Delete invisible KItemListWidget instances that have not been reused
1648 foreach (int index
, reusableItems
) {
1649 recycleWidget(m_visibleItems
.value(index
));
1652 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1653 Q_ASSERT(lastSibblingIndex
>= 0);
1654 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1658 // Update the layout of all visible group headers
1659 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1660 while (it
.hasNext()) {
1662 updateGroupHeaderLayout(it
.key());
1666 emitOffsetChanges();
1669 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1670 int lastVisibleIndex
,
1671 LayoutAnimationHint hint
)
1673 // Determine all items that are completely invisible and might be
1674 // reused for items that just got (at least partly) visible. If the
1675 // animation hint is set to 'Animation' items that do e.g. an animated
1676 // moving of their position are not marked as invisible: This assures
1677 // that a scrolling inside the view can be done without breaking an animation.
1681 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1682 while (it
.hasNext()) {
1685 KItemListWidget
* widget
= it
.value();
1686 const int index
= widget
->index();
1687 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1690 if (m_animation
->isStarted(widget
)) {
1691 if (hint
== NoAnimation
) {
1692 // Stopping the animation will call KItemListView::slotAnimationFinished()
1693 // and the widget will be recycled if necessary there.
1694 m_animation
->stop(widget
);
1697 widget
->setVisible(false);
1698 items
.append(index
);
1701 recycleGroupHeaderForWidget(widget
);
1710 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1712 if (widget
->pos() == newPos
) {
1716 bool startMovingAnim
= false;
1718 if (m_itemSize
.isEmpty()) {
1719 // The items are not aligned in a grid but either as columns or rows.
1720 startMovingAnim
= !supportsItemExpanding();
1722 // When having a grid the moving-animation should only be started, if it is done within
1723 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1724 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1725 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1726 const int index
= widget
->index();
1727 const Cell cell
= m_visibleCells
.value(index
);
1728 if (cell
.column
>= 0 && cell
.row
>= 0) {
1729 if (scrollOrientation() == Qt::Vertical
) {
1730 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1732 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1737 if (startMovingAnim
) {
1738 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1742 m_animation
->stop(widget
);
1743 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1747 void KItemListView::emitOffsetChanges()
1749 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1750 if (m_oldScrollOffset
!= newScrollOffset
) {
1751 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1752 m_oldScrollOffset
= newScrollOffset
;
1755 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1756 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1757 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1758 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1761 const qreal newItemOffset
= m_layouter
->itemOffset();
1762 if (m_oldItemOffset
!= newItemOffset
) {
1763 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1764 m_oldItemOffset
= newItemOffset
;
1767 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1768 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1769 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1770 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1774 KItemListWidget
* KItemListView::createWidget(int index
)
1776 KItemListWidget
* widget
= widgetCreator()->create(this);
1777 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1779 m_visibleItems
.insert(index
, widget
);
1780 m_visibleCells
.insert(index
, Cell());
1781 updateWidgetProperties(widget
, index
);
1782 initializeItemListWidget(widget
);
1786 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1789 recycleGroupHeaderForWidget(widget
);
1792 const int index
= widget
->index();
1793 m_visibleItems
.remove(index
);
1794 m_visibleCells
.remove(index
);
1796 widgetCreator()->recycle(widget
);
1799 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1801 const int oldIndex
= widget
->index();
1802 m_visibleItems
.remove(oldIndex
);
1803 m_visibleCells
.remove(oldIndex
);
1805 m_visibleItems
.insert(index
, widget
);
1806 m_visibleCells
.insert(index
, Cell());
1808 widget
->setIndex(index
);
1811 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1813 const int oldIndex
= widget
->index();
1814 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1816 setWidgetIndex(widget
, index
);
1818 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1819 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1820 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1821 (!vertical
&& oldCell
.column
== newCell
.column
);
1823 m_visibleCells
.insert(index
, newCell
);
1827 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1830 case LayouterSize
: m_layouter
->setSize(size
); break;
1831 case ItemSize
: m_layouter
->setItemSize(size
); break;
1836 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1838 widget
->setVisibleRoles(m_visibleRoles
);
1839 updateWidgetColumnWidths(widget
);
1840 widget
->setStyleOption(m_styleOption
);
1842 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1843 widget
->setCurrent(index
== selectionManager
->currentItem());
1844 widget
->setSelected(selectionManager
->isSelected(index
));
1845 widget
->setHovered(false);
1846 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1847 widget
->setIndex(index
);
1848 widget
->setData(m_model
->data(index
));
1849 widget
->setSiblingsInformation(QBitArray());
1850 updateAlternateBackgroundForWidget(widget
);
1853 updateGroupHeaderForWidget(widget
);
1857 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1859 Q_ASSERT(m_grouped
);
1861 const int index
= widget
->index();
1862 if (!m_layouter
->isFirstGroupItem(index
)) {
1863 // The widget does not represent the first item of a group
1864 // and hence requires no header
1865 recycleGroupHeaderForWidget(widget
);
1869 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1870 if (groups
.isEmpty() || !groupHeaderCreator()) {
1874 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1876 groupHeader
= groupHeaderCreator()->create(this);
1877 groupHeader
->setParentItem(widget
);
1878 m_visibleGroups
.insert(widget
, groupHeader
);
1879 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1881 Q_ASSERT(groupHeader
->parentItem() == widget
);
1883 const int groupIndex
= groupIndexForItem(index
);
1884 Q_ASSERT(groupIndex
>= 0);
1885 groupHeader
->setData(groups
.at(groupIndex
).second
);
1886 groupHeader
->setRole(model()->sortRole());
1887 groupHeader
->setStyleOption(m_styleOption
);
1888 groupHeader
->setScrollOrientation(scrollOrientation());
1889 groupHeader
->setItemIndex(index
);
1891 groupHeader
->show();
1894 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1896 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1897 Q_ASSERT(groupHeader
);
1899 const int index
= widget
->index();
1900 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1901 const QRectF itemRect
= m_layouter
->itemRect(index
);
1903 // The group-header is a child of the itemlist widget. Translate the
1904 // group header position to the relative position.
1905 if (scrollOrientation() == Qt::Vertical
) {
1906 // In the vertical scroll orientation the group header should always span
1907 // the whole width no matter which temporary position the parent widget
1908 // has. In this case the x-position and width will be adjusted manually.
1909 const qreal x
= -widget
->x() - itemOffset();
1910 const qreal width
= maximumItemOffset();
1911 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1912 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1914 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1915 groupHeader
->resize(groupHeaderRect
.size());
1919 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1921 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1923 header
->setParentItem(0);
1924 groupHeaderCreator()->recycle(header
);
1925 m_visibleGroups
.remove(widget
);
1926 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1930 void KItemListView::updateVisibleGroupHeaders()
1932 Q_ASSERT(m_grouped
);
1933 m_layouter
->markAsDirty();
1935 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1936 while (it
.hasNext()) {
1938 updateGroupHeaderForWidget(it
.value());
1942 int KItemListView::groupIndexForItem(int index
) const
1944 Q_ASSERT(m_grouped
);
1946 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1947 if (groups
.isEmpty()) {
1952 int max
= groups
.count() - 1;
1955 mid
= (min
+ max
) / 2;
1956 if (index
> groups
[mid
].first
) {
1961 } while (groups
[mid
].first
!= index
&& min
<= max
);
1964 while (groups
[mid
].first
> index
&& mid
> 0) {
1972 void KItemListView::updateAlternateBackgrounds()
1974 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1975 while (it
.hasNext()) {
1977 updateAlternateBackgroundForWidget(it
.value());
1981 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
1983 bool enabled
= useAlternateBackgrounds();
1985 const int index
= widget
->index();
1986 enabled
= (index
& 0x1) > 0;
1988 const int groupIndex
= groupIndexForItem(index
);
1989 if (groupIndex
>= 0) {
1990 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1991 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
1992 const int relativeIndex
= index
- indexOfFirstGroupItem
;
1993 enabled
= (relativeIndex
& 0x1) > 0;
1997 widget
->setAlternateBackground(enabled
);
2000 bool KItemListView::useAlternateBackgrounds() const
2002 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2005 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2007 QElapsedTimer timer
;
2010 QHash
<QByteArray
, qreal
> widths
;
2012 // Calculate the minimum width for each column that is required
2013 // to show the headline unclipped.
2014 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2015 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2016 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2017 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2018 const QString headerText
= m_model
->roleDescription(visibleRole
);
2019 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2020 widths
.insert(visibleRole
, headerWidth
);
2023 // Calculate the preferred column withs for each item and ignore values
2024 // smaller than the width for showing the headline unclipped.
2025 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2026 int calculatedItemCount
= 0;
2027 bool maxTimeExceeded
= false;
2028 foreach (const KItemRange
& itemRange
, itemRanges
) {
2029 const int startIndex
= itemRange
.index
;
2030 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2032 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2033 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2034 qreal maxWidth
= widths
.value(visibleRole
, 0);
2035 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2036 maxWidth
= qMax(width
, maxWidth
);
2037 widths
.insert(visibleRole
, maxWidth
);
2040 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2041 // When having several thousands of items calculating the sizes can get
2042 // very expensive. We accept a possibly too small role-size in favour
2043 // of having no blocking user interface.
2044 maxTimeExceeded
= true;
2047 ++calculatedItemCount
;
2049 if (maxTimeExceeded
) {
2057 void KItemListView::applyColumnWidthsFromHeader()
2059 // Apply the new size to the layouter
2060 const qreal requiredWidth
= columnWidthsSum();
2061 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2062 m_itemSize
.height());
2063 m_layouter
->setItemSize(dynamicItemSize
);
2065 // Update the role sizes for all visible widgets
2066 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2067 while (it
.hasNext()) {
2069 updateWidgetColumnWidths(it
.value());
2073 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2075 foreach (const QByteArray
& role
, m_visibleRoles
) {
2076 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2080 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2082 Q_ASSERT(m_itemSize
.isEmpty());
2083 const int itemCount
= m_model
->count();
2084 int rangesItemCount
= 0;
2085 foreach (const KItemRange
& range
, itemRanges
) {
2086 rangesItemCount
+= range
.count
;
2089 if (itemCount
== rangesItemCount
) {
2090 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2091 foreach (const QByteArray
& role
, m_visibleRoles
) {
2092 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2095 // Only a sub range of the roles need to be determined.
2096 // The chances are good that the widths of the sub ranges
2097 // already fit into the available widths and hence no
2098 // expensive update might be required.
2099 bool changed
= false;
2101 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2102 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2103 while (it
.hasNext()) {
2105 const QByteArray
& role
= it
.key();
2106 const qreal updatedWidth
= it
.value();
2107 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2108 if (updatedWidth
> currentWidth
) {
2109 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2115 // All the updated sizes are smaller than the current sizes and no change
2116 // of the stretched roles-widths is required
2121 if (m_headerWidget
->automaticColumnResizing()) {
2122 applyAutomaticColumnWidths();
2126 void KItemListView::updatePreferredColumnWidths()
2129 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2133 void KItemListView::applyAutomaticColumnWidths()
2135 Q_ASSERT(m_itemSize
.isEmpty());
2136 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2137 if (m_visibleRoles
.isEmpty()) {
2141 // Calculate the maximum size of an item by considering the
2142 // visible role sizes and apply them to the layouter. If the
2143 // size does not use the available view-size the size of the
2144 // first role will get stretched.
2146 foreach (const QByteArray
& role
, m_visibleRoles
) {
2147 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2148 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2151 const QByteArray firstRole
= m_visibleRoles
.first();
2152 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2153 QSizeF dynamicItemSize
= m_itemSize
;
2155 qreal requiredWidth
= columnWidthsSum();
2156 const qreal availableWidth
= size().width();
2157 if (requiredWidth
< availableWidth
) {
2158 // Stretch the first column to use the whole remaining width
2159 firstColumnWidth
+= availableWidth
- requiredWidth
;
2160 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2161 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2162 // Shrink the first column to be able to show as much other
2163 // columns as possible
2164 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2166 // TODO: A proper calculation of the minimum width depends on the implementation
2167 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2169 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2170 if (shrinkedFirstColumnWidth
< minWidth
) {
2171 shrinkedFirstColumnWidth
= minWidth
;
2174 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2175 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2178 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2180 m_layouter
->setItemSize(dynamicItemSize
);
2182 // Update the role sizes for all visible widgets
2183 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2184 while (it
.hasNext()) {
2186 updateWidgetColumnWidths(it
.value());
2190 qreal
KItemListView::columnWidthsSum() const
2192 qreal widthsSum
= 0;
2193 foreach (const QByteArray
& role
, m_visibleRoles
) {
2194 widthsSum
+= m_headerWidget
->columnWidth(role
);
2199 QRectF
KItemListView::headerBoundaries() const
2201 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2204 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2205 const QSizeF
& newItemSize
,
2206 const QSizeF
& newItemMargin
) const
2208 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2212 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2213 const qreal itemWidth
= m_layouter
->itemSize().width();
2214 if (itemWidth
> 0) {
2215 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2216 newItemSize
.width(),
2217 newItemMargin
.width());
2218 if (m_model
->count() > newColumnCount
) {
2219 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2221 m_layouter
->itemMargin().width());
2222 return oldColumnCount
!= newColumnCount
;
2226 const qreal itemHeight
= m_layouter
->itemSize().height();
2227 if (itemHeight
> 0) {
2228 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2229 newItemSize
.height(),
2230 newItemMargin
.height());
2231 if (m_model
->count() > newRowCount
) {
2232 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2234 m_layouter
->itemMargin().height());
2235 return oldRowCount
!= newRowCount
;
2243 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2245 if (m_itemSize
.isEmpty()) {
2246 // We have only columns or only rows, but no grid: An animation is usually
2247 // welcome when inserting or removing items.
2248 return !supportsItemExpanding();
2251 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2255 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2256 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2257 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2258 // Only animate if up to 2/3 of a row or column are inserted or removed
2259 return changedItemCount
<= maximum
* 2 / 3;
2263 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2265 const QSizeF oldSize
= m_layouter
->size();
2267 m_layouter
->setSize(size
);
2268 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2269 m_layouter
->setSize(oldSize
);
2271 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2272 : maxOffset
> size
.width();
2275 void KItemListView::updateGroupHeaderHeight()
2277 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2278 qreal groupHeaderMargin
= 0;
2280 if (scrollOrientation() == Qt::Horizontal
) {
2281 // The vertical margin above and below the header should be
2282 // equal to the horizontal margin, not the vertical margin
2283 // from m_styleOption.
2284 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2285 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2286 } else if (m_itemSize
.isEmpty()){
2287 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2288 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2290 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2291 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2293 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2294 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2296 updateVisibleGroupHeaders();
2299 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2301 if (!supportsItemExpanding() || !m_model
) {
2305 if (firstIndex
< 0 || lastIndex
< 0) {
2306 firstIndex
= m_layouter
->firstVisibleIndex();
2307 lastIndex
= m_layouter
->lastVisibleIndex();
2309 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2310 lastIndex
>= m_layouter
->firstVisibleIndex());
2311 if (!isRangeVisible
) {
2316 int previousParents
= 0;
2317 QBitArray previousSiblings
;
2319 // The rootIndex describes the first index where the siblings get
2320 // calculated from. For the calculation the upper most parent item
2321 // is required. For performance reasons it is checked first whether
2322 // the visible items before or after the current range already
2323 // contain a siblings information which can be used as base.
2324 int rootIndex
= firstIndex
;
2326 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2328 // There is no visible widget before the range, check whether there
2329 // is one after the range:
2330 widget
= m_visibleItems
.value(lastIndex
+ 1);
2332 // The sibling information of the widget may only be used if
2333 // all items of the range have the same number of parents.
2334 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2335 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2336 if (m_model
->expandedParentsCount(i
) != parents
) {
2345 // Performance optimization: Use the sibling information of the visible
2346 // widget beside the given range.
2347 previousSiblings
= widget
->siblingsInformation();
2348 if (previousSiblings
.isEmpty()) {
2351 previousParents
= previousSiblings
.count() - 1;
2352 previousSiblings
.truncate(previousParents
);
2354 // Potentially slow path: Go back to the upper most parent of firstIndex
2355 // to be able to calculate the initial value for the siblings.
2356 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2361 Q_ASSERT(previousParents
>= 0);
2362 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2363 // Update the parent-siblings in case if the current item represents
2364 // a child or an upper parent.
2365 const int currentParents
= m_model
->expandedParentsCount(i
);
2366 Q_ASSERT(currentParents
>= 0);
2367 if (previousParents
< currentParents
) {
2368 previousParents
= currentParents
;
2369 previousSiblings
.resize(currentParents
);
2370 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2371 } else if (previousParents
> currentParents
) {
2372 previousParents
= currentParents
;
2373 previousSiblings
.truncate(currentParents
);
2376 if (i
>= firstIndex
) {
2377 // The index represents a visible item. Apply the parent-siblings
2378 // and update the sibling of the current item.
2379 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2384 QBitArray siblings
= previousSiblings
;
2385 siblings
.resize(siblings
.count() + 1);
2386 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2388 widget
->setSiblingsInformation(siblings
);
2393 bool KItemListView::hasSiblingSuccessor(int index
) const
2395 bool hasSuccessor
= false;
2396 const int parentsCount
= m_model
->expandedParentsCount(index
);
2397 int successorIndex
= index
+ 1;
2399 // Search the next sibling
2400 const int itemCount
= m_model
->count();
2401 while (successorIndex
< itemCount
) {
2402 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2403 if (currentParentsCount
== parentsCount
) {
2404 hasSuccessor
= true;
2406 } else if (currentParentsCount
< parentsCount
) {
2412 if (m_grouped
&& hasSuccessor
) {
2413 // If the sibling is part of another group, don't mark it as
2414 // successor as the group header is between the sibling connections.
2415 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2416 if (m_layouter
->isFirstGroupItem(i
)) {
2417 hasSuccessor
= false;
2423 return hasSuccessor
;
2426 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2430 const int minSpeed
= 4;
2431 const int maxSpeed
= 128;
2432 const int speedLimiter
= 96;
2433 const int autoScrollBorder
= 64;
2435 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2436 // This assures that the autoscrolling speed grows gradually.
2437 const int incLimiter
= 1;
2439 if (pos
< autoScrollBorder
) {
2440 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2441 inc
= qMax(inc
, -maxSpeed
);
2442 inc
= qMax(inc
, oldInc
- incLimiter
);
2443 } else if (pos
> range
- autoScrollBorder
) {
2444 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2445 inc
= qMin(inc
, maxSpeed
);
2446 inc
= qMin(inc
, oldInc
+ incLimiter
);
2452 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2454 const qreal availableSize
= size
- itemMargin
;
2455 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2461 KItemListCreatorBase::~KItemListCreatorBase()
2463 qDeleteAll(m_recycleableWidgets
);
2464 qDeleteAll(m_createdWidgets
);
2467 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2469 m_createdWidgets
.insert(widget
);
2472 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2474 Q_ASSERT(m_createdWidgets
.contains(widget
));
2475 m_createdWidgets
.remove(widget
);
2477 if (m_recycleableWidgets
.count() < 100) {
2478 m_recycleableWidgets
.append(widget
);
2479 widget
->setVisible(false);
2485 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2487 if (m_recycleableWidgets
.isEmpty()) {
2491 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2492 m_createdWidgets
.insert(widget
);
2496 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2500 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2502 widget
->setParentItem(0);
2503 widget
->setOpacity(1.0);
2504 pushRecycleableWidget(widget
);
2507 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2511 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2513 header
->setOpacity(1.0);
2514 pushRecycleableWidget(header
);
2517 #include "kitemlistview.moc"