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 KItemListViewLayouter
* KItemListView::layouter() const
667 void KItemListView::setItemSize(const QSizeF
& size
)
669 const QSizeF previousSize
= m_itemSize
;
670 if (size
== previousSize
) {
674 // Skip animations when the number of rows or columns
675 // are changed in the grid layout. Although the animation
676 // engine can handle this usecase, it looks obtrusive.
677 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
679 m_layouter
->itemMargin());
681 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
682 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
683 (!m_itemSize
.isEmpty() && size
.isEmpty()));
687 if (alternateBackgroundsChanged
) {
688 // For an empty item size alternate backgrounds are drawn if more than
689 // one role is shown. Assure that the backgrounds for visible items are
690 // updated when changing the size in this context.
691 updateAlternateBackgrounds();
694 if (size
.isEmpty()) {
695 if (m_headerWidget
->automaticColumnResizing()) {
696 updatePreferredColumnWidths();
698 // Only apply the changed height and respect the header widths
700 const qreal currentWidth
= m_layouter
->itemSize().width();
701 const QSizeF
newSize(currentWidth
, size
.height());
702 m_layouter
->setItemSize(newSize
);
705 m_layouter
->setItemSize(size
);
708 m_sizeHintResolver
->clearCache();
709 doLayout(animate
? Animation
: NoAnimation
);
710 onItemSizeChanged(size
, previousSize
);
713 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
715 const KItemListStyleOption previousOption
= m_styleOption
;
716 m_styleOption
= option
;
719 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
720 if (margin
!= m_layouter
->itemMargin()) {
721 // Skip animations when the number of rows or columns
722 // are changed in the grid layout. Although the animation
723 // engine can handle this usecase, it looks obtrusive.
724 animate
= !changesItemGridLayout(m_layouter
->size(),
725 m_layouter
->itemSize(),
727 m_layouter
->setItemMargin(margin
);
731 updateGroupHeaderHeight();
734 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
735 // Animating a change of the maximum text size just results in expensive
736 // temporary eliding and clipping operations and does not look good visually.
740 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
741 while (it
.hasNext()) {
743 it
.value()->setStyleOption(option
);
746 m_sizeHintResolver
->clearCache();
747 m_layouter
->markAsDirty();
748 doLayout(animate
? Animation
: NoAnimation
);
750 if (m_itemSize
.isEmpty()) {
751 updatePreferredColumnWidths();
754 onStyleOptionChanged(option
, previousOption
);
757 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
759 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
760 if (orientation
== previousOrientation
) {
764 m_layouter
->setScrollOrientation(orientation
);
765 m_animation
->setScrollOrientation(orientation
);
766 m_sizeHintResolver
->clearCache();
769 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
770 while (it
.hasNext()) {
772 it
.value()->setScrollOrientation(orientation
);
774 updateGroupHeaderHeight();
778 doLayout(NoAnimation
);
780 onScrollOrientationChanged(orientation
, previousOrientation
);
781 emit
scrollOrientationChanged(orientation
, previousOrientation
);
784 Qt::Orientation
KItemListView::scrollOrientation() const
786 return m_layouter
->scrollOrientation();
789 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
794 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
799 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
804 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
806 Q_UNUSED(changedRoles
);
810 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
816 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
822 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
828 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
834 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
840 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
846 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
852 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
854 Q_UNUSED(supportsExpanding
);
857 void KItemListView::onTransactionBegin()
861 void KItemListView::onTransactionEnd()
865 bool KItemListView::event(QEvent
* event
)
867 // Forward all events to the controller and handle them there
868 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
872 return QGraphicsWidget::event(event
);
875 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
877 m_mousePos
= transform().map(event
->pos());
881 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
883 QGraphicsWidget::mouseMoveEvent(event
);
885 m_mousePos
= transform().map(event
->pos());
886 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
887 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
891 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
893 event
->setAccepted(true);
897 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
899 QGraphicsWidget::dragMoveEvent(event
);
901 m_mousePos
= transform().map(event
->pos());
902 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
903 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
907 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
909 QGraphicsWidget::dragLeaveEvent(event
);
910 setAutoScroll(false);
913 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
915 QGraphicsWidget::dropEvent(event
);
916 setAutoScroll(false);
919 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
921 return m_visibleItems
.values();
924 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
926 if (m_itemSize
.isEmpty()) {
927 updatePreferredColumnWidths(itemRanges
);
930 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
931 if (hasMultipleRanges
) {
935 m_layouter
->markAsDirty();
937 int previouslyInsertedCount
= 0;
938 foreach (const KItemRange
& range
, itemRanges
) {
939 // range.index is related to the model before anything has been inserted.
940 // As in each loop the current item-range gets inserted the index must
941 // be increased by the already previously inserted items.
942 const int index
= range
.index
+ previouslyInsertedCount
;
943 const int count
= range
.count
;
944 if (index
< 0 || count
<= 0) {
945 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
948 previouslyInsertedCount
+= count
;
950 m_sizeHintResolver
->itemsInserted(index
, count
);
952 // Determine which visible items must be moved
953 QList
<int> itemsToMove
;
954 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
955 while (it
.hasNext()) {
957 const int visibleItemIndex
= it
.key();
958 if (visibleItemIndex
>= index
) {
959 itemsToMove
.append(visibleItemIndex
);
963 // Update the indexes of all KItemListWidget instances that are located
964 // after the inserted items. It is important to adjust the indexes in the order
965 // from the highest index to the lowest index to prevent overlaps when setting the new index.
967 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
968 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
970 const int newIndex
= widget
->index() + count
;
971 if (hasMultipleRanges
) {
972 setWidgetIndex(widget
, newIndex
);
974 // Try to animate the moving of the item
975 moveWidgetToIndex(widget
, newIndex
);
979 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
980 // Check whether a scrollbar is required to show the inserted items. In this case
981 // the size of the layouter will be decreased before calling doLayout(): This prevents
982 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
983 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
984 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
985 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
986 if (decreaseLayouterSize
) {
987 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
988 QSizeF layouterSize
= m_layouter
->size();
989 if (verticalScrollOrientation
) {
990 layouterSize
.rwidth() -= scrollBarExtent
;
992 layouterSize
.rheight() -= scrollBarExtent
;
994 m_layouter
->setSize(layouterSize
);
998 if (!hasMultipleRanges
) {
999 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1000 updateSiblingsInformation();
1005 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1008 if (hasMultipleRanges
) {
1010 // Important: Don't read any m_layouter-property inside the for-loop in case if
1011 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1012 // updated in each loop-cycle and has only a consistent state after the loop.
1013 Q_ASSERT(m_layouter
->isDirty());
1015 m_endTransactionAnimationHint
= NoAnimation
;
1018 updateSiblingsInformation();
1021 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1022 // In case if items of the same group have been inserted before an item that
1023 // currently represents the first item of the group, the group header of
1024 // this item must be removed.
1025 updateVisibleGroupHeaders();
1028 if (useAlternateBackgrounds()) {
1029 updateAlternateBackgrounds();
1033 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1035 if (m_itemSize
.isEmpty()) {
1036 // Don't pass the item-range: The preferred column-widths of
1037 // all items must be adjusted when removing items.
1038 updatePreferredColumnWidths();
1041 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1042 if (hasMultipleRanges
) {
1046 m_layouter
->markAsDirty();
1048 int removedItemsCount
= 0;
1049 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1050 removedItemsCount
+= itemRanges
[i
].count
;
1053 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1054 const KItemRange
& range
= itemRanges
[i
];
1055 const int index
= range
.index
;
1056 const int count
= range
.count
;
1057 if (index
< 0 || count
<= 0) {
1058 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1062 m_sizeHintResolver
->itemsRemoved(index
, count
);
1064 const int firstRemovedIndex
= index
;
1065 const int lastRemovedIndex
= index
+ count
- 1;
1066 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1067 removedItemsCount
-= count
;
1069 // Remove all KItemListWidget instances that got deleted
1070 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1071 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1076 m_animation
->stop(widget
);
1077 // Stopping the animation might lead to recycling the widget if
1078 // it is invisible (see slotAnimationFinished()).
1079 // Check again whether it is still visible:
1080 if (!m_visibleItems
.contains(i
)) {
1084 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1085 // Remove the widget without animation
1086 recycleWidget(widget
);
1088 // Animate the removing of the items. Special case: When removing an item there
1089 // is no valid model index available anymore. For the
1090 // remove-animation the item gets removed from m_visibleItems but the widget
1091 // will stay alive until the animation has been finished and will
1092 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1093 m_visibleItems
.remove(i
);
1094 widget
->setIndex(-1);
1095 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1099 // Update the indexes of all KItemListWidget instances that are located
1100 // after the deleted items
1101 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1102 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1104 const int newIndex
= i
- count
;
1105 if (hasMultipleRanges
) {
1106 setWidgetIndex(widget
, newIndex
);
1108 // Try to animate the moving of the item
1109 moveWidgetToIndex(widget
, newIndex
);
1114 if (!hasMultipleRanges
) {
1115 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1116 // assumes an updated geometry. If items are removed during an active transaction,
1117 // the transaction will be temporary deactivated so that doLayout() triggers a
1118 // geometry update if necessary.
1119 const int activeTransactions
= m_activeTransactions
;
1120 m_activeTransactions
= 0;
1121 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1122 m_activeTransactions
= activeTransactions
;
1123 updateSiblingsInformation();
1128 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1131 if (hasMultipleRanges
) {
1133 // Important: Don't read any m_layouter-property inside the for-loop in case if
1134 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1135 // updated in each loop-cycle and has only a consistent state after the loop.
1136 Q_ASSERT(m_layouter
->isDirty());
1138 m_endTransactionAnimationHint
= NoAnimation
;
1140 updateSiblingsInformation();
1143 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1144 // In case if the first item of a group has been removed, the group header
1145 // must be applied to the next visible item.
1146 updateVisibleGroupHeaders();
1149 if (useAlternateBackgrounds()) {
1150 updateAlternateBackgrounds();
1154 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1156 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1157 m_layouter
->markAsDirty();
1160 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1163 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1164 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1166 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1167 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1169 updateWidgetProperties(widget
, index
);
1170 initializeItemListWidget(widget
);
1174 doLayout(NoAnimation
);
1175 updateSiblingsInformation();
1178 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1179 const QSet
<QByteArray
>& roles
)
1181 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1182 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1183 updatePreferredColumnWidths(itemRanges
);
1186 foreach (const KItemRange
& itemRange
, itemRanges
) {
1187 const int index
= itemRange
.index
;
1188 const int count
= itemRange
.count
;
1190 if (updateSizeHints
) {
1191 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1192 m_layouter
->markAsDirty();
1194 if (!m_layoutTimer
->isActive()) {
1195 m_layoutTimer
->start();
1199 // Apply the changed roles to the visible item-widgets
1200 const int lastIndex
= index
+ count
- 1;
1201 for (int i
= index
; i
<= lastIndex
; ++i
) {
1202 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1204 widget
->setData(m_model
->data(i
), roles
);
1208 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1209 // The sort-role has been changed which might result
1210 // in modified group headers
1211 updateVisibleGroupHeaders();
1212 doLayout(NoAnimation
);
1217 void KItemListView::slotGroupedSortingChanged(bool current
)
1219 m_grouped
= current
;
1220 m_layouter
->markAsDirty();
1223 updateGroupHeaderHeight();
1225 // Clear all visible headers
1226 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1227 while (it
.hasNext()) {
1229 recycleGroupHeaderForWidget(it
.key());
1231 Q_ASSERT(m_visibleGroups
.isEmpty());
1234 if (useAlternateBackgrounds()) {
1235 // Changing the group mode requires to update the alternate backgrounds
1236 // as with the enabled group mode the altering is done on base of the first
1238 updateAlternateBackgrounds();
1240 updateSiblingsInformation();
1241 doLayout(NoAnimation
);
1244 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1249 updateVisibleGroupHeaders();
1250 doLayout(NoAnimation
);
1254 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1259 updateVisibleGroupHeaders();
1260 doLayout(NoAnimation
);
1264 void KItemListView::slotCurrentChanged(int current
, int previous
)
1268 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1269 if (previousWidget
) {
1270 previousWidget
->setCurrent(false);
1273 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1274 if (currentWidget
) {
1275 currentWidget
->setCurrent(true);
1277 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1280 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1284 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1285 while (it
.hasNext()) {
1287 const int index
= it
.key();
1288 KItemListWidget
* widget
= it
.value();
1289 widget
->setSelected(current
.contains(index
));
1293 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1294 KItemListViewAnimation::AnimationType type
)
1296 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1297 Q_ASSERT(itemListWidget
);
1300 case KItemListViewAnimation::DeleteAnimation
: {
1301 // As we recycle the widget in this case it is important to assure that no
1302 // other animation has been started. This is a convention in KItemListView and
1303 // not a requirement defined by KItemListViewAnimation.
1304 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1306 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1307 // by m_visibleWidgets and must be deleted manually after the animation has
1309 recycleGroupHeaderForWidget(itemListWidget
);
1310 widgetCreator()->recycle(itemListWidget
);
1314 case KItemListViewAnimation::CreateAnimation
:
1315 case KItemListViewAnimation::MovingAnimation
:
1316 case KItemListViewAnimation::ResizeAnimation
: {
1317 const int index
= itemListWidget
->index();
1318 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1319 (index
> m_layouter
->lastVisibleIndex());
1320 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1321 recycleWidget(itemListWidget
);
1330 void KItemListView::slotLayoutTimerFinished()
1332 m_layouter
->setSize(geometry().size());
1333 doLayout(Animation
);
1336 void KItemListView::slotRubberBandPosChanged()
1341 void KItemListView::slotRubberBandActivationChanged(bool active
)
1344 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1345 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1346 m_skipAutoScrollForRubberBand
= true;
1348 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1349 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1350 m_skipAutoScrollForRubberBand
= false;
1356 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1358 qreal previousWidth
)
1361 Q_UNUSED(currentWidth
);
1362 Q_UNUSED(previousWidth
);
1364 m_headerWidget
->setAutomaticColumnResizing(false);
1365 applyColumnWidthsFromHeader();
1366 doLayout(NoAnimation
);
1369 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1373 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1375 const QList
<QByteArray
> previous
= m_visibleRoles
;
1377 QList
<QByteArray
> current
= m_visibleRoles
;
1378 current
.removeAt(previousIndex
);
1379 current
.insert(currentIndex
, role
);
1381 setVisibleRoles(current
);
1383 emit
visibleRolesChanged(current
, previous
);
1386 void KItemListView::triggerAutoScrolling()
1388 if (!m_autoScrollTimer
) {
1393 int visibleSize
= 0;
1394 if (scrollOrientation() == Qt::Vertical
) {
1395 pos
= m_mousePos
.y();
1396 visibleSize
= size().height();
1398 pos
= m_mousePos
.x();
1399 visibleSize
= size().width();
1402 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1403 m_autoScrollIncrement
= 0;
1406 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1407 if (m_autoScrollIncrement
== 0) {
1408 // The mouse position is not above an autoscroll margin (the autoscroll timer
1409 // will be restarted in mouseMoveEvent())
1410 m_autoScrollTimer
->stop();
1414 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1415 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1416 // if the direction of the rubberband is similar to the autoscroll direction. This
1417 // prevents that starting to create a rubberband within the autoscroll margins starts
1418 // an autoscrolling.
1420 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1421 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1422 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1423 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1424 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1425 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1426 // been moved up although the autoscroll direction might be down)
1427 m_autoScrollTimer
->stop();
1432 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1433 // the autoscrolling may not get skipped anymore until a new rubberband is created
1434 m_skipAutoScrollForRubberBand
= false;
1436 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1437 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1438 setScrollOffset(newScrollOffset
);
1440 // Trigger the autoscroll timer which will periodically call
1441 // triggerAutoScrolling()
1442 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1445 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1447 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1449 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1450 Q_ASSERT(groupHeader
);
1451 updateGroupHeaderLayout(widget
);
1454 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1456 emit
roleEditingCanceled(index
, role
, value
);
1457 m_editingRole
= false;
1460 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1462 emit
roleEditingFinished(index
, role
, value
);
1463 m_editingRole
= false;
1466 void KItemListView::setController(KItemListController
* controller
)
1468 if (m_controller
!= controller
) {
1469 KItemListController
* previous
= m_controller
;
1471 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1472 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1473 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1476 m_controller
= controller
;
1479 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1480 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1481 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1484 onControllerChanged(controller
, previous
);
1488 void KItemListView::setModel(KItemModelBase
* model
)
1490 if (m_model
== model
) {
1494 KItemModelBase
* previous
= m_model
;
1497 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1498 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1499 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1500 this, SLOT(slotItemsInserted(KItemRangeList
)));
1501 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1502 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1503 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1504 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1505 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1506 this, SLOT(slotGroupedSortingChanged(bool)));
1507 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1508 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1509 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1510 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1513 m_sizeHintResolver
->clearCache();
1516 m_layouter
->setModel(model
);
1517 m_grouped
= model
->groupedSorting();
1520 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1521 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1522 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1523 this, SLOT(slotItemsInserted(KItemRangeList
)));
1524 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1525 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1526 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1527 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1528 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1529 this, SLOT(slotGroupedSortingChanged(bool)));
1530 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1531 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1532 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1533 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1535 const int itemCount
= m_model
->count();
1536 if (itemCount
> 0) {
1537 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1538 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1542 onModelChanged(model
, previous
);
1545 KItemListRubberBand
* KItemListView::rubberBand() const
1547 return m_rubberBand
;
1550 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1552 if (m_layoutTimer
->isActive()) {
1553 m_layoutTimer
->stop();
1556 if (m_activeTransactions
> 0) {
1557 if (hint
== NoAnimation
) {
1558 // As soon as at least one property change should be done without animation,
1559 // the whole transaction will be marked as not animated.
1560 m_endTransactionAnimationHint
= NoAnimation
;
1565 if (!m_model
|| m_model
->count() < 0) {
1569 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1570 if (firstVisibleIndex
< 0) {
1571 emitOffsetChanges();
1575 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1576 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1577 // is still shown if the maximum offset got decreased.
1578 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1579 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1580 if (scrollOffset() > maxOffsetToShowFullRange
) {
1581 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1582 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1585 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1587 int firstSibblingIndex
= -1;
1588 int lastSibblingIndex
= -1;
1589 const bool supportsExpanding
= supportsItemExpanding();
1591 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1593 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1594 // instances from invisible items are reused. If no reusable items are
1595 // found then new KItemListWidget instances get created.
1596 const bool animate
= (hint
== Animation
);
1597 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1598 bool applyNewPos
= true;
1599 bool wasHidden
= false;
1601 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1602 const QPointF newPos
= itemBounds
.topLeft();
1603 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1606 if (!reusableItems
.isEmpty()) {
1607 // Reuse a KItemListWidget instance from an invisible item
1608 const int oldIndex
= reusableItems
.takeLast();
1609 widget
= m_visibleItems
.value(oldIndex
);
1610 setWidgetIndex(widget
, i
);
1611 updateWidgetProperties(widget
, i
);
1612 initializeItemListWidget(widget
);
1614 // No reusable KItemListWidget instance is available, create a new one
1615 widget
= createWidget(i
);
1617 widget
->resize(itemBounds
.size());
1619 if (animate
&& changedCount
< 0) {
1620 // Items have been deleted, move the created item to the
1621 // imaginary old position. They will get animated to the new position
1623 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1624 if (itemRect
.isEmpty()) {
1625 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1626 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1627 widget
->setPos(invisibleOldPos
);
1629 widget
->setPos(itemRect
.topLeft());
1631 applyNewPos
= false;
1634 if (supportsExpanding
&& changedCount
== 0) {
1635 if (firstSibblingIndex
< 0) {
1636 firstSibblingIndex
= i
;
1638 lastSibblingIndex
= i
;
1643 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1644 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1645 applyNewPos
= false;
1648 const bool itemsRemoved
= (changedCount
< 0);
1649 const bool itemsInserted
= (changedCount
> 0);
1650 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1651 // The item is located after the removed items. Animate the moving of the position.
1652 applyNewPos
= !moveWidget(widget
, newPos
);
1653 } else if (itemsInserted
&& i
>= changedIndex
) {
1654 // The item is located after the first inserted item
1655 if (i
<= changedIndex
+ changedCount
- 1) {
1656 // The item is an inserted item. Animate the appearing of the item.
1657 // For performance reasons no animation is done when changedCount is equal
1658 // to all available items.
1659 if (changedCount
< m_model
->count()) {
1660 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1662 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1663 // The item was already there before, so animate the moving of the position.
1664 // No moving animation is done if the item is animated by a create animation: This
1665 // prevents a "move animation mess" when inserting several ranges in parallel.
1666 applyNewPos
= !moveWidget(widget
, newPos
);
1668 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1669 // The size of the view might have been changed. Animate the moving of the position.
1670 applyNewPos
= !moveWidget(widget
, newPos
);
1673 m_animation
->stop(widget
);
1677 widget
->setPos(newPos
);
1680 Q_ASSERT(widget
->index() == i
);
1681 widget
->setVisible(true);
1683 if (widget
->size() != itemBounds
.size()) {
1684 // Resize the widget for the item to the changed size.
1686 // If a dynamic item size is used then no animation is done in the direction
1687 // of the dynamic size.
1688 if (m_itemSize
.width() <= 0) {
1689 // The width is dynamic, apply the new width without animation.
1690 widget
->resize(itemBounds
.width(), widget
->size().height());
1691 } else if (m_itemSize
.height() <= 0) {
1692 // The height is dynamic, apply the new height without animation.
1693 widget
->resize(widget
->size().width(), itemBounds
.height());
1695 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1697 widget
->resize(itemBounds
.size());
1701 // Updating the cell-information must be done as last step: The decision whether the
1702 // moving-animation should be started at all is based on the previous cell-information.
1703 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1704 m_visibleCells
.insert(i
, cell
);
1707 // Delete invisible KItemListWidget instances that have not been reused
1708 foreach (int index
, reusableItems
) {
1709 recycleWidget(m_visibleItems
.value(index
));
1712 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1713 Q_ASSERT(lastSibblingIndex
>= 0);
1714 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1718 // Update the layout of all visible group headers
1719 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1720 while (it
.hasNext()) {
1722 updateGroupHeaderLayout(it
.key());
1726 emitOffsetChanges();
1729 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1730 int lastVisibleIndex
,
1731 LayoutAnimationHint hint
)
1733 // Determine all items that are completely invisible and might be
1734 // reused for items that just got (at least partly) visible. If the
1735 // animation hint is set to 'Animation' items that do e.g. an animated
1736 // moving of their position are not marked as invisible: This assures
1737 // that a scrolling inside the view can be done without breaking an animation.
1741 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1742 while (it
.hasNext()) {
1745 KItemListWidget
* widget
= it
.value();
1746 const int index
= widget
->index();
1747 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1750 if (m_animation
->isStarted(widget
)) {
1751 if (hint
== NoAnimation
) {
1752 // Stopping the animation will call KItemListView::slotAnimationFinished()
1753 // and the widget will be recycled if necessary there.
1754 m_animation
->stop(widget
);
1757 widget
->setVisible(false);
1758 items
.append(index
);
1761 recycleGroupHeaderForWidget(widget
);
1770 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1772 if (widget
->pos() == newPos
) {
1776 bool startMovingAnim
= false;
1778 if (m_itemSize
.isEmpty()) {
1779 // The items are not aligned in a grid but either as columns or rows.
1780 startMovingAnim
= true;
1782 // When having a grid the moving-animation should only be started, if it is done within
1783 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1784 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1785 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1786 const int index
= widget
->index();
1787 const Cell cell
= m_visibleCells
.value(index
);
1788 if (cell
.column
>= 0 && cell
.row
>= 0) {
1789 if (scrollOrientation() == Qt::Vertical
) {
1790 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1792 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1797 if (startMovingAnim
) {
1798 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1802 m_animation
->stop(widget
);
1803 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1807 void KItemListView::emitOffsetChanges()
1809 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1810 if (m_oldScrollOffset
!= newScrollOffset
) {
1811 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1812 m_oldScrollOffset
= newScrollOffset
;
1815 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1816 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1817 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1818 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1821 const qreal newItemOffset
= m_layouter
->itemOffset();
1822 if (m_oldItemOffset
!= newItemOffset
) {
1823 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1824 m_oldItemOffset
= newItemOffset
;
1827 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1828 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1829 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1830 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1834 KItemListWidget
* KItemListView::createWidget(int index
)
1836 KItemListWidget
* widget
= widgetCreator()->create(this);
1837 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1839 m_visibleItems
.insert(index
, widget
);
1840 m_visibleCells
.insert(index
, Cell());
1841 updateWidgetProperties(widget
, index
);
1842 initializeItemListWidget(widget
);
1846 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1849 recycleGroupHeaderForWidget(widget
);
1852 const int index
= widget
->index();
1853 m_visibleItems
.remove(index
);
1854 m_visibleCells
.remove(index
);
1856 widgetCreator()->recycle(widget
);
1859 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1861 const int oldIndex
= widget
->index();
1862 m_visibleItems
.remove(oldIndex
);
1863 m_visibleCells
.remove(oldIndex
);
1865 m_visibleItems
.insert(index
, widget
);
1866 m_visibleCells
.insert(index
, Cell());
1868 widget
->setIndex(index
);
1871 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1873 const int oldIndex
= widget
->index();
1874 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1876 setWidgetIndex(widget
, index
);
1878 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1879 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1880 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1881 (!vertical
&& oldCell
.column
== newCell
.column
);
1883 m_visibleCells
.insert(index
, newCell
);
1887 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1890 case LayouterSize
: m_layouter
->setSize(size
); break;
1891 case ItemSize
: m_layouter
->setItemSize(size
); break;
1896 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1898 widget
->setVisibleRoles(m_visibleRoles
);
1899 updateWidgetColumnWidths(widget
);
1900 widget
->setStyleOption(m_styleOption
);
1902 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1903 widget
->setCurrent(index
== selectionManager
->currentItem());
1904 widget
->setSelected(selectionManager
->isSelected(index
));
1905 widget
->setHovered(false);
1906 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1907 widget
->setIndex(index
);
1908 widget
->setData(m_model
->data(index
));
1909 widget
->setSiblingsInformation(QBitArray());
1910 updateAlternateBackgroundForWidget(widget
);
1913 updateGroupHeaderForWidget(widget
);
1917 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1919 Q_ASSERT(m_grouped
);
1921 const int index
= widget
->index();
1922 if (!m_layouter
->isFirstGroupItem(index
)) {
1923 // The widget does not represent the first item of a group
1924 // and hence requires no header
1925 recycleGroupHeaderForWidget(widget
);
1929 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1930 if (groups
.isEmpty() || !groupHeaderCreator()) {
1934 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1936 groupHeader
= groupHeaderCreator()->create(this);
1937 groupHeader
->setParentItem(widget
);
1938 m_visibleGroups
.insert(widget
, groupHeader
);
1939 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1941 Q_ASSERT(groupHeader
->parentItem() == widget
);
1943 const int groupIndex
= groupIndexForItem(index
);
1944 Q_ASSERT(groupIndex
>= 0);
1945 groupHeader
->setData(groups
.at(groupIndex
).second
);
1946 groupHeader
->setRole(model()->sortRole());
1947 groupHeader
->setStyleOption(m_styleOption
);
1948 groupHeader
->setScrollOrientation(scrollOrientation());
1949 groupHeader
->setItemIndex(index
);
1951 groupHeader
->show();
1954 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1956 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1957 Q_ASSERT(groupHeader
);
1959 const int index
= widget
->index();
1960 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1961 const QRectF itemRect
= m_layouter
->itemRect(index
);
1963 // The group-header is a child of the itemlist widget. Translate the
1964 // group header position to the relative position.
1965 if (scrollOrientation() == Qt::Vertical
) {
1966 // In the vertical scroll orientation the group header should always span
1967 // the whole width no matter which temporary position the parent widget
1968 // has. In this case the x-position and width will be adjusted manually.
1969 const qreal x
= -widget
->x() - itemOffset();
1970 const qreal width
= maximumItemOffset();
1971 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1972 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1974 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1975 groupHeader
->resize(groupHeaderRect
.size());
1979 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1981 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1983 header
->setParentItem(0);
1984 groupHeaderCreator()->recycle(header
);
1985 m_visibleGroups
.remove(widget
);
1986 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1990 void KItemListView::updateVisibleGroupHeaders()
1992 Q_ASSERT(m_grouped
);
1993 m_layouter
->markAsDirty();
1995 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1996 while (it
.hasNext()) {
1998 updateGroupHeaderForWidget(it
.value());
2002 int KItemListView::groupIndexForItem(int index
) const
2004 Q_ASSERT(m_grouped
);
2006 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2007 if (groups
.isEmpty()) {
2012 int max
= groups
.count() - 1;
2015 mid
= (min
+ max
) / 2;
2016 if (index
> groups
[mid
].first
) {
2021 } while (groups
[mid
].first
!= index
&& min
<= max
);
2024 while (groups
[mid
].first
> index
&& mid
> 0) {
2032 void KItemListView::updateAlternateBackgrounds()
2034 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2035 while (it
.hasNext()) {
2037 updateAlternateBackgroundForWidget(it
.value());
2041 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2043 bool enabled
= useAlternateBackgrounds();
2045 const int index
= widget
->index();
2046 enabled
= (index
& 0x1) > 0;
2048 const int groupIndex
= groupIndexForItem(index
);
2049 if (groupIndex
>= 0) {
2050 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2051 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2052 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2053 enabled
= (relativeIndex
& 0x1) > 0;
2057 widget
->setAlternateBackground(enabled
);
2060 bool KItemListView::useAlternateBackgrounds() const
2062 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2065 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2067 QElapsedTimer timer
;
2070 QHash
<QByteArray
, qreal
> widths
;
2072 // Calculate the minimum width for each column that is required
2073 // to show the headline unclipped.
2074 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2075 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2076 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2077 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2078 const QString headerText
= m_model
->roleDescription(visibleRole
);
2079 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2080 widths
.insert(visibleRole
, headerWidth
);
2083 // Calculate the preferred column withs for each item and ignore values
2084 // smaller than the width for showing the headline unclipped.
2085 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2086 int calculatedItemCount
= 0;
2087 bool maxTimeExceeded
= false;
2088 foreach (const KItemRange
& itemRange
, itemRanges
) {
2089 const int startIndex
= itemRange
.index
;
2090 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2092 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2093 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2094 qreal maxWidth
= widths
.value(visibleRole
, 0);
2095 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2096 maxWidth
= qMax(width
, maxWidth
);
2097 widths
.insert(visibleRole
, maxWidth
);
2100 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2101 // When having several thousands of items calculating the sizes can get
2102 // very expensive. We accept a possibly too small role-size in favour
2103 // of having no blocking user interface.
2104 maxTimeExceeded
= true;
2107 ++calculatedItemCount
;
2109 if (maxTimeExceeded
) {
2117 void KItemListView::applyColumnWidthsFromHeader()
2119 // Apply the new size to the layouter
2120 const qreal requiredWidth
= columnWidthsSum();
2121 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2122 m_itemSize
.height());
2123 m_layouter
->setItemSize(dynamicItemSize
);
2125 // Update the role sizes for all visible widgets
2126 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2127 while (it
.hasNext()) {
2129 updateWidgetColumnWidths(it
.value());
2133 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2135 foreach (const QByteArray
& role
, m_visibleRoles
) {
2136 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2140 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2142 Q_ASSERT(m_itemSize
.isEmpty());
2143 const int itemCount
= m_model
->count();
2144 int rangesItemCount
= 0;
2145 foreach (const KItemRange
& range
, itemRanges
) {
2146 rangesItemCount
+= range
.count
;
2149 if (itemCount
== rangesItemCount
) {
2150 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2151 foreach (const QByteArray
& role
, m_visibleRoles
) {
2152 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2155 // Only a sub range of the roles need to be determined.
2156 // The chances are good that the widths of the sub ranges
2157 // already fit into the available widths and hence no
2158 // expensive update might be required.
2159 bool changed
= false;
2161 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2162 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2163 while (it
.hasNext()) {
2165 const QByteArray
& role
= it
.key();
2166 const qreal updatedWidth
= it
.value();
2167 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2168 if (updatedWidth
> currentWidth
) {
2169 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2175 // All the updated sizes are smaller than the current sizes and no change
2176 // of the stretched roles-widths is required
2181 if (m_headerWidget
->automaticColumnResizing()) {
2182 applyAutomaticColumnWidths();
2186 void KItemListView::updatePreferredColumnWidths()
2189 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2193 void KItemListView::applyAutomaticColumnWidths()
2195 Q_ASSERT(m_itemSize
.isEmpty());
2196 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2197 if (m_visibleRoles
.isEmpty()) {
2201 // Calculate the maximum size of an item by considering the
2202 // visible role sizes and apply them to the layouter. If the
2203 // size does not use the available view-size the size of the
2204 // first role will get stretched.
2206 foreach (const QByteArray
& role
, m_visibleRoles
) {
2207 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2208 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2211 const QByteArray firstRole
= m_visibleRoles
.first();
2212 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2213 QSizeF dynamicItemSize
= m_itemSize
;
2215 qreal requiredWidth
= columnWidthsSum();
2216 const qreal availableWidth
= size().width();
2217 if (requiredWidth
< availableWidth
) {
2218 // Stretch the first column to use the whole remaining width
2219 firstColumnWidth
+= availableWidth
- requiredWidth
;
2220 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2221 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2222 // Shrink the first column to be able to show as much other
2223 // columns as possible
2224 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2226 // TODO: A proper calculation of the minimum width depends on the implementation
2227 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2229 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2230 if (shrinkedFirstColumnWidth
< minWidth
) {
2231 shrinkedFirstColumnWidth
= minWidth
;
2234 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2235 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2238 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2240 m_layouter
->setItemSize(dynamicItemSize
);
2242 // Update the role sizes for all visible widgets
2243 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2244 while (it
.hasNext()) {
2246 updateWidgetColumnWidths(it
.value());
2250 qreal
KItemListView::columnWidthsSum() const
2252 qreal widthsSum
= 0;
2253 foreach (const QByteArray
& role
, m_visibleRoles
) {
2254 widthsSum
+= m_headerWidget
->columnWidth(role
);
2259 QRectF
KItemListView::headerBoundaries() const
2261 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2264 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2265 const QSizeF
& newItemSize
,
2266 const QSizeF
& newItemMargin
) const
2268 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2272 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2273 const qreal itemWidth
= m_layouter
->itemSize().width();
2274 if (itemWidth
> 0) {
2275 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2276 newItemSize
.width(),
2277 newItemMargin
.width());
2278 if (m_model
->count() > newColumnCount
) {
2279 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2281 m_layouter
->itemMargin().width());
2282 return oldColumnCount
!= newColumnCount
;
2286 const qreal itemHeight
= m_layouter
->itemSize().height();
2287 if (itemHeight
> 0) {
2288 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2289 newItemSize
.height(),
2290 newItemMargin
.height());
2291 if (m_model
->count() > newRowCount
) {
2292 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2294 m_layouter
->itemMargin().height());
2295 return oldRowCount
!= newRowCount
;
2303 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2305 if (m_itemSize
.isEmpty()) {
2306 // We have only columns or only rows, but no grid: An animation is usually
2307 // welcome when inserting or removing items.
2308 return !supportsItemExpanding();
2311 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2315 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2316 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2317 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2318 // Only animate if up to 2/3 of a row or column are inserted or removed
2319 return changedItemCount
<= maximum
* 2 / 3;
2323 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2325 const QSizeF oldSize
= m_layouter
->size();
2327 m_layouter
->setSize(size
);
2328 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2329 m_layouter
->setSize(oldSize
);
2331 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2332 : maxOffset
> size
.width();
2335 int KItemListView::showDropIndicator(const QPointF
& pos
)
2337 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2338 while (it
.hasNext()) {
2340 const KItemListWidget
* widget
= it
.value();
2342 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2343 const QRectF rect
= itemRect(widget
->index());
2344 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2345 if (m_model
->supportsDropping(widget
->index())) {
2346 const int gap
= qMax(4, m_styleOption
.padding
);
2347 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2352 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2353 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2355 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2356 if (m_dropIndicator
!= draggingInsertIndicator
) {
2357 m_dropIndicator
= draggingInsertIndicator
;
2361 int index
= widget
->index();
2369 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2370 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2373 void KItemListView::hideDropIndicator()
2375 if (!m_dropIndicator
.isNull()) {
2376 m_dropIndicator
= QRectF();
2381 void KItemListView::updateGroupHeaderHeight()
2383 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2384 qreal groupHeaderMargin
= 0;
2386 if (scrollOrientation() == Qt::Horizontal
) {
2387 // The vertical margin above and below the header should be
2388 // equal to the horizontal margin, not the vertical margin
2389 // from m_styleOption.
2390 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2391 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2392 } else if (m_itemSize
.isEmpty()){
2393 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2394 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2396 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2397 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2399 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2400 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2402 updateVisibleGroupHeaders();
2405 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2407 if (!supportsItemExpanding() || !m_model
) {
2411 if (firstIndex
< 0 || lastIndex
< 0) {
2412 firstIndex
= m_layouter
->firstVisibleIndex();
2413 lastIndex
= m_layouter
->lastVisibleIndex();
2415 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2416 lastIndex
>= m_layouter
->firstVisibleIndex());
2417 if (!isRangeVisible
) {
2422 int previousParents
= 0;
2423 QBitArray previousSiblings
;
2425 // The rootIndex describes the first index where the siblings get
2426 // calculated from. For the calculation the upper most parent item
2427 // is required. For performance reasons it is checked first whether
2428 // the visible items before or after the current range already
2429 // contain a siblings information which can be used as base.
2430 int rootIndex
= firstIndex
;
2432 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2434 // There is no visible widget before the range, check whether there
2435 // is one after the range:
2436 widget
= m_visibleItems
.value(lastIndex
+ 1);
2438 // The sibling information of the widget may only be used if
2439 // all items of the range have the same number of parents.
2440 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2441 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2442 if (m_model
->expandedParentsCount(i
) != parents
) {
2451 // Performance optimization: Use the sibling information of the visible
2452 // widget beside the given range.
2453 previousSiblings
= widget
->siblingsInformation();
2454 if (previousSiblings
.isEmpty()) {
2457 previousParents
= previousSiblings
.count() - 1;
2458 previousSiblings
.truncate(previousParents
);
2460 // Potentially slow path: Go back to the upper most parent of firstIndex
2461 // to be able to calculate the initial value for the siblings.
2462 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2467 Q_ASSERT(previousParents
>= 0);
2468 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2469 // Update the parent-siblings in case if the current item represents
2470 // a child or an upper parent.
2471 const int currentParents
= m_model
->expandedParentsCount(i
);
2472 Q_ASSERT(currentParents
>= 0);
2473 if (previousParents
< currentParents
) {
2474 previousParents
= currentParents
;
2475 previousSiblings
.resize(currentParents
);
2476 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2477 } else if (previousParents
> currentParents
) {
2478 previousParents
= currentParents
;
2479 previousSiblings
.truncate(currentParents
);
2482 if (i
>= firstIndex
) {
2483 // The index represents a visible item. Apply the parent-siblings
2484 // and update the sibling of the current item.
2485 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2490 QBitArray siblings
= previousSiblings
;
2491 siblings
.resize(siblings
.count() + 1);
2492 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2494 widget
->setSiblingsInformation(siblings
);
2499 bool KItemListView::hasSiblingSuccessor(int index
) const
2501 bool hasSuccessor
= false;
2502 const int parentsCount
= m_model
->expandedParentsCount(index
);
2503 int successorIndex
= index
+ 1;
2505 // Search the next sibling
2506 const int itemCount
= m_model
->count();
2507 while (successorIndex
< itemCount
) {
2508 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2509 if (currentParentsCount
== parentsCount
) {
2510 hasSuccessor
= true;
2512 } else if (currentParentsCount
< parentsCount
) {
2518 if (m_grouped
&& hasSuccessor
) {
2519 // If the sibling is part of another group, don't mark it as
2520 // successor as the group header is between the sibling connections.
2521 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2522 if (m_layouter
->isFirstGroupItem(i
)) {
2523 hasSuccessor
= false;
2529 return hasSuccessor
;
2532 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2536 const int minSpeed
= 4;
2537 const int maxSpeed
= 128;
2538 const int speedLimiter
= 96;
2539 const int autoScrollBorder
= 64;
2541 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2542 // This assures that the autoscrolling speed grows gradually.
2543 const int incLimiter
= 1;
2545 if (pos
< autoScrollBorder
) {
2546 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2547 inc
= qMax(inc
, -maxSpeed
);
2548 inc
= qMax(inc
, oldInc
- incLimiter
);
2549 } else if (pos
> range
- autoScrollBorder
) {
2550 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2551 inc
= qMin(inc
, maxSpeed
);
2552 inc
= qMin(inc
, oldInc
+ incLimiter
);
2558 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2560 const qreal availableSize
= size
- itemMargin
;
2561 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2567 KItemListCreatorBase::~KItemListCreatorBase()
2569 qDeleteAll(m_recycleableWidgets
);
2570 qDeleteAll(m_createdWidgets
);
2573 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2575 m_createdWidgets
.insert(widget
);
2578 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2580 Q_ASSERT(m_createdWidgets
.contains(widget
));
2581 m_createdWidgets
.remove(widget
);
2583 if (m_recycleableWidgets
.count() < 100) {
2584 m_recycleableWidgets
.append(widget
);
2585 widget
->setVisible(false);
2591 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2593 if (m_recycleableWidgets
.isEmpty()) {
2597 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2598 m_createdWidgets
.insert(widget
);
2602 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2606 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2608 widget
->setParentItem(0);
2609 widget
->setOpacity(1.0);
2610 pushRecycleableWidget(widget
);
2613 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2617 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2619 header
->setOpacity(1.0);
2620 pushRecycleableWidget(header
);
2623 #include "kitemlistview.moc"