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>
39 #include <QGraphicsView>
41 #include <QPropertyAnimation>
43 #include <QStyleOptionRubberBand>
46 #include "kitemlistviewaccessible.h"
49 // Time in ms until reaching the autoscroll margin triggers
50 // an initial autoscrolling
51 const int InitialAutoScrollDelay
= 700;
53 // Delay in ms for triggering the next autoscroll
54 const int RepeatingAutoScrollDelay
= 1000 / 60;
57 #ifndef QT_NO_ACCESSIBILITY
58 QAccessibleInterface
* accessibleViewFactory(const QString
&key
, QObject
*object
)
61 if (KItemListView
*view
= qobject_cast
<KItemListView
*>(object
)) {
62 return new KItemListViewAccessible(view
);
68 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
69 QGraphicsWidget(parent
),
70 m_enabledSelectionToggles(false),
72 m_supportsItemExpanding(false),
74 m_activeTransactions(0),
75 m_endTransactionAnimationHint(Animation
),
81 m_groupHeaderCreator(0),
86 m_sizeHintResolver(0),
91 m_oldMaximumScrollOffset(0),
93 m_oldMaximumItemOffset(0),
94 m_skipAutoScrollForRubberBand(false),
97 m_autoScrollIncrement(0),
103 setAcceptHoverEvents(true);
105 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
107 m_layouter
= new KItemListViewLayouter(this);
108 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
110 m_animation
= new KItemListViewAnimation(this);
111 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
112 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
114 m_layoutTimer
= new QTimer(this);
115 m_layoutTimer
->setInterval(300);
116 m_layoutTimer
->setSingleShot(true);
117 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
119 m_rubberBand
= new KItemListRubberBand(this);
120 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
122 m_headerWidget
= new KItemListHeaderWidget(this);
123 m_headerWidget
->setVisible(false);
125 m_header
= new KItemListHeader(this);
127 #ifndef QT_NO_ACCESSIBILITY
128 QAccessible::installFactory(accessibleViewFactory
);
133 KItemListView::~KItemListView()
135 // The group headers are children of the widgets created by
136 // widgetCreator(). So it is mandatory to delete the group headers
138 delete m_groupHeaderCreator
;
139 m_groupHeaderCreator
= 0;
141 delete m_widgetCreator
;
144 delete m_sizeHintResolver
;
145 m_sizeHintResolver
= 0;
148 void KItemListView::setScrollOffset(qreal offset
)
154 const qreal previousOffset
= m_layouter
->scrollOffset();
155 if (offset
== previousOffset
) {
159 m_layouter
->setScrollOffset(offset
);
160 m_animation
->setScrollOffset(offset
);
162 // Don't check whether the m_layoutTimer is active: Changing the
163 // scroll offset must always trigger a synchronous layout, otherwise
164 // the smooth-scrolling might get jerky.
165 doLayout(NoAnimation
);
166 onScrollOffsetChanged(offset
, previousOffset
);
169 qreal
KItemListView::scrollOffset() const
171 return m_layouter
->scrollOffset();
174 qreal
KItemListView::maximumScrollOffset() const
176 return m_layouter
->maximumScrollOffset();
179 void KItemListView::setItemOffset(qreal offset
)
181 if (m_layouter
->itemOffset() == offset
) {
185 m_layouter
->setItemOffset(offset
);
186 if (m_headerWidget
->isVisible()) {
187 m_headerWidget
->setOffset(offset
);
190 // Don't check whether the m_layoutTimer is active: Changing the
191 // item offset must always trigger a synchronous layout, otherwise
192 // the smooth-scrolling might get jerky.
193 doLayout(NoAnimation
);
196 qreal
KItemListView::itemOffset() const
198 return m_layouter
->itemOffset();
201 qreal
KItemListView::maximumItemOffset() const
203 return m_layouter
->maximumItemOffset();
206 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
208 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
209 m_visibleRoles
= roles
;
210 onVisibleRolesChanged(roles
, previousRoles
);
212 m_sizeHintResolver
->clearCache();
213 m_layouter
->markAsDirty();
215 if (m_itemSize
.isEmpty()) {
216 m_headerWidget
->setColumns(roles
);
217 updatePreferredColumnWidths();
218 if (!m_headerWidget
->automaticColumnResizing()) {
219 // The column-width of new roles are still 0. Apply the preferred
220 // column-width as default with.
221 foreach (const QByteArray
& role
, m_visibleRoles
) {
222 if (m_headerWidget
->columnWidth(role
) == 0) {
223 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
224 m_headerWidget
->setColumnWidth(role
, width
);
228 applyColumnWidthsFromHeader();
232 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
233 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
234 (roles
.count() <= 1 && previousRoles
.count() > 1));
236 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
237 while (it
.hasNext()) {
239 KItemListWidget
* widget
= it
.value();
240 widget
->setVisibleRoles(roles
);
241 if (alternateBackgroundsChanged
) {
242 updateAlternateBackgroundForWidget(widget
);
246 doLayout(NoAnimation
);
249 QList
<QByteArray
> KItemListView::visibleRoles() const
251 return m_visibleRoles
;
254 void KItemListView::setAutoScroll(bool enabled
)
256 if (enabled
&& !m_autoScrollTimer
) {
257 m_autoScrollTimer
= new QTimer(this);
258 m_autoScrollTimer
->setSingleShot(true);
259 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
260 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
261 } else if (!enabled
&& m_autoScrollTimer
) {
262 delete m_autoScrollTimer
;
263 m_autoScrollTimer
= 0;
267 bool KItemListView::autoScroll() const
269 return m_autoScrollTimer
!= 0;
272 void KItemListView::setEnabledSelectionToggles(bool enabled
)
274 if (m_enabledSelectionToggles
!= enabled
) {
275 m_enabledSelectionToggles
= enabled
;
277 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
278 while (it
.hasNext()) {
280 it
.value()->setEnabledSelectionToggle(enabled
);
285 bool KItemListView::enabledSelectionToggles() const
287 return m_enabledSelectionToggles
;
290 KItemListController
* KItemListView::controller() const
295 KItemModelBase
* KItemListView::model() const
300 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
302 if (m_widgetCreator
) {
303 delete m_widgetCreator
;
305 m_widgetCreator
= widgetCreator
;
308 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
310 if (!m_widgetCreator
) {
311 m_widgetCreator
= defaultWidgetCreator();
313 return m_widgetCreator
;
316 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
318 if (m_groupHeaderCreator
) {
319 delete m_groupHeaderCreator
;
321 m_groupHeaderCreator
= groupHeaderCreator
;
324 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
326 if (!m_groupHeaderCreator
) {
327 m_groupHeaderCreator
= defaultGroupHeaderCreator();
329 return m_groupHeaderCreator
;
332 QSizeF
KItemListView::itemSize() const
337 const KItemListStyleOption
& KItemListView::styleOption() const
339 return m_styleOption
;
342 void KItemListView::setGeometry(const QRectF
& rect
)
344 QGraphicsWidget::setGeometry(rect
);
350 const QSizeF newSize
= rect
.size();
351 if (m_itemSize
.isEmpty()) {
352 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
353 if (m_headerWidget
->automaticColumnResizing()) {
354 applyAutomaticColumnWidths();
356 const qreal requiredWidth
= columnWidthsSum();
357 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
358 m_itemSize
.height());
359 m_layouter
->setItemSize(dynamicItemSize
);
362 // Triggering a synchronous layout is fine from a performance point of view,
363 // as with dynamic item sizes no moving animation must be done.
364 m_layouter
->setSize(newSize
);
365 doLayout(NoAnimation
);
367 const bool animate
= !changesItemGridLayout(newSize
,
368 m_layouter
->itemSize(),
369 m_layouter
->itemMargin());
370 m_layouter
->setSize(newSize
);
373 // Trigger an asynchronous relayout with m_layoutTimer to prevent
374 // performance bottlenecks. If the timer is exceeded, an animated layout
375 // will be triggered.
376 if (!m_layoutTimer
->isActive()) {
377 m_layoutTimer
->start();
380 m_layoutTimer
->stop();
381 doLayout(NoAnimation
);
386 int KItemListView::itemAt(const QPointF
& pos
) const
388 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
389 while (it
.hasNext()) {
392 const KItemListWidget
* widget
= it
.value();
393 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
394 if (widget
->contains(mappedPos
)) {
402 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
404 if (!m_enabledSelectionToggles
) {
408 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
410 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
411 if (!selectionToggleRect
.isEmpty()) {
412 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
413 return selectionToggleRect
.contains(mappedPos
);
419 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
421 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
423 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
424 if (!expansionToggleRect
.isEmpty()) {
425 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
426 return expansionToggleRect
.contains(mappedPos
);
432 int KItemListView::firstVisibleIndex() const
434 return m_layouter
->firstVisibleIndex();
437 int KItemListView::lastVisibleIndex() const
439 return m_layouter
->lastVisibleIndex();
442 QSizeF
KItemListView::itemSizeHint(int index
) const
444 return widgetCreator()->itemSizeHint(index
, this);
447 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
449 if (m_supportsItemExpanding
!= supportsExpanding
) {
450 m_supportsItemExpanding
= supportsExpanding
;
451 updateSiblingsInformation();
452 onSupportsItemExpandingChanged(supportsExpanding
);
456 bool KItemListView::supportsItemExpanding() const
458 return m_supportsItemExpanding
;
461 QRectF
KItemListView::itemRect(int index
) const
463 return m_layouter
->itemRect(index
);
466 QRectF
KItemListView::itemContextRect(int index
) const
470 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
472 contextRect
= widget
->iconRect() | widget
->textRect();
473 contextRect
.translate(itemRect(index
).topLeft());
479 void KItemListView::scrollToItem(int index
)
481 QRectF viewGeometry
= geometry();
482 if (m_headerWidget
->isVisible()) {
483 const qreal headerHeight
= m_headerWidget
->size().height();
484 viewGeometry
.adjust(0, headerHeight
, 0, 0);
486 const QRectF currentRect
= itemRect(index
);
488 if (!viewGeometry
.contains(currentRect
)) {
489 qreal newOffset
= scrollOffset();
490 if (scrollOrientation() == Qt::Vertical
) {
491 if (currentRect
.top() < viewGeometry
.top()) {
492 newOffset
+= currentRect
.top() - viewGeometry
.top();
493 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
494 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
497 if (currentRect
.left() < viewGeometry
.left()) {
498 newOffset
+= currentRect
.left() - viewGeometry
.left();
499 } else if (currentRect
.right() > viewGeometry
.right()) {
500 newOffset
+= currentRect
.right() - viewGeometry
.right();
504 if (newOffset
!= scrollOffset()) {
505 emit
scrollTo(newOffset
);
510 void KItemListView::beginTransaction()
512 ++m_activeTransactions
;
513 if (m_activeTransactions
== 1) {
514 onTransactionBegin();
518 void KItemListView::endTransaction()
520 --m_activeTransactions
;
521 if (m_activeTransactions
< 0) {
522 m_activeTransactions
= 0;
523 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
526 if (m_activeTransactions
== 0) {
528 doLayout(m_endTransactionAnimationHint
);
529 m_endTransactionAnimationHint
= Animation
;
533 bool KItemListView::isTransactionActive() const
535 return m_activeTransactions
> 0;
538 void KItemListView::setHeaderVisible(bool visible
)
540 if (visible
&& !m_headerWidget
->isVisible()) {
541 QStyleOptionHeader option
;
542 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
545 m_headerWidget
->setPos(0, 0);
546 m_headerWidget
->resize(size().width(), headerSize
.height());
547 m_headerWidget
->setModel(m_model
);
548 m_headerWidget
->setColumns(m_visibleRoles
);
549 m_headerWidget
->setZValue(1);
551 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
552 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
553 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
554 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
555 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
556 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
557 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
558 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
560 m_layouter
->setHeaderHeight(headerSize
.height());
561 m_headerWidget
->setVisible(true);
562 } else if (!visible
&& m_headerWidget
->isVisible()) {
563 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
564 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
565 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
566 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
567 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
568 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
569 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
570 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
572 m_layouter
->setHeaderHeight(0);
573 m_headerWidget
->setVisible(false);
577 bool KItemListView::isHeaderVisible() const
579 return m_headerWidget
->isVisible();
582 KItemListHeader
* KItemListView::header() const
587 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
591 if (indexes
.count() == 1) {
592 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
593 QGraphicsView
* graphicsView
= scene()->views()[0];
594 if (item
&& graphicsView
) {
595 pixmap
= item
->createDragPixmap(0, graphicsView
);
598 // TODO: Not implemented yet. Probably extend the interface
599 // from KItemListWidget::createDragPixmap() to return a pixmap
600 // that can be used for multiple indexes.
606 void KItemListView::editRole(int index
, const QByteArray
& role
)
608 KItemListWidget
* widget
= m_visibleItems
.value(index
);
609 if (!widget
|| m_editingRole
) {
613 m_editingRole
= true;
614 widget
->setEditedRole(role
);
616 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
617 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
618 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
619 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
622 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
624 QGraphicsWidget::paint(painter
, option
, widget
);
626 if (m_rubberBand
->isActive()) {
627 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
628 m_rubberBand
->endPosition()).normalized();
630 const QPointF topLeft
= rubberBandRect
.topLeft();
631 if (scrollOrientation() == Qt::Vertical
) {
632 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
634 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
637 QStyleOptionRubberBand opt
;
638 opt
.initFrom(widget
);
639 opt
.shape
= QRubberBand::Rectangle
;
641 opt
.rect
= rubberBandRect
.toRect();
642 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
645 if (!m_dropIndicator
.isEmpty()) {
646 const QRectF r
= m_dropIndicator
.toRect();
648 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
649 painter
->setPen(color
);
651 // TODO: The following implementation works only for a vertical scroll-orientation
652 // and assumes a height of the m_draggingInsertIndicator of 1.
653 Q_ASSERT(r
.height() == 1);
654 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
657 painter
->setPen(color
);
658 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
662 void KItemListView::setItemSize(const QSizeF
& size
)
664 const QSizeF previousSize
= m_itemSize
;
665 if (size
== previousSize
) {
669 // Skip animations when the number of rows or columns
670 // are changed in the grid layout. Although the animation
671 // engine can handle this usecase, it looks obtrusive.
672 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
674 m_layouter
->itemMargin());
676 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
677 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
678 (!m_itemSize
.isEmpty() && size
.isEmpty()));
682 if (alternateBackgroundsChanged
) {
683 // For an empty item size alternate backgrounds are drawn if more than
684 // one role is shown. Assure that the backgrounds for visible items are
685 // updated when changing the size in this context.
686 updateAlternateBackgrounds();
689 if (size
.isEmpty()) {
690 if (m_headerWidget
->automaticColumnResizing()) {
691 updatePreferredColumnWidths();
693 // Only apply the changed height and respect the header widths
695 const qreal currentWidth
= m_layouter
->itemSize().width();
696 const QSizeF
newSize(currentWidth
, size
.height());
697 m_layouter
->setItemSize(newSize
);
700 m_layouter
->setItemSize(size
);
703 m_sizeHintResolver
->clearCache();
704 doLayout(animate
? Animation
: NoAnimation
);
705 onItemSizeChanged(size
, previousSize
);
708 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
710 const KItemListStyleOption previousOption
= m_styleOption
;
711 m_styleOption
= option
;
714 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
715 if (margin
!= m_layouter
->itemMargin()) {
716 // Skip animations when the number of rows or columns
717 // are changed in the grid layout. Although the animation
718 // engine can handle this usecase, it looks obtrusive.
719 animate
= !changesItemGridLayout(m_layouter
->size(),
720 m_layouter
->itemSize(),
722 m_layouter
->setItemMargin(margin
);
726 updateGroupHeaderHeight();
729 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
730 // Animating a change of the maximum text size just results in expensive
731 // temporary eliding and clipping operations and does not look good visually.
735 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
736 while (it
.hasNext()) {
738 it
.value()->setStyleOption(option
);
741 m_sizeHintResolver
->clearCache();
742 m_layouter
->markAsDirty();
743 doLayout(animate
? Animation
: NoAnimation
);
745 if (m_itemSize
.isEmpty()) {
746 updatePreferredColumnWidths();
749 onStyleOptionChanged(option
, previousOption
);
752 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
754 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
755 if (orientation
== previousOrientation
) {
759 m_layouter
->setScrollOrientation(orientation
);
760 m_animation
->setScrollOrientation(orientation
);
761 m_sizeHintResolver
->clearCache();
764 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
765 while (it
.hasNext()) {
767 it
.value()->setScrollOrientation(orientation
);
769 updateGroupHeaderHeight();
773 doLayout(NoAnimation
);
775 onScrollOrientationChanged(orientation
, previousOrientation
);
776 emit
scrollOrientationChanged(orientation
, previousOrientation
);
779 Qt::Orientation
KItemListView::scrollOrientation() const
781 return m_layouter
->scrollOrientation();
784 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
789 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
794 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
799 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
801 Q_UNUSED(changedRoles
);
805 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
811 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
817 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
823 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
829 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
835 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
841 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
847 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
849 Q_UNUSED(supportsExpanding
);
852 void KItemListView::onTransactionBegin()
856 void KItemListView::onTransactionEnd()
860 bool KItemListView::event(QEvent
* event
)
862 // Forward all events to the controller and handle them there
863 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
867 return QGraphicsWidget::event(event
);
870 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
872 m_mousePos
= transform().map(event
->pos());
876 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
878 QGraphicsWidget::mouseMoveEvent(event
);
880 m_mousePos
= transform().map(event
->pos());
881 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
882 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
886 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
888 event
->setAccepted(true);
892 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
894 QGraphicsWidget::dragMoveEvent(event
);
896 m_mousePos
= transform().map(event
->pos());
897 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
898 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
902 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
904 QGraphicsWidget::dragLeaveEvent(event
);
905 setAutoScroll(false);
908 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
910 QGraphicsWidget::dropEvent(event
);
911 setAutoScroll(false);
914 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
916 return m_visibleItems
.values();
919 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
921 if (m_itemSize
.isEmpty()) {
922 updatePreferredColumnWidths(itemRanges
);
925 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
926 if (hasMultipleRanges
) {
930 m_layouter
->markAsDirty();
932 int previouslyInsertedCount
= 0;
933 foreach (const KItemRange
& range
, itemRanges
) {
934 // range.index is related to the model before anything has been inserted.
935 // As in each loop the current item-range gets inserted the index must
936 // be increased by the already previously inserted items.
937 const int index
= range
.index
+ previouslyInsertedCount
;
938 const int count
= range
.count
;
939 if (index
< 0 || count
<= 0) {
940 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
943 previouslyInsertedCount
+= count
;
945 m_sizeHintResolver
->itemsInserted(index
, count
);
947 // Determine which visible items must be moved
948 QList
<int> itemsToMove
;
949 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
950 while (it
.hasNext()) {
952 const int visibleItemIndex
= it
.key();
953 if (visibleItemIndex
>= index
) {
954 itemsToMove
.append(visibleItemIndex
);
958 // Update the indexes of all KItemListWidget instances that are located
959 // after the inserted items. It is important to adjust the indexes in the order
960 // from the highest index to the lowest index to prevent overlaps when setting the new index.
962 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
963 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
965 const int newIndex
= widget
->index() + count
;
966 if (hasMultipleRanges
) {
967 setWidgetIndex(widget
, newIndex
);
969 // Try to animate the moving of the item
970 moveWidgetToIndex(widget
, newIndex
);
974 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
975 // Check whether a scrollbar is required to show the inserted items. In this case
976 // the size of the layouter will be decreased before calling doLayout(): This prevents
977 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
978 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
979 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
980 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
981 if (decreaseLayouterSize
) {
982 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
983 QSizeF layouterSize
= m_layouter
->size();
984 if (verticalScrollOrientation
) {
985 layouterSize
.rwidth() -= scrollBarExtent
;
987 layouterSize
.rheight() -= scrollBarExtent
;
989 m_layouter
->setSize(layouterSize
);
993 if (!hasMultipleRanges
) {
994 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
995 updateSiblingsInformation();
1000 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1003 if (hasMultipleRanges
) {
1005 // Important: Don't read any m_layouter-property inside the for-loop in case if
1006 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1007 // updated in each loop-cycle and has only a consistent state after the loop.
1008 Q_ASSERT(m_layouter
->isDirty());
1010 m_endTransactionAnimationHint
= NoAnimation
;
1013 updateSiblingsInformation();
1016 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1017 // In case if items of the same group have been inserted before an item that
1018 // currently represents the first item of the group, the group header of
1019 // this item must be removed.
1020 updateVisibleGroupHeaders();
1023 if (useAlternateBackgrounds()) {
1024 updateAlternateBackgrounds();
1028 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1030 if (m_itemSize
.isEmpty()) {
1031 // Don't pass the item-range: The preferred column-widths of
1032 // all items must be adjusted when removing items.
1033 updatePreferredColumnWidths();
1036 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1037 if (hasMultipleRanges
) {
1041 m_layouter
->markAsDirty();
1043 int removedItemsCount
= 0;
1044 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1045 removedItemsCount
+= itemRanges
[i
].count
;
1048 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1049 const KItemRange
& range
= itemRanges
[i
];
1050 const int index
= range
.index
;
1051 const int count
= range
.count
;
1052 if (index
< 0 || count
<= 0) {
1053 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1057 m_sizeHintResolver
->itemsRemoved(index
, count
);
1059 const int firstRemovedIndex
= index
;
1060 const int lastRemovedIndex
= index
+ count
- 1;
1061 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1062 removedItemsCount
-= count
;
1064 // Remove all KItemListWidget instances that got deleted
1065 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1066 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1071 m_animation
->stop(widget
);
1072 // Stopping the animation might lead to recycling the widget if
1073 // it is invisible (see slotAnimationFinished()).
1074 // Check again whether it is still visible:
1075 if (!m_visibleItems
.contains(i
)) {
1079 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1080 // Remove the widget without animation
1081 recycleWidget(widget
);
1083 // Animate the removing of the items. Special case: When removing an item there
1084 // is no valid model index available anymore. For the
1085 // remove-animation the item gets removed from m_visibleItems but the widget
1086 // will stay alive until the animation has been finished and will
1087 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1088 m_visibleItems
.remove(i
);
1089 widget
->setIndex(-1);
1090 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1094 // Update the indexes of all KItemListWidget instances that are located
1095 // after the deleted items
1096 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1097 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1099 const int newIndex
= i
- count
;
1100 if (hasMultipleRanges
) {
1101 setWidgetIndex(widget
, newIndex
);
1103 // Try to animate the moving of the item
1104 moveWidgetToIndex(widget
, newIndex
);
1109 if (!hasMultipleRanges
) {
1110 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1111 // assumes an updated geometry. If items are removed during an active transaction,
1112 // the transaction will be temporary deactivated so that doLayout() triggers a
1113 // geometry update if necessary.
1114 const int activeTransactions
= m_activeTransactions
;
1115 m_activeTransactions
= 0;
1116 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1117 m_activeTransactions
= activeTransactions
;
1118 updateSiblingsInformation();
1123 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1126 if (hasMultipleRanges
) {
1128 // Important: Don't read any m_layouter-property inside the for-loop in case if
1129 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1130 // updated in each loop-cycle and has only a consistent state after the loop.
1131 Q_ASSERT(m_layouter
->isDirty());
1133 m_endTransactionAnimationHint
= NoAnimation
;
1135 updateSiblingsInformation();
1138 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1139 // In case if the first item of a group has been removed, the group header
1140 // must be applied to the next visible item.
1141 updateVisibleGroupHeaders();
1144 if (useAlternateBackgrounds()) {
1145 updateAlternateBackgrounds();
1149 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1151 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1152 m_layouter
->markAsDirty();
1155 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1158 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1159 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1161 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1162 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1164 updateWidgetProperties(widget
, index
);
1165 initializeItemListWidget(widget
);
1169 doLayout(NoAnimation
);
1170 updateSiblingsInformation();
1173 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1174 const QSet
<QByteArray
>& roles
)
1176 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1177 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1178 updatePreferredColumnWidths(itemRanges
);
1181 foreach (const KItemRange
& itemRange
, itemRanges
) {
1182 const int index
= itemRange
.index
;
1183 const int count
= itemRange
.count
;
1185 if (updateSizeHints
) {
1186 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1187 m_layouter
->markAsDirty();
1189 if (!m_layoutTimer
->isActive()) {
1190 m_layoutTimer
->start();
1194 // Apply the changed roles to the visible item-widgets
1195 const int lastIndex
= index
+ count
- 1;
1196 for (int i
= index
; i
<= lastIndex
; ++i
) {
1197 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1199 widget
->setData(m_model
->data(i
), roles
);
1203 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1204 // The sort-role has been changed which might result
1205 // in modified group headers
1206 updateVisibleGroupHeaders();
1207 doLayout(NoAnimation
);
1212 void KItemListView::slotGroupedSortingChanged(bool current
)
1214 m_grouped
= current
;
1215 m_layouter
->markAsDirty();
1218 updateGroupHeaderHeight();
1220 // Clear all visible headers
1221 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1222 while (it
.hasNext()) {
1224 recycleGroupHeaderForWidget(it
.key());
1226 Q_ASSERT(m_visibleGroups
.isEmpty());
1229 if (useAlternateBackgrounds()) {
1230 // Changing the group mode requires to update the alternate backgrounds
1231 // as with the enabled group mode the altering is done on base of the first
1233 updateAlternateBackgrounds();
1235 updateSiblingsInformation();
1236 doLayout(NoAnimation
);
1239 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1244 updateVisibleGroupHeaders();
1245 doLayout(NoAnimation
);
1249 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1254 updateVisibleGroupHeaders();
1255 doLayout(NoAnimation
);
1259 void KItemListView::slotCurrentChanged(int current
, int previous
)
1263 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1264 if (previousWidget
) {
1265 previousWidget
->setCurrent(false);
1268 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1269 if (currentWidget
) {
1270 currentWidget
->setCurrent(true);
1272 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1275 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1279 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1280 while (it
.hasNext()) {
1282 const int index
= it
.key();
1283 KItemListWidget
* widget
= it
.value();
1284 widget
->setSelected(current
.contains(index
));
1288 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1289 KItemListViewAnimation::AnimationType type
)
1291 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1292 Q_ASSERT(itemListWidget
);
1295 case KItemListViewAnimation::DeleteAnimation
: {
1296 // As we recycle the widget in this case it is important to assure that no
1297 // other animation has been started. This is a convention in KItemListView and
1298 // not a requirement defined by KItemListViewAnimation.
1299 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1301 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1302 // by m_visibleWidgets and must be deleted manually after the animation has
1304 recycleGroupHeaderForWidget(itemListWidget
);
1305 widgetCreator()->recycle(itemListWidget
);
1309 case KItemListViewAnimation::CreateAnimation
:
1310 case KItemListViewAnimation::MovingAnimation
:
1311 case KItemListViewAnimation::ResizeAnimation
: {
1312 const int index
= itemListWidget
->index();
1313 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1314 (index
> m_layouter
->lastVisibleIndex());
1315 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1316 recycleWidget(itemListWidget
);
1325 void KItemListView::slotLayoutTimerFinished()
1327 m_layouter
->setSize(geometry().size());
1328 doLayout(Animation
);
1331 void KItemListView::slotRubberBandPosChanged()
1336 void KItemListView::slotRubberBandActivationChanged(bool active
)
1339 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1340 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1341 m_skipAutoScrollForRubberBand
= true;
1343 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1344 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1345 m_skipAutoScrollForRubberBand
= false;
1351 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1353 qreal previousWidth
)
1356 Q_UNUSED(currentWidth
);
1357 Q_UNUSED(previousWidth
);
1359 m_headerWidget
->setAutomaticColumnResizing(false);
1360 applyColumnWidthsFromHeader();
1361 doLayout(NoAnimation
);
1364 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1368 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1370 const QList
<QByteArray
> previous
= m_visibleRoles
;
1372 QList
<QByteArray
> current
= m_visibleRoles
;
1373 current
.removeAt(previousIndex
);
1374 current
.insert(currentIndex
, role
);
1376 setVisibleRoles(current
);
1378 emit
visibleRolesChanged(current
, previous
);
1381 void KItemListView::triggerAutoScrolling()
1383 if (!m_autoScrollTimer
) {
1388 int visibleSize
= 0;
1389 if (scrollOrientation() == Qt::Vertical
) {
1390 pos
= m_mousePos
.y();
1391 visibleSize
= size().height();
1393 pos
= m_mousePos
.x();
1394 visibleSize
= size().width();
1397 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1398 m_autoScrollIncrement
= 0;
1401 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1402 if (m_autoScrollIncrement
== 0) {
1403 // The mouse position is not above an autoscroll margin (the autoscroll timer
1404 // will be restarted in mouseMoveEvent())
1405 m_autoScrollTimer
->stop();
1409 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1410 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1411 // if the direction of the rubberband is similar to the autoscroll direction. This
1412 // prevents that starting to create a rubberband within the autoscroll margins starts
1413 // an autoscrolling.
1415 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1416 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1417 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1418 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1419 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1420 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1421 // been moved up although the autoscroll direction might be down)
1422 m_autoScrollTimer
->stop();
1427 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1428 // the autoscrolling may not get skipped anymore until a new rubberband is created
1429 m_skipAutoScrollForRubberBand
= false;
1431 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1432 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1433 setScrollOffset(newScrollOffset
);
1435 // Trigger the autoscroll timer which will periodically call
1436 // triggerAutoScrolling()
1437 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1440 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1442 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1444 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1445 Q_ASSERT(groupHeader
);
1446 updateGroupHeaderLayout(widget
);
1449 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1451 emit
roleEditingCanceled(index
, role
, value
);
1452 m_editingRole
= false;
1455 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1457 emit
roleEditingFinished(index
, role
, value
);
1458 m_editingRole
= false;
1461 void KItemListView::setController(KItemListController
* controller
)
1463 if (m_controller
!= controller
) {
1464 KItemListController
* previous
= m_controller
;
1466 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1467 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1468 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1471 m_controller
= controller
;
1474 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1475 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1476 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1479 onControllerChanged(controller
, previous
);
1483 void KItemListView::setModel(KItemModelBase
* model
)
1485 if (m_model
== model
) {
1489 KItemModelBase
* previous
= m_model
;
1492 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1493 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1494 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1495 this, SLOT(slotItemsInserted(KItemRangeList
)));
1496 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1497 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1498 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1499 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1500 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1501 this, SLOT(slotGroupedSortingChanged(bool)));
1502 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1503 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1504 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1505 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1508 m_sizeHintResolver
->clearCache();
1511 m_layouter
->setModel(model
);
1512 m_grouped
= model
->groupedSorting();
1515 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1516 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1517 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1518 this, SLOT(slotItemsInserted(KItemRangeList
)));
1519 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1520 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1521 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1522 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1523 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1524 this, SLOT(slotGroupedSortingChanged(bool)));
1525 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1526 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1527 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1528 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1530 const int itemCount
= m_model
->count();
1531 if (itemCount
> 0) {
1532 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1533 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1537 onModelChanged(model
, previous
);
1540 KItemListRubberBand
* KItemListView::rubberBand() const
1542 return m_rubberBand
;
1545 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1547 if (m_layoutTimer
->isActive()) {
1548 m_layoutTimer
->stop();
1551 if (m_activeTransactions
> 0) {
1552 if (hint
== NoAnimation
) {
1553 // As soon as at least one property change should be done without animation,
1554 // the whole transaction will be marked as not animated.
1555 m_endTransactionAnimationHint
= NoAnimation
;
1560 if (!m_model
|| m_model
->count() < 0) {
1564 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1565 if (firstVisibleIndex
< 0) {
1566 emitOffsetChanges();
1570 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1571 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1572 // is still shown if the maximum offset got decreased.
1573 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1574 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1575 if (scrollOffset() > maxOffsetToShowFullRange
) {
1576 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1577 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1580 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1582 int firstSibblingIndex
= -1;
1583 int lastSibblingIndex
= -1;
1584 const bool supportsExpanding
= supportsItemExpanding();
1586 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1588 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1589 // instances from invisible items are reused. If no reusable items are
1590 // found then new KItemListWidget instances get created.
1591 const bool animate
= (hint
== Animation
);
1592 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1593 bool applyNewPos
= true;
1594 bool wasHidden
= false;
1596 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1597 const QPointF newPos
= itemBounds
.topLeft();
1598 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1601 if (!reusableItems
.isEmpty()) {
1602 // Reuse a KItemListWidget instance from an invisible item
1603 const int oldIndex
= reusableItems
.takeLast();
1604 widget
= m_visibleItems
.value(oldIndex
);
1605 setWidgetIndex(widget
, i
);
1606 updateWidgetProperties(widget
, i
);
1607 initializeItemListWidget(widget
);
1609 // No reusable KItemListWidget instance is available, create a new one
1610 widget
= createWidget(i
);
1612 widget
->resize(itemBounds
.size());
1614 if (animate
&& changedCount
< 0) {
1615 // Items have been deleted, move the created item to the
1616 // imaginary old position. They will get animated to the new position
1618 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1619 if (itemRect
.isEmpty()) {
1620 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1621 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1622 widget
->setPos(invisibleOldPos
);
1624 widget
->setPos(itemRect
.topLeft());
1626 applyNewPos
= false;
1629 if (supportsExpanding
&& changedCount
== 0) {
1630 if (firstSibblingIndex
< 0) {
1631 firstSibblingIndex
= i
;
1633 lastSibblingIndex
= i
;
1638 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1639 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1640 applyNewPos
= false;
1643 const bool itemsRemoved
= (changedCount
< 0);
1644 const bool itemsInserted
= (changedCount
> 0);
1645 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1646 // The item is located after the removed items. Animate the moving of the position.
1647 applyNewPos
= !moveWidget(widget
, newPos
);
1648 } else if (itemsInserted
&& i
>= changedIndex
) {
1649 // The item is located after the first inserted item
1650 if (i
<= changedIndex
+ changedCount
- 1) {
1651 // The item is an inserted item. Animate the appearing of the item.
1652 // For performance reasons no animation is done when changedCount is equal
1653 // to all available items.
1654 if (changedCount
< m_model
->count()) {
1655 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1657 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1658 // The item was already there before, so animate the moving of the position.
1659 // No moving animation is done if the item is animated by a create animation: This
1660 // prevents a "move animation mess" when inserting several ranges in parallel.
1661 applyNewPos
= !moveWidget(widget
, newPos
);
1663 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1664 // The size of the view might have been changed. Animate the moving of the position.
1665 applyNewPos
= !moveWidget(widget
, newPos
);
1668 m_animation
->stop(widget
);
1672 widget
->setPos(newPos
);
1675 Q_ASSERT(widget
->index() == i
);
1676 widget
->setVisible(true);
1678 if (widget
->size() != itemBounds
.size()) {
1679 // Resize the widget for the item to the changed size.
1681 // If a dynamic item size is used then no animation is done in the direction
1682 // of the dynamic size.
1683 if (m_itemSize
.width() <= 0) {
1684 // The width is dynamic, apply the new width without animation.
1685 widget
->resize(itemBounds
.width(), widget
->size().height());
1686 } else if (m_itemSize
.height() <= 0) {
1687 // The height is dynamic, apply the new height without animation.
1688 widget
->resize(widget
->size().width(), itemBounds
.height());
1690 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1692 widget
->resize(itemBounds
.size());
1696 // Updating the cell-information must be done as last step: The decision whether the
1697 // moving-animation should be started at all is based on the previous cell-information.
1698 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1699 m_visibleCells
.insert(i
, cell
);
1702 // Delete invisible KItemListWidget instances that have not been reused
1703 foreach (int index
, reusableItems
) {
1704 recycleWidget(m_visibleItems
.value(index
));
1707 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1708 Q_ASSERT(lastSibblingIndex
>= 0);
1709 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1713 // Update the layout of all visible group headers
1714 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1715 while (it
.hasNext()) {
1717 updateGroupHeaderLayout(it
.key());
1721 emitOffsetChanges();
1724 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1725 int lastVisibleIndex
,
1726 LayoutAnimationHint hint
)
1728 // Determine all items that are completely invisible and might be
1729 // reused for items that just got (at least partly) visible. If the
1730 // animation hint is set to 'Animation' items that do e.g. an animated
1731 // moving of their position are not marked as invisible: This assures
1732 // that a scrolling inside the view can be done without breaking an animation.
1736 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1737 while (it
.hasNext()) {
1740 KItemListWidget
* widget
= it
.value();
1741 const int index
= widget
->index();
1742 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1745 if (m_animation
->isStarted(widget
)) {
1746 if (hint
== NoAnimation
) {
1747 // Stopping the animation will call KItemListView::slotAnimationFinished()
1748 // and the widget will be recycled if necessary there.
1749 m_animation
->stop(widget
);
1752 widget
->setVisible(false);
1753 items
.append(index
);
1756 recycleGroupHeaderForWidget(widget
);
1765 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1767 if (widget
->pos() == newPos
) {
1771 bool startMovingAnim
= false;
1773 if (m_itemSize
.isEmpty()) {
1774 // The items are not aligned in a grid but either as columns or rows.
1775 startMovingAnim
= true;
1777 // When having a grid the moving-animation should only be started, if it is done within
1778 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1779 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1780 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1781 const int index
= widget
->index();
1782 const Cell cell
= m_visibleCells
.value(index
);
1783 if (cell
.column
>= 0 && cell
.row
>= 0) {
1784 if (scrollOrientation() == Qt::Vertical
) {
1785 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1787 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1792 if (startMovingAnim
) {
1793 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1797 m_animation
->stop(widget
);
1798 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1802 void KItemListView::emitOffsetChanges()
1804 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1805 if (m_oldScrollOffset
!= newScrollOffset
) {
1806 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1807 m_oldScrollOffset
= newScrollOffset
;
1810 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1811 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1812 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1813 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1816 const qreal newItemOffset
= m_layouter
->itemOffset();
1817 if (m_oldItemOffset
!= newItemOffset
) {
1818 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1819 m_oldItemOffset
= newItemOffset
;
1822 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1823 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1824 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1825 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1829 KItemListWidget
* KItemListView::createWidget(int index
)
1831 KItemListWidget
* widget
= widgetCreator()->create(this);
1832 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1834 m_visibleItems
.insert(index
, widget
);
1835 m_visibleCells
.insert(index
, Cell());
1836 updateWidgetProperties(widget
, index
);
1837 initializeItemListWidget(widget
);
1841 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1844 recycleGroupHeaderForWidget(widget
);
1847 const int index
= widget
->index();
1848 m_visibleItems
.remove(index
);
1849 m_visibleCells
.remove(index
);
1851 widgetCreator()->recycle(widget
);
1854 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1856 const int oldIndex
= widget
->index();
1857 m_visibleItems
.remove(oldIndex
);
1858 m_visibleCells
.remove(oldIndex
);
1860 m_visibleItems
.insert(index
, widget
);
1861 m_visibleCells
.insert(index
, Cell());
1863 widget
->setIndex(index
);
1866 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1868 const int oldIndex
= widget
->index();
1869 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1871 setWidgetIndex(widget
, index
);
1873 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1874 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1875 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1876 (!vertical
&& oldCell
.column
== newCell
.column
);
1878 m_visibleCells
.insert(index
, newCell
);
1882 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1885 case LayouterSize
: m_layouter
->setSize(size
); break;
1886 case ItemSize
: m_layouter
->setItemSize(size
); break;
1891 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1893 widget
->setVisibleRoles(m_visibleRoles
);
1894 updateWidgetColumnWidths(widget
);
1895 widget
->setStyleOption(m_styleOption
);
1897 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1898 widget
->setCurrent(index
== selectionManager
->currentItem());
1899 widget
->setSelected(selectionManager
->isSelected(index
));
1900 widget
->setHovered(false);
1901 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1902 widget
->setIndex(index
);
1903 widget
->setData(m_model
->data(index
));
1904 widget
->setSiblingsInformation(QBitArray());
1905 updateAlternateBackgroundForWidget(widget
);
1908 updateGroupHeaderForWidget(widget
);
1912 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1914 Q_ASSERT(m_grouped
);
1916 const int index
= widget
->index();
1917 if (!m_layouter
->isFirstGroupItem(index
)) {
1918 // The widget does not represent the first item of a group
1919 // and hence requires no header
1920 recycleGroupHeaderForWidget(widget
);
1924 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1925 if (groups
.isEmpty() || !groupHeaderCreator()) {
1929 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1931 groupHeader
= groupHeaderCreator()->create(this);
1932 groupHeader
->setParentItem(widget
);
1933 m_visibleGroups
.insert(widget
, groupHeader
);
1934 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1936 Q_ASSERT(groupHeader
->parentItem() == widget
);
1938 const int groupIndex
= groupIndexForItem(index
);
1939 Q_ASSERT(groupIndex
>= 0);
1940 groupHeader
->setData(groups
.at(groupIndex
).second
);
1941 groupHeader
->setRole(model()->sortRole());
1942 groupHeader
->setStyleOption(m_styleOption
);
1943 groupHeader
->setScrollOrientation(scrollOrientation());
1944 groupHeader
->setItemIndex(index
);
1946 groupHeader
->show();
1949 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1951 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1952 Q_ASSERT(groupHeader
);
1954 const int index
= widget
->index();
1955 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1956 const QRectF itemRect
= m_layouter
->itemRect(index
);
1958 // The group-header is a child of the itemlist widget. Translate the
1959 // group header position to the relative position.
1960 if (scrollOrientation() == Qt::Vertical
) {
1961 // In the vertical scroll orientation the group header should always span
1962 // the whole width no matter which temporary position the parent widget
1963 // has. In this case the x-position and width will be adjusted manually.
1964 const qreal x
= -widget
->x() - itemOffset();
1965 const qreal width
= maximumItemOffset();
1966 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1967 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1969 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1970 groupHeader
->resize(groupHeaderRect
.size());
1974 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1976 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1978 header
->setParentItem(0);
1979 groupHeaderCreator()->recycle(header
);
1980 m_visibleGroups
.remove(widget
);
1981 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1985 void KItemListView::updateVisibleGroupHeaders()
1987 Q_ASSERT(m_grouped
);
1988 m_layouter
->markAsDirty();
1990 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1991 while (it
.hasNext()) {
1993 updateGroupHeaderForWidget(it
.value());
1997 int KItemListView::groupIndexForItem(int index
) const
1999 Q_ASSERT(m_grouped
);
2001 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2002 if (groups
.isEmpty()) {
2007 int max
= groups
.count() - 1;
2010 mid
= (min
+ max
) / 2;
2011 if (index
> groups
[mid
].first
) {
2016 } while (groups
[mid
].first
!= index
&& min
<= max
);
2019 while (groups
[mid
].first
> index
&& mid
> 0) {
2027 void KItemListView::updateAlternateBackgrounds()
2029 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2030 while (it
.hasNext()) {
2032 updateAlternateBackgroundForWidget(it
.value());
2036 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2038 bool enabled
= useAlternateBackgrounds();
2040 const int index
= widget
->index();
2041 enabled
= (index
& 0x1) > 0;
2043 const int groupIndex
= groupIndexForItem(index
);
2044 if (groupIndex
>= 0) {
2045 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2046 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2047 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2048 enabled
= (relativeIndex
& 0x1) > 0;
2052 widget
->setAlternateBackground(enabled
);
2055 bool KItemListView::useAlternateBackgrounds() const
2057 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2060 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2062 QElapsedTimer timer
;
2065 QHash
<QByteArray
, qreal
> widths
;
2067 // Calculate the minimum width for each column that is required
2068 // to show the headline unclipped.
2069 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2070 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2071 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2072 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2073 const QString headerText
= m_model
->roleDescription(visibleRole
);
2074 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2075 widths
.insert(visibleRole
, headerWidth
);
2078 // Calculate the preferred column withs for each item and ignore values
2079 // smaller than the width for showing the headline unclipped.
2080 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2081 int calculatedItemCount
= 0;
2082 bool maxTimeExceeded
= false;
2083 foreach (const KItemRange
& itemRange
, itemRanges
) {
2084 const int startIndex
= itemRange
.index
;
2085 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2087 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2088 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2089 qreal maxWidth
= widths
.value(visibleRole
, 0);
2090 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2091 maxWidth
= qMax(width
, maxWidth
);
2092 widths
.insert(visibleRole
, maxWidth
);
2095 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2096 // When having several thousands of items calculating the sizes can get
2097 // very expensive. We accept a possibly too small role-size in favour
2098 // of having no blocking user interface.
2099 maxTimeExceeded
= true;
2102 ++calculatedItemCount
;
2104 if (maxTimeExceeded
) {
2112 void KItemListView::applyColumnWidthsFromHeader()
2114 // Apply the new size to the layouter
2115 const qreal requiredWidth
= columnWidthsSum();
2116 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2117 m_itemSize
.height());
2118 m_layouter
->setItemSize(dynamicItemSize
);
2120 // Update the role sizes for all visible widgets
2121 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2122 while (it
.hasNext()) {
2124 updateWidgetColumnWidths(it
.value());
2128 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2130 foreach (const QByteArray
& role
, m_visibleRoles
) {
2131 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2135 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2137 Q_ASSERT(m_itemSize
.isEmpty());
2138 const int itemCount
= m_model
->count();
2139 int rangesItemCount
= 0;
2140 foreach (const KItemRange
& range
, itemRanges
) {
2141 rangesItemCount
+= range
.count
;
2144 if (itemCount
== rangesItemCount
) {
2145 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2146 foreach (const QByteArray
& role
, m_visibleRoles
) {
2147 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2150 // Only a sub range of the roles need to be determined.
2151 // The chances are good that the widths of the sub ranges
2152 // already fit into the available widths and hence no
2153 // expensive update might be required.
2154 bool changed
= false;
2156 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2157 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2158 while (it
.hasNext()) {
2160 const QByteArray
& role
= it
.key();
2161 const qreal updatedWidth
= it
.value();
2162 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2163 if (updatedWidth
> currentWidth
) {
2164 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2170 // All the updated sizes are smaller than the current sizes and no change
2171 // of the stretched roles-widths is required
2176 if (m_headerWidget
->automaticColumnResizing()) {
2177 applyAutomaticColumnWidths();
2181 void KItemListView::updatePreferredColumnWidths()
2184 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2188 void KItemListView::applyAutomaticColumnWidths()
2190 Q_ASSERT(m_itemSize
.isEmpty());
2191 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2192 if (m_visibleRoles
.isEmpty()) {
2196 // Calculate the maximum size of an item by considering the
2197 // visible role sizes and apply them to the layouter. If the
2198 // size does not use the available view-size the size of the
2199 // first role will get stretched.
2201 foreach (const QByteArray
& role
, m_visibleRoles
) {
2202 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2203 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2206 const QByteArray firstRole
= m_visibleRoles
.first();
2207 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2208 QSizeF dynamicItemSize
= m_itemSize
;
2210 qreal requiredWidth
= columnWidthsSum();
2211 const qreal availableWidth
= size().width();
2212 if (requiredWidth
< availableWidth
) {
2213 // Stretch the first column to use the whole remaining width
2214 firstColumnWidth
+= availableWidth
- requiredWidth
;
2215 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2216 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2217 // Shrink the first column to be able to show as much other
2218 // columns as possible
2219 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2221 // TODO: A proper calculation of the minimum width depends on the implementation
2222 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2224 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2225 if (shrinkedFirstColumnWidth
< minWidth
) {
2226 shrinkedFirstColumnWidth
= minWidth
;
2229 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2230 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2233 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2235 m_layouter
->setItemSize(dynamicItemSize
);
2237 // Update the role sizes for all visible widgets
2238 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2239 while (it
.hasNext()) {
2241 updateWidgetColumnWidths(it
.value());
2245 qreal
KItemListView::columnWidthsSum() const
2247 qreal widthsSum
= 0;
2248 foreach (const QByteArray
& role
, m_visibleRoles
) {
2249 widthsSum
+= m_headerWidget
->columnWidth(role
);
2254 QRectF
KItemListView::headerBoundaries() const
2256 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2259 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2260 const QSizeF
& newItemSize
,
2261 const QSizeF
& newItemMargin
) const
2263 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2267 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2268 const qreal itemWidth
= m_layouter
->itemSize().width();
2269 if (itemWidth
> 0) {
2270 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2271 newItemSize
.width(),
2272 newItemMargin
.width());
2273 if (m_model
->count() > newColumnCount
) {
2274 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2276 m_layouter
->itemMargin().width());
2277 return oldColumnCount
!= newColumnCount
;
2281 const qreal itemHeight
= m_layouter
->itemSize().height();
2282 if (itemHeight
> 0) {
2283 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2284 newItemSize
.height(),
2285 newItemMargin
.height());
2286 if (m_model
->count() > newRowCount
) {
2287 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2289 m_layouter
->itemMargin().height());
2290 return oldRowCount
!= newRowCount
;
2298 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2300 if (m_itemSize
.isEmpty()) {
2301 // We have only columns or only rows, but no grid: An animation is usually
2302 // welcome when inserting or removing items.
2303 return !supportsItemExpanding();
2306 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2310 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2311 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2312 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2313 // Only animate if up to 2/3 of a row or column are inserted or removed
2314 return changedItemCount
<= maximum
* 2 / 3;
2318 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2320 const QSizeF oldSize
= m_layouter
->size();
2322 m_layouter
->setSize(size
);
2323 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2324 m_layouter
->setSize(oldSize
);
2326 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2327 : maxOffset
> size
.width();
2330 int KItemListView::showDropIndicator(const QPointF
& pos
)
2332 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2333 while (it
.hasNext()) {
2335 const KItemListWidget
* widget
= it
.value();
2337 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2338 const QRectF rect
= itemRect(widget
->index());
2339 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2340 if (m_model
->supportsDropping(widget
->index())) {
2341 const int gap
= qMax(4, m_styleOption
.padding
);
2342 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2347 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2348 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2350 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2351 if (m_dropIndicator
!= draggingInsertIndicator
) {
2352 m_dropIndicator
= draggingInsertIndicator
;
2356 int index
= widget
->index();
2364 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2365 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2368 void KItemListView::hideDropIndicator()
2370 if (!m_dropIndicator
.isNull()) {
2371 m_dropIndicator
= QRectF();
2376 void KItemListView::updateGroupHeaderHeight()
2378 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2379 qreal groupHeaderMargin
= 0;
2381 if (scrollOrientation() == Qt::Horizontal
) {
2382 // The vertical margin above and below the header should be
2383 // equal to the horizontal margin, not the vertical margin
2384 // from m_styleOption.
2385 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2386 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2387 } else if (m_itemSize
.isEmpty()){
2388 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2389 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2391 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2392 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2394 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2395 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2397 updateVisibleGroupHeaders();
2400 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2402 if (!supportsItemExpanding() || !m_model
) {
2406 if (firstIndex
< 0 || lastIndex
< 0) {
2407 firstIndex
= m_layouter
->firstVisibleIndex();
2408 lastIndex
= m_layouter
->lastVisibleIndex();
2410 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2411 lastIndex
>= m_layouter
->firstVisibleIndex());
2412 if (!isRangeVisible
) {
2417 int previousParents
= 0;
2418 QBitArray previousSiblings
;
2420 // The rootIndex describes the first index where the siblings get
2421 // calculated from. For the calculation the upper most parent item
2422 // is required. For performance reasons it is checked first whether
2423 // the visible items before or after the current range already
2424 // contain a siblings information which can be used as base.
2425 int rootIndex
= firstIndex
;
2427 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2429 // There is no visible widget before the range, check whether there
2430 // is one after the range:
2431 widget
= m_visibleItems
.value(lastIndex
+ 1);
2433 // The sibling information of the widget may only be used if
2434 // all items of the range have the same number of parents.
2435 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2436 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2437 if (m_model
->expandedParentsCount(i
) != parents
) {
2446 // Performance optimization: Use the sibling information of the visible
2447 // widget beside the given range.
2448 previousSiblings
= widget
->siblingsInformation();
2449 if (previousSiblings
.isEmpty()) {
2452 previousParents
= previousSiblings
.count() - 1;
2453 previousSiblings
.truncate(previousParents
);
2455 // Potentially slow path: Go back to the upper most parent of firstIndex
2456 // to be able to calculate the initial value for the siblings.
2457 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2462 Q_ASSERT(previousParents
>= 0);
2463 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2464 // Update the parent-siblings in case if the current item represents
2465 // a child or an upper parent.
2466 const int currentParents
= m_model
->expandedParentsCount(i
);
2467 Q_ASSERT(currentParents
>= 0);
2468 if (previousParents
< currentParents
) {
2469 previousParents
= currentParents
;
2470 previousSiblings
.resize(currentParents
);
2471 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2472 } else if (previousParents
> currentParents
) {
2473 previousParents
= currentParents
;
2474 previousSiblings
.truncate(currentParents
);
2477 if (i
>= firstIndex
) {
2478 // The index represents a visible item. Apply the parent-siblings
2479 // and update the sibling of the current item.
2480 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2485 QBitArray siblings
= previousSiblings
;
2486 siblings
.resize(siblings
.count() + 1);
2487 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2489 widget
->setSiblingsInformation(siblings
);
2494 bool KItemListView::hasSiblingSuccessor(int index
) const
2496 bool hasSuccessor
= false;
2497 const int parentsCount
= m_model
->expandedParentsCount(index
);
2498 int successorIndex
= index
+ 1;
2500 // Search the next sibling
2501 const int itemCount
= m_model
->count();
2502 while (successorIndex
< itemCount
) {
2503 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2504 if (currentParentsCount
== parentsCount
) {
2505 hasSuccessor
= true;
2507 } else if (currentParentsCount
< parentsCount
) {
2513 if (m_grouped
&& hasSuccessor
) {
2514 // If the sibling is part of another group, don't mark it as
2515 // successor as the group header is between the sibling connections.
2516 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2517 if (m_layouter
->isFirstGroupItem(i
)) {
2518 hasSuccessor
= false;
2524 return hasSuccessor
;
2527 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2531 const int minSpeed
= 4;
2532 const int maxSpeed
= 128;
2533 const int speedLimiter
= 96;
2534 const int autoScrollBorder
= 64;
2536 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2537 // This assures that the autoscrolling speed grows gradually.
2538 const int incLimiter
= 1;
2540 if (pos
< autoScrollBorder
) {
2541 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2542 inc
= qMax(inc
, -maxSpeed
);
2543 inc
= qMax(inc
, oldInc
- incLimiter
);
2544 } else if (pos
> range
- autoScrollBorder
) {
2545 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2546 inc
= qMin(inc
, maxSpeed
);
2547 inc
= qMin(inc
, oldInc
+ incLimiter
);
2553 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2555 const qreal availableSize
= size
- itemMargin
;
2556 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2562 KItemListCreatorBase::~KItemListCreatorBase()
2564 qDeleteAll(m_recycleableWidgets
);
2565 qDeleteAll(m_createdWidgets
);
2568 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2570 m_createdWidgets
.insert(widget
);
2573 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2575 Q_ASSERT(m_createdWidgets
.contains(widget
));
2576 m_createdWidgets
.remove(widget
);
2578 if (m_recycleableWidgets
.count() < 100) {
2579 m_recycleableWidgets
.append(widget
);
2580 widget
->setVisible(false);
2586 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2588 if (m_recycleableWidgets
.isEmpty()) {
2592 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2593 m_createdWidgets
.insert(widget
);
2597 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2601 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2603 widget
->setParentItem(0);
2604 widget
->setOpacity(1.0);
2605 pushRecycleableWidget(widget
);
2608 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2612 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2614 header
->setOpacity(1.0);
2615 pushRecycleableWidget(header
);
2618 #include "kitemlistview.moc"