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
* accessibleInterfaceFactory(const QString
&key
, QObject
*object
)
61 if (KItemListContainer
*view
= qobject_cast
<KItemListContainer
*>(object
)) {
62 return new KItemListContainerAccessible(view
);
64 if (KItemListView
*view
= qobject_cast
<KItemListView
*>(object
)) {
65 return new KItemListViewAccessible(view
);
71 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
72 QGraphicsWidget(parent
),
73 m_enabledSelectionToggles(false),
75 m_supportsItemExpanding(false),
77 m_activeTransactions(0),
78 m_endTransactionAnimationHint(Animation
),
84 m_groupHeaderCreator(0),
89 m_sizeHintResolver(0),
94 m_oldMaximumScrollOffset(0),
96 m_oldMaximumItemOffset(0),
97 m_skipAutoScrollForRubberBand(false),
100 m_autoScrollIncrement(0),
101 m_autoScrollTimer(0),
106 setAcceptHoverEvents(true);
108 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
110 m_layouter
= new KItemListViewLayouter(this);
111 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
113 m_animation
= new KItemListViewAnimation(this);
114 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
115 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
117 m_layoutTimer
= new QTimer(this);
118 m_layoutTimer
->setInterval(300);
119 m_layoutTimer
->setSingleShot(true);
120 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
122 m_rubberBand
= new KItemListRubberBand(this);
123 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
125 m_headerWidget
= new KItemListHeaderWidget(this);
126 m_headerWidget
->setVisible(false);
128 m_header
= new KItemListHeader(this);
130 #ifndef QT_NO_ACCESSIBILITY
131 QAccessible::installFactory(accessibleInterfaceFactory
);
136 KItemListView::~KItemListView()
138 // The group headers are children of the widgets created by
139 // widgetCreator(). So it is mandatory to delete the group headers
141 delete m_groupHeaderCreator
;
142 m_groupHeaderCreator
= 0;
144 delete m_widgetCreator
;
147 delete m_sizeHintResolver
;
148 m_sizeHintResolver
= 0;
151 void KItemListView::setScrollOffset(qreal offset
)
157 const qreal previousOffset
= m_layouter
->scrollOffset();
158 if (offset
== previousOffset
) {
162 m_layouter
->setScrollOffset(offset
);
163 m_animation
->setScrollOffset(offset
);
165 // Don't check whether the m_layoutTimer is active: Changing the
166 // scroll offset must always trigger a synchronous layout, otherwise
167 // the smooth-scrolling might get jerky.
168 doLayout(NoAnimation
);
169 onScrollOffsetChanged(offset
, previousOffset
);
172 qreal
KItemListView::scrollOffset() const
174 return m_layouter
->scrollOffset();
177 qreal
KItemListView::maximumScrollOffset() const
179 return m_layouter
->maximumScrollOffset();
182 void KItemListView::setItemOffset(qreal offset
)
184 if (m_layouter
->itemOffset() == offset
) {
188 m_layouter
->setItemOffset(offset
);
189 if (m_headerWidget
->isVisible()) {
190 m_headerWidget
->setOffset(offset
);
193 // Don't check whether the m_layoutTimer is active: Changing the
194 // item offset must always trigger a synchronous layout, otherwise
195 // the smooth-scrolling might get jerky.
196 doLayout(NoAnimation
);
199 qreal
KItemListView::itemOffset() const
201 return m_layouter
->itemOffset();
204 qreal
KItemListView::maximumItemOffset() const
206 return m_layouter
->maximumItemOffset();
209 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
211 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
212 m_visibleRoles
= roles
;
213 onVisibleRolesChanged(roles
, previousRoles
);
215 m_sizeHintResolver
->clearCache();
216 m_layouter
->markAsDirty();
218 if (m_itemSize
.isEmpty()) {
219 m_headerWidget
->setColumns(roles
);
220 updatePreferredColumnWidths();
221 if (!m_headerWidget
->automaticColumnResizing()) {
222 // The column-width of new roles are still 0. Apply the preferred
223 // column-width as default with.
224 foreach (const QByteArray
& role
, m_visibleRoles
) {
225 if (m_headerWidget
->columnWidth(role
) == 0) {
226 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
227 m_headerWidget
->setColumnWidth(role
, width
);
231 applyColumnWidthsFromHeader();
235 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
236 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
237 (roles
.count() <= 1 && previousRoles
.count() > 1));
239 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
240 while (it
.hasNext()) {
242 KItemListWidget
* widget
= it
.value();
243 widget
->setVisibleRoles(roles
);
244 if (alternateBackgroundsChanged
) {
245 updateAlternateBackgroundForWidget(widget
);
249 doLayout(NoAnimation
);
252 QList
<QByteArray
> KItemListView::visibleRoles() const
254 return m_visibleRoles
;
257 void KItemListView::setAutoScroll(bool enabled
)
259 if (enabled
&& !m_autoScrollTimer
) {
260 m_autoScrollTimer
= new QTimer(this);
261 m_autoScrollTimer
->setSingleShot(true);
262 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
263 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
264 } else if (!enabled
&& m_autoScrollTimer
) {
265 delete m_autoScrollTimer
;
266 m_autoScrollTimer
= 0;
270 bool KItemListView::autoScroll() const
272 return m_autoScrollTimer
!= 0;
275 void KItemListView::setEnabledSelectionToggles(bool enabled
)
277 if (m_enabledSelectionToggles
!= enabled
) {
278 m_enabledSelectionToggles
= enabled
;
280 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
281 while (it
.hasNext()) {
283 it
.value()->setEnabledSelectionToggle(enabled
);
288 bool KItemListView::enabledSelectionToggles() const
290 return m_enabledSelectionToggles
;
293 KItemListController
* KItemListView::controller() const
298 KItemModelBase
* KItemListView::model() const
303 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
305 if (m_widgetCreator
) {
306 delete m_widgetCreator
;
308 m_widgetCreator
= widgetCreator
;
311 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
313 if (!m_widgetCreator
) {
314 m_widgetCreator
= defaultWidgetCreator();
316 return m_widgetCreator
;
319 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
321 if (m_groupHeaderCreator
) {
322 delete m_groupHeaderCreator
;
324 m_groupHeaderCreator
= groupHeaderCreator
;
327 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
329 if (!m_groupHeaderCreator
) {
330 m_groupHeaderCreator
= defaultGroupHeaderCreator();
332 return m_groupHeaderCreator
;
335 QSizeF
KItemListView::itemSize() const
340 const KItemListStyleOption
& KItemListView::styleOption() const
342 return m_styleOption
;
345 void KItemListView::setGeometry(const QRectF
& rect
)
347 QGraphicsWidget::setGeometry(rect
);
353 const QSizeF newSize
= rect
.size();
354 if (m_itemSize
.isEmpty()) {
355 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
356 if (m_headerWidget
->automaticColumnResizing()) {
357 applyAutomaticColumnWidths();
359 const qreal requiredWidth
= columnWidthsSum();
360 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
361 m_itemSize
.height());
362 m_layouter
->setItemSize(dynamicItemSize
);
365 // Triggering a synchronous layout is fine from a performance point of view,
366 // as with dynamic item sizes no moving animation must be done.
367 m_layouter
->setSize(newSize
);
368 doLayout(NoAnimation
);
370 const bool animate
= !changesItemGridLayout(newSize
,
371 m_layouter
->itemSize(),
372 m_layouter
->itemMargin());
373 m_layouter
->setSize(newSize
);
376 // Trigger an asynchronous relayout with m_layoutTimer to prevent
377 // performance bottlenecks. If the timer is exceeded, an animated layout
378 // will be triggered.
379 if (!m_layoutTimer
->isActive()) {
380 m_layoutTimer
->start();
383 m_layoutTimer
->stop();
384 doLayout(NoAnimation
);
389 int KItemListView::itemAt(const QPointF
& pos
) const
391 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
392 while (it
.hasNext()) {
395 const KItemListWidget
* widget
= it
.value();
396 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
397 if (widget
->contains(mappedPos
)) {
405 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
407 if (!m_enabledSelectionToggles
) {
411 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
413 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
414 if (!selectionToggleRect
.isEmpty()) {
415 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
416 return selectionToggleRect
.contains(mappedPos
);
422 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
424 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
426 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
427 if (!expansionToggleRect
.isEmpty()) {
428 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
429 return expansionToggleRect
.contains(mappedPos
);
435 int KItemListView::firstVisibleIndex() const
437 return m_layouter
->firstVisibleIndex();
440 int KItemListView::lastVisibleIndex() const
442 return m_layouter
->lastVisibleIndex();
445 QSizeF
KItemListView::itemSizeHint(int index
) const
447 return widgetCreator()->itemSizeHint(index
, this);
450 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
452 if (m_supportsItemExpanding
!= supportsExpanding
) {
453 m_supportsItemExpanding
= supportsExpanding
;
454 updateSiblingsInformation();
455 onSupportsItemExpandingChanged(supportsExpanding
);
459 bool KItemListView::supportsItemExpanding() const
461 return m_supportsItemExpanding
;
464 QRectF
KItemListView::itemRect(int index
) const
466 return m_layouter
->itemRect(index
);
469 QRectF
KItemListView::itemContextRect(int index
) const
473 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
475 contextRect
= widget
->iconRect() | widget
->textRect();
476 contextRect
.translate(itemRect(index
).topLeft());
482 void KItemListView::scrollToItem(int index
)
484 QRectF viewGeometry
= geometry();
485 if (m_headerWidget
->isVisible()) {
486 const qreal headerHeight
= m_headerWidget
->size().height();
487 viewGeometry
.adjust(0, headerHeight
, 0, 0);
489 const QRectF currentRect
= itemRect(index
);
491 if (!viewGeometry
.contains(currentRect
)) {
492 qreal newOffset
= scrollOffset();
493 if (scrollOrientation() == Qt::Vertical
) {
494 if (currentRect
.top() < viewGeometry
.top()) {
495 newOffset
+= currentRect
.top() - viewGeometry
.top();
496 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
497 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
500 if (currentRect
.left() < viewGeometry
.left()) {
501 newOffset
+= currentRect
.left() - viewGeometry
.left();
502 } else if (currentRect
.right() > viewGeometry
.right()) {
503 newOffset
+= currentRect
.right() - viewGeometry
.right();
507 if (newOffset
!= scrollOffset()) {
508 emit
scrollTo(newOffset
);
513 void KItemListView::beginTransaction()
515 ++m_activeTransactions
;
516 if (m_activeTransactions
== 1) {
517 onTransactionBegin();
521 void KItemListView::endTransaction()
523 --m_activeTransactions
;
524 if (m_activeTransactions
< 0) {
525 m_activeTransactions
= 0;
526 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
529 if (m_activeTransactions
== 0) {
531 doLayout(m_endTransactionAnimationHint
);
532 m_endTransactionAnimationHint
= Animation
;
536 bool KItemListView::isTransactionActive() const
538 return m_activeTransactions
> 0;
541 void KItemListView::setHeaderVisible(bool visible
)
543 if (visible
&& !m_headerWidget
->isVisible()) {
544 QStyleOptionHeader option
;
545 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
548 m_headerWidget
->setPos(0, 0);
549 m_headerWidget
->resize(size().width(), headerSize
.height());
550 m_headerWidget
->setModel(m_model
);
551 m_headerWidget
->setColumns(m_visibleRoles
);
552 m_headerWidget
->setZValue(1);
554 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
555 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
556 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
557 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
558 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
559 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
560 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
561 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
563 m_layouter
->setHeaderHeight(headerSize
.height());
564 m_headerWidget
->setVisible(true);
565 } else if (!visible
&& m_headerWidget
->isVisible()) {
566 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
567 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
568 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
569 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
570 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
571 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
572 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
573 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
575 m_layouter
->setHeaderHeight(0);
576 m_headerWidget
->setVisible(false);
580 bool KItemListView::isHeaderVisible() const
582 return m_headerWidget
->isVisible();
585 KItemListHeader
* KItemListView::header() const
590 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
594 if (indexes
.count() == 1) {
595 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
596 QGraphicsView
* graphicsView
= scene()->views()[0];
597 if (item
&& graphicsView
) {
598 pixmap
= item
->createDragPixmap(0, graphicsView
);
601 // TODO: Not implemented yet. Probably extend the interface
602 // from KItemListWidget::createDragPixmap() to return a pixmap
603 // that can be used for multiple indexes.
609 void KItemListView::editRole(int index
, const QByteArray
& role
)
611 KItemListWidget
* widget
= m_visibleItems
.value(index
);
612 if (!widget
|| m_editingRole
) {
616 m_editingRole
= true;
617 widget
->setEditedRole(role
);
619 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
620 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
621 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
622 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
625 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
627 QGraphicsWidget::paint(painter
, option
, widget
);
629 if (m_rubberBand
->isActive()) {
630 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
631 m_rubberBand
->endPosition()).normalized();
633 const QPointF topLeft
= rubberBandRect
.topLeft();
634 if (scrollOrientation() == Qt::Vertical
) {
635 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
637 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
640 QStyleOptionRubberBand opt
;
641 opt
.initFrom(widget
);
642 opt
.shape
= QRubberBand::Rectangle
;
644 opt
.rect
= rubberBandRect
.toRect();
645 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
648 if (!m_dropIndicator
.isEmpty()) {
649 const QRectF r
= m_dropIndicator
.toRect();
651 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
652 painter
->setPen(color
);
654 // TODO: The following implementation works only for a vertical scroll-orientation
655 // and assumes a height of the m_draggingInsertIndicator of 1.
656 Q_ASSERT(r
.height() == 1);
657 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
660 painter
->setPen(color
);
661 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
665 KItemListViewLayouter
* KItemListView::layouter() const
670 void KItemListView::setItemSize(const QSizeF
& size
)
672 const QSizeF previousSize
= m_itemSize
;
673 if (size
== previousSize
) {
677 // Skip animations when the number of rows or columns
678 // are changed in the grid layout. Although the animation
679 // engine can handle this usecase, it looks obtrusive.
680 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
682 m_layouter
->itemMargin());
684 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
685 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
686 (!m_itemSize
.isEmpty() && size
.isEmpty()));
690 if (alternateBackgroundsChanged
) {
691 // For an empty item size alternate backgrounds are drawn if more than
692 // one role is shown. Assure that the backgrounds for visible items are
693 // updated when changing the size in this context.
694 updateAlternateBackgrounds();
697 if (size
.isEmpty()) {
698 if (m_headerWidget
->automaticColumnResizing()) {
699 updatePreferredColumnWidths();
701 // Only apply the changed height and respect the header widths
703 const qreal currentWidth
= m_layouter
->itemSize().width();
704 const QSizeF
newSize(currentWidth
, size
.height());
705 m_layouter
->setItemSize(newSize
);
708 m_layouter
->setItemSize(size
);
711 m_sizeHintResolver
->clearCache();
712 doLayout(animate
? Animation
: NoAnimation
);
713 onItemSizeChanged(size
, previousSize
);
716 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
718 const KItemListStyleOption previousOption
= m_styleOption
;
719 m_styleOption
= option
;
722 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
723 if (margin
!= m_layouter
->itemMargin()) {
724 // Skip animations when the number of rows or columns
725 // are changed in the grid layout. Although the animation
726 // engine can handle this usecase, it looks obtrusive.
727 animate
= !changesItemGridLayout(m_layouter
->size(),
728 m_layouter
->itemSize(),
730 m_layouter
->setItemMargin(margin
);
734 updateGroupHeaderHeight();
737 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
738 // Animating a change of the maximum text size just results in expensive
739 // temporary eliding and clipping operations and does not look good visually.
743 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
744 while (it
.hasNext()) {
746 it
.value()->setStyleOption(option
);
749 m_sizeHintResolver
->clearCache();
750 m_layouter
->markAsDirty();
751 doLayout(animate
? Animation
: NoAnimation
);
753 if (m_itemSize
.isEmpty()) {
754 updatePreferredColumnWidths();
757 onStyleOptionChanged(option
, previousOption
);
760 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
762 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
763 if (orientation
== previousOrientation
) {
767 m_layouter
->setScrollOrientation(orientation
);
768 m_animation
->setScrollOrientation(orientation
);
769 m_sizeHintResolver
->clearCache();
772 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
773 while (it
.hasNext()) {
775 it
.value()->setScrollOrientation(orientation
);
777 updateGroupHeaderHeight();
781 doLayout(NoAnimation
);
783 onScrollOrientationChanged(orientation
, previousOrientation
);
784 emit
scrollOrientationChanged(orientation
, previousOrientation
);
787 Qt::Orientation
KItemListView::scrollOrientation() const
789 return m_layouter
->scrollOrientation();
792 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
797 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
802 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
807 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
809 Q_UNUSED(changedRoles
);
813 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
819 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
825 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
831 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
837 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
843 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
849 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
855 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
857 Q_UNUSED(supportsExpanding
);
860 void KItemListView::onTransactionBegin()
864 void KItemListView::onTransactionEnd()
868 bool KItemListView::event(QEvent
* event
)
870 // Forward all events to the controller and handle them there
871 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
875 return QGraphicsWidget::event(event
);
878 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
880 m_mousePos
= transform().map(event
->pos());
884 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
886 QGraphicsWidget::mouseMoveEvent(event
);
888 m_mousePos
= transform().map(event
->pos());
889 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
890 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
894 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
896 event
->setAccepted(true);
900 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
902 QGraphicsWidget::dragMoveEvent(event
);
904 m_mousePos
= transform().map(event
->pos());
905 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
906 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
910 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
912 QGraphicsWidget::dragLeaveEvent(event
);
913 setAutoScroll(false);
916 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
918 QGraphicsWidget::dropEvent(event
);
919 setAutoScroll(false);
922 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
924 return m_visibleItems
.values();
927 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
929 if (m_itemSize
.isEmpty()) {
930 updatePreferredColumnWidths(itemRanges
);
933 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
934 if (hasMultipleRanges
) {
938 m_layouter
->markAsDirty();
940 int previouslyInsertedCount
= 0;
941 foreach (const KItemRange
& range
, itemRanges
) {
942 // range.index is related to the model before anything has been inserted.
943 // As in each loop the current item-range gets inserted the index must
944 // be increased by the already previously inserted items.
945 const int index
= range
.index
+ previouslyInsertedCount
;
946 const int count
= range
.count
;
947 if (index
< 0 || count
<= 0) {
948 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
951 previouslyInsertedCount
+= count
;
953 m_sizeHintResolver
->itemsInserted(index
, count
);
955 // Determine which visible items must be moved
956 QList
<int> itemsToMove
;
957 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
958 while (it
.hasNext()) {
960 const int visibleItemIndex
= it
.key();
961 if (visibleItemIndex
>= index
) {
962 itemsToMove
.append(visibleItemIndex
);
966 // Update the indexes of all KItemListWidget instances that are located
967 // after the inserted items. It is important to adjust the indexes in the order
968 // from the highest index to the lowest index to prevent overlaps when setting the new index.
970 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
971 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
973 const int newIndex
= widget
->index() + count
;
974 if (hasMultipleRanges
) {
975 setWidgetIndex(widget
, newIndex
);
977 // Try to animate the moving of the item
978 moveWidgetToIndex(widget
, newIndex
);
982 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
983 // Check whether a scrollbar is required to show the inserted items. In this case
984 // the size of the layouter will be decreased before calling doLayout(): This prevents
985 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
986 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
987 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
988 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
989 if (decreaseLayouterSize
) {
990 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
991 QSizeF layouterSize
= m_layouter
->size();
992 if (verticalScrollOrientation
) {
993 layouterSize
.rwidth() -= scrollBarExtent
;
995 layouterSize
.rheight() -= scrollBarExtent
;
997 m_layouter
->setSize(layouterSize
);
1001 if (!hasMultipleRanges
) {
1002 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1003 updateSiblingsInformation();
1008 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1011 if (hasMultipleRanges
) {
1013 // Important: Don't read any m_layouter-property inside the for-loop in case if
1014 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1015 // updated in each loop-cycle and has only a consistent state after the loop.
1016 Q_ASSERT(m_layouter
->isDirty());
1018 m_endTransactionAnimationHint
= NoAnimation
;
1021 updateSiblingsInformation();
1024 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1025 // In case if items of the same group have been inserted before an item that
1026 // currently represents the first item of the group, the group header of
1027 // this item must be removed.
1028 updateVisibleGroupHeaders();
1031 if (useAlternateBackgrounds()) {
1032 updateAlternateBackgrounds();
1036 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1038 if (m_itemSize
.isEmpty()) {
1039 // Don't pass the item-range: The preferred column-widths of
1040 // all items must be adjusted when removing items.
1041 updatePreferredColumnWidths();
1044 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1045 if (hasMultipleRanges
) {
1049 m_layouter
->markAsDirty();
1051 int removedItemsCount
= 0;
1052 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1053 removedItemsCount
+= itemRanges
[i
].count
;
1056 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1057 const KItemRange
& range
= itemRanges
[i
];
1058 const int index
= range
.index
;
1059 const int count
= range
.count
;
1060 if (index
< 0 || count
<= 0) {
1061 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1065 m_sizeHintResolver
->itemsRemoved(index
, count
);
1067 const int firstRemovedIndex
= index
;
1068 const int lastRemovedIndex
= index
+ count
- 1;
1069 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1070 removedItemsCount
-= count
;
1072 // Remove all KItemListWidget instances that got deleted
1073 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1074 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1079 m_animation
->stop(widget
);
1080 // Stopping the animation might lead to recycling the widget if
1081 // it is invisible (see slotAnimationFinished()).
1082 // Check again whether it is still visible:
1083 if (!m_visibleItems
.contains(i
)) {
1087 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1088 // Remove the widget without animation
1089 recycleWidget(widget
);
1091 // Animate the removing of the items. Special case: When removing an item there
1092 // is no valid model index available anymore. For the
1093 // remove-animation the item gets removed from m_visibleItems but the widget
1094 // will stay alive until the animation has been finished and will
1095 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1096 m_visibleItems
.remove(i
);
1097 widget
->setIndex(-1);
1098 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1102 // Update the indexes of all KItemListWidget instances that are located
1103 // after the deleted items
1104 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1105 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1107 const int newIndex
= i
- count
;
1108 if (hasMultipleRanges
) {
1109 setWidgetIndex(widget
, newIndex
);
1111 // Try to animate the moving of the item
1112 moveWidgetToIndex(widget
, newIndex
);
1117 if (!hasMultipleRanges
) {
1118 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1119 // assumes an updated geometry. If items are removed during an active transaction,
1120 // the transaction will be temporary deactivated so that doLayout() triggers a
1121 // geometry update if necessary.
1122 const int activeTransactions
= m_activeTransactions
;
1123 m_activeTransactions
= 0;
1124 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1125 m_activeTransactions
= activeTransactions
;
1126 updateSiblingsInformation();
1131 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1134 if (hasMultipleRanges
) {
1136 // Important: Don't read any m_layouter-property inside the for-loop in case if
1137 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1138 // updated in each loop-cycle and has only a consistent state after the loop.
1139 Q_ASSERT(m_layouter
->isDirty());
1141 m_endTransactionAnimationHint
= NoAnimation
;
1143 updateSiblingsInformation();
1146 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1147 // In case if the first item of a group has been removed, the group header
1148 // must be applied to the next visible item.
1149 updateVisibleGroupHeaders();
1152 if (useAlternateBackgrounds()) {
1153 updateAlternateBackgrounds();
1157 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1159 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1160 m_layouter
->markAsDirty();
1163 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1166 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1167 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1169 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1170 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1172 updateWidgetProperties(widget
, index
);
1173 initializeItemListWidget(widget
);
1177 doLayout(NoAnimation
);
1178 updateSiblingsInformation();
1181 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1182 const QSet
<QByteArray
>& roles
)
1184 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1185 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1186 updatePreferredColumnWidths(itemRanges
);
1189 foreach (const KItemRange
& itemRange
, itemRanges
) {
1190 const int index
= itemRange
.index
;
1191 const int count
= itemRange
.count
;
1193 if (updateSizeHints
) {
1194 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1195 m_layouter
->markAsDirty();
1197 if (!m_layoutTimer
->isActive()) {
1198 m_layoutTimer
->start();
1202 // Apply the changed roles to the visible item-widgets
1203 const int lastIndex
= index
+ count
- 1;
1204 for (int i
= index
; i
<= lastIndex
; ++i
) {
1205 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1207 widget
->setData(m_model
->data(i
), roles
);
1211 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1212 // The sort-role has been changed which might result
1213 // in modified group headers
1214 updateVisibleGroupHeaders();
1215 doLayout(NoAnimation
);
1220 void KItemListView::slotGroupedSortingChanged(bool current
)
1222 m_grouped
= current
;
1223 m_layouter
->markAsDirty();
1226 updateGroupHeaderHeight();
1228 // Clear all visible headers
1229 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1230 while (it
.hasNext()) {
1232 recycleGroupHeaderForWidget(it
.key());
1234 Q_ASSERT(m_visibleGroups
.isEmpty());
1237 if (useAlternateBackgrounds()) {
1238 // Changing the group mode requires to update the alternate backgrounds
1239 // as with the enabled group mode the altering is done on base of the first
1241 updateAlternateBackgrounds();
1243 updateSiblingsInformation();
1244 doLayout(NoAnimation
);
1247 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1252 updateVisibleGroupHeaders();
1253 doLayout(NoAnimation
);
1257 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1262 updateVisibleGroupHeaders();
1263 doLayout(NoAnimation
);
1267 void KItemListView::slotCurrentChanged(int current
, int previous
)
1271 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1272 if (previousWidget
) {
1273 previousWidget
->setCurrent(false);
1276 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1277 if (currentWidget
) {
1278 currentWidget
->setCurrent(true);
1280 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1283 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1288 while (it
.hasNext()) {
1290 const int index
= it
.key();
1291 KItemListWidget
* widget
= it
.value();
1292 widget
->setSelected(current
.contains(index
));
1296 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1297 KItemListViewAnimation::AnimationType type
)
1299 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1300 Q_ASSERT(itemListWidget
);
1303 case KItemListViewAnimation::DeleteAnimation
: {
1304 // As we recycle the widget in this case it is important to assure that no
1305 // other animation has been started. This is a convention in KItemListView and
1306 // not a requirement defined by KItemListViewAnimation.
1307 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1309 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1310 // by m_visibleWidgets and must be deleted manually after the animation has
1312 recycleGroupHeaderForWidget(itemListWidget
);
1313 widgetCreator()->recycle(itemListWidget
);
1317 case KItemListViewAnimation::CreateAnimation
:
1318 case KItemListViewAnimation::MovingAnimation
:
1319 case KItemListViewAnimation::ResizeAnimation
: {
1320 const int index
= itemListWidget
->index();
1321 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1322 (index
> m_layouter
->lastVisibleIndex());
1323 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1324 recycleWidget(itemListWidget
);
1333 void KItemListView::slotLayoutTimerFinished()
1335 m_layouter
->setSize(geometry().size());
1336 doLayout(Animation
);
1339 void KItemListView::slotRubberBandPosChanged()
1344 void KItemListView::slotRubberBandActivationChanged(bool active
)
1347 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1348 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1349 m_skipAutoScrollForRubberBand
= true;
1351 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1352 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1353 m_skipAutoScrollForRubberBand
= false;
1359 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1361 qreal previousWidth
)
1364 Q_UNUSED(currentWidth
);
1365 Q_UNUSED(previousWidth
);
1367 m_headerWidget
->setAutomaticColumnResizing(false);
1368 applyColumnWidthsFromHeader();
1369 doLayout(NoAnimation
);
1372 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1376 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1378 const QList
<QByteArray
> previous
= m_visibleRoles
;
1380 QList
<QByteArray
> current
= m_visibleRoles
;
1381 current
.removeAt(previousIndex
);
1382 current
.insert(currentIndex
, role
);
1384 setVisibleRoles(current
);
1386 emit
visibleRolesChanged(current
, previous
);
1389 void KItemListView::triggerAutoScrolling()
1391 if (!m_autoScrollTimer
) {
1396 int visibleSize
= 0;
1397 if (scrollOrientation() == Qt::Vertical
) {
1398 pos
= m_mousePos
.y();
1399 visibleSize
= size().height();
1401 pos
= m_mousePos
.x();
1402 visibleSize
= size().width();
1405 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1406 m_autoScrollIncrement
= 0;
1409 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1410 if (m_autoScrollIncrement
== 0) {
1411 // The mouse position is not above an autoscroll margin (the autoscroll timer
1412 // will be restarted in mouseMoveEvent())
1413 m_autoScrollTimer
->stop();
1417 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1418 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1419 // if the direction of the rubberband is similar to the autoscroll direction. This
1420 // prevents that starting to create a rubberband within the autoscroll margins starts
1421 // an autoscrolling.
1423 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1424 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1425 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1426 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1427 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1428 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1429 // been moved up although the autoscroll direction might be down)
1430 m_autoScrollTimer
->stop();
1435 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1436 // the autoscrolling may not get skipped anymore until a new rubberband is created
1437 m_skipAutoScrollForRubberBand
= false;
1439 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1440 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1441 setScrollOffset(newScrollOffset
);
1443 // Trigger the autoscroll timer which will periodically call
1444 // triggerAutoScrolling()
1445 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1448 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1450 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1452 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1453 Q_ASSERT(groupHeader
);
1454 updateGroupHeaderLayout(widget
);
1457 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1459 emit
roleEditingCanceled(index
, role
, value
);
1460 m_editingRole
= false;
1463 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1465 emit
roleEditingFinished(index
, role
, value
);
1466 m_editingRole
= false;
1469 void KItemListView::setController(KItemListController
* controller
)
1471 if (m_controller
!= controller
) {
1472 KItemListController
* previous
= m_controller
;
1474 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1475 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1476 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1479 m_controller
= controller
;
1482 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1483 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1484 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1487 onControllerChanged(controller
, previous
);
1491 void KItemListView::setModel(KItemModelBase
* model
)
1493 if (m_model
== model
) {
1497 KItemModelBase
* previous
= m_model
;
1500 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1501 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1502 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1503 this, SLOT(slotItemsInserted(KItemRangeList
)));
1504 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1505 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1506 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1507 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1508 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1509 this, SLOT(slotGroupedSortingChanged(bool)));
1510 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1511 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1512 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1513 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1516 m_sizeHintResolver
->clearCache();
1519 m_layouter
->setModel(model
);
1520 m_grouped
= model
->groupedSorting();
1523 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1524 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1525 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1526 this, SLOT(slotItemsInserted(KItemRangeList
)));
1527 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1528 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1529 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1530 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1531 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1532 this, SLOT(slotGroupedSortingChanged(bool)));
1533 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1534 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1535 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1536 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1538 const int itemCount
= m_model
->count();
1539 if (itemCount
> 0) {
1540 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1541 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1545 onModelChanged(model
, previous
);
1548 KItemListRubberBand
* KItemListView::rubberBand() const
1550 return m_rubberBand
;
1553 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1555 if (m_layoutTimer
->isActive()) {
1556 m_layoutTimer
->stop();
1559 if (m_activeTransactions
> 0) {
1560 if (hint
== NoAnimation
) {
1561 // As soon as at least one property change should be done without animation,
1562 // the whole transaction will be marked as not animated.
1563 m_endTransactionAnimationHint
= NoAnimation
;
1568 if (!m_model
|| m_model
->count() < 0) {
1572 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1573 if (firstVisibleIndex
< 0) {
1574 emitOffsetChanges();
1578 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1579 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1580 // is still shown if the maximum offset got decreased.
1581 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1582 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1583 if (scrollOffset() > maxOffsetToShowFullRange
) {
1584 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1585 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1588 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1590 int firstSibblingIndex
= -1;
1591 int lastSibblingIndex
= -1;
1592 const bool supportsExpanding
= supportsItemExpanding();
1594 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1596 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1597 // instances from invisible items are reused. If no reusable items are
1598 // found then new KItemListWidget instances get created.
1599 const bool animate
= (hint
== Animation
);
1600 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1601 bool applyNewPos
= true;
1602 bool wasHidden
= false;
1604 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1605 const QPointF newPos
= itemBounds
.topLeft();
1606 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1609 if (!reusableItems
.isEmpty()) {
1610 // Reuse a KItemListWidget instance from an invisible item
1611 const int oldIndex
= reusableItems
.takeLast();
1612 widget
= m_visibleItems
.value(oldIndex
);
1613 setWidgetIndex(widget
, i
);
1614 updateWidgetProperties(widget
, i
);
1615 initializeItemListWidget(widget
);
1617 // No reusable KItemListWidget instance is available, create a new one
1618 widget
= createWidget(i
);
1620 widget
->resize(itemBounds
.size());
1622 if (animate
&& changedCount
< 0) {
1623 // Items have been deleted, move the created item to the
1624 // imaginary old position. They will get animated to the new position
1626 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1627 if (itemRect
.isEmpty()) {
1628 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1629 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1630 widget
->setPos(invisibleOldPos
);
1632 widget
->setPos(itemRect
.topLeft());
1634 applyNewPos
= false;
1637 if (supportsExpanding
&& changedCount
== 0) {
1638 if (firstSibblingIndex
< 0) {
1639 firstSibblingIndex
= i
;
1641 lastSibblingIndex
= i
;
1646 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1647 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1648 applyNewPos
= false;
1651 const bool itemsRemoved
= (changedCount
< 0);
1652 const bool itemsInserted
= (changedCount
> 0);
1653 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1654 // The item is located after the removed items. Animate the moving of the position.
1655 applyNewPos
= !moveWidget(widget
, newPos
);
1656 } else if (itemsInserted
&& i
>= changedIndex
) {
1657 // The item is located after the first inserted item
1658 if (i
<= changedIndex
+ changedCount
- 1) {
1659 // The item is an inserted item. Animate the appearing of the item.
1660 // For performance reasons no animation is done when changedCount is equal
1661 // to all available items.
1662 if (changedCount
< m_model
->count()) {
1663 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1665 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1666 // The item was already there before, so animate the moving of the position.
1667 // No moving animation is done if the item is animated by a create animation: This
1668 // prevents a "move animation mess" when inserting several ranges in parallel.
1669 applyNewPos
= !moveWidget(widget
, newPos
);
1671 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1672 // The size of the view might have been changed. Animate the moving of the position.
1673 applyNewPos
= !moveWidget(widget
, newPos
);
1676 m_animation
->stop(widget
);
1680 widget
->setPos(newPos
);
1683 Q_ASSERT(widget
->index() == i
);
1684 widget
->setVisible(true);
1686 if (widget
->size() != itemBounds
.size()) {
1687 // Resize the widget for the item to the changed size.
1689 // If a dynamic item size is used then no animation is done in the direction
1690 // of the dynamic size.
1691 if (m_itemSize
.width() <= 0) {
1692 // The width is dynamic, apply the new width without animation.
1693 widget
->resize(itemBounds
.width(), widget
->size().height());
1694 } else if (m_itemSize
.height() <= 0) {
1695 // The height is dynamic, apply the new height without animation.
1696 widget
->resize(widget
->size().width(), itemBounds
.height());
1698 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1700 widget
->resize(itemBounds
.size());
1704 // Updating the cell-information must be done as last step: The decision whether the
1705 // moving-animation should be started at all is based on the previous cell-information.
1706 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1707 m_visibleCells
.insert(i
, cell
);
1710 // Delete invisible KItemListWidget instances that have not been reused
1711 foreach (int index
, reusableItems
) {
1712 recycleWidget(m_visibleItems
.value(index
));
1715 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1716 Q_ASSERT(lastSibblingIndex
>= 0);
1717 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1721 // Update the layout of all visible group headers
1722 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1723 while (it
.hasNext()) {
1725 updateGroupHeaderLayout(it
.key());
1729 emitOffsetChanges();
1732 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1733 int lastVisibleIndex
,
1734 LayoutAnimationHint hint
)
1736 // Determine all items that are completely invisible and might be
1737 // reused for items that just got (at least partly) visible. If the
1738 // animation hint is set to 'Animation' items that do e.g. an animated
1739 // moving of their position are not marked as invisible: This assures
1740 // that a scrolling inside the view can be done without breaking an animation.
1744 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1745 while (it
.hasNext()) {
1748 KItemListWidget
* widget
= it
.value();
1749 const int index
= widget
->index();
1750 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1753 if (m_animation
->isStarted(widget
)) {
1754 if (hint
== NoAnimation
) {
1755 // Stopping the animation will call KItemListView::slotAnimationFinished()
1756 // and the widget will be recycled if necessary there.
1757 m_animation
->stop(widget
);
1760 widget
->setVisible(false);
1761 items
.append(index
);
1764 recycleGroupHeaderForWidget(widget
);
1773 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1775 if (widget
->pos() == newPos
) {
1779 bool startMovingAnim
= false;
1781 if (m_itemSize
.isEmpty()) {
1782 // The items are not aligned in a grid but either as columns or rows.
1783 startMovingAnim
= true;
1785 // When having a grid the moving-animation should only be started, if it is done within
1786 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1787 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1788 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1789 const int index
= widget
->index();
1790 const Cell cell
= m_visibleCells
.value(index
);
1791 if (cell
.column
>= 0 && cell
.row
>= 0) {
1792 if (scrollOrientation() == Qt::Vertical
) {
1793 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1795 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1800 if (startMovingAnim
) {
1801 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1805 m_animation
->stop(widget
);
1806 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1810 void KItemListView::emitOffsetChanges()
1812 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1813 if (m_oldScrollOffset
!= newScrollOffset
) {
1814 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1815 m_oldScrollOffset
= newScrollOffset
;
1818 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1819 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1820 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1821 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1824 const qreal newItemOffset
= m_layouter
->itemOffset();
1825 if (m_oldItemOffset
!= newItemOffset
) {
1826 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1827 m_oldItemOffset
= newItemOffset
;
1830 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1831 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1832 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1833 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1837 KItemListWidget
* KItemListView::createWidget(int index
)
1839 KItemListWidget
* widget
= widgetCreator()->create(this);
1840 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1842 m_visibleItems
.insert(index
, widget
);
1843 m_visibleCells
.insert(index
, Cell());
1844 updateWidgetProperties(widget
, index
);
1845 initializeItemListWidget(widget
);
1849 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1852 recycleGroupHeaderForWidget(widget
);
1855 const int index
= widget
->index();
1856 m_visibleItems
.remove(index
);
1857 m_visibleCells
.remove(index
);
1859 widgetCreator()->recycle(widget
);
1862 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1864 const int oldIndex
= widget
->index();
1865 m_visibleItems
.remove(oldIndex
);
1866 m_visibleCells
.remove(oldIndex
);
1868 m_visibleItems
.insert(index
, widget
);
1869 m_visibleCells
.insert(index
, Cell());
1871 widget
->setIndex(index
);
1874 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1876 const int oldIndex
= widget
->index();
1877 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1879 setWidgetIndex(widget
, index
);
1881 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1882 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1883 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1884 (!vertical
&& oldCell
.column
== newCell
.column
);
1886 m_visibleCells
.insert(index
, newCell
);
1890 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1893 case LayouterSize
: m_layouter
->setSize(size
); break;
1894 case ItemSize
: m_layouter
->setItemSize(size
); break;
1899 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1901 widget
->setVisibleRoles(m_visibleRoles
);
1902 updateWidgetColumnWidths(widget
);
1903 widget
->setStyleOption(m_styleOption
);
1905 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1906 widget
->setCurrent(index
== selectionManager
->currentItem());
1907 widget
->setSelected(selectionManager
->isSelected(index
));
1908 widget
->setHovered(false);
1909 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1910 widget
->setIndex(index
);
1911 widget
->setData(m_model
->data(index
));
1912 widget
->setSiblingsInformation(QBitArray());
1913 updateAlternateBackgroundForWidget(widget
);
1916 updateGroupHeaderForWidget(widget
);
1920 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1922 Q_ASSERT(m_grouped
);
1924 const int index
= widget
->index();
1925 if (!m_layouter
->isFirstGroupItem(index
)) {
1926 // The widget does not represent the first item of a group
1927 // and hence requires no header
1928 recycleGroupHeaderForWidget(widget
);
1932 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1933 if (groups
.isEmpty() || !groupHeaderCreator()) {
1937 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1939 groupHeader
= groupHeaderCreator()->create(this);
1940 groupHeader
->setParentItem(widget
);
1941 m_visibleGroups
.insert(widget
, groupHeader
);
1942 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1944 Q_ASSERT(groupHeader
->parentItem() == widget
);
1946 const int groupIndex
= groupIndexForItem(index
);
1947 Q_ASSERT(groupIndex
>= 0);
1948 groupHeader
->setData(groups
.at(groupIndex
).second
);
1949 groupHeader
->setRole(model()->sortRole());
1950 groupHeader
->setStyleOption(m_styleOption
);
1951 groupHeader
->setScrollOrientation(scrollOrientation());
1952 groupHeader
->setItemIndex(index
);
1954 groupHeader
->show();
1957 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1959 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1960 Q_ASSERT(groupHeader
);
1962 const int index
= widget
->index();
1963 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1964 const QRectF itemRect
= m_layouter
->itemRect(index
);
1966 // The group-header is a child of the itemlist widget. Translate the
1967 // group header position to the relative position.
1968 if (scrollOrientation() == Qt::Vertical
) {
1969 // In the vertical scroll orientation the group header should always span
1970 // the whole width no matter which temporary position the parent widget
1971 // has. In this case the x-position and width will be adjusted manually.
1972 const qreal x
= -widget
->x() - itemOffset();
1973 const qreal width
= maximumItemOffset();
1974 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1975 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1977 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1978 groupHeader
->resize(groupHeaderRect
.size());
1982 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1984 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1986 header
->setParentItem(0);
1987 groupHeaderCreator()->recycle(header
);
1988 m_visibleGroups
.remove(widget
);
1989 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1993 void KItemListView::updateVisibleGroupHeaders()
1995 Q_ASSERT(m_grouped
);
1996 m_layouter
->markAsDirty();
1998 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1999 while (it
.hasNext()) {
2001 updateGroupHeaderForWidget(it
.value());
2005 int KItemListView::groupIndexForItem(int index
) const
2007 Q_ASSERT(m_grouped
);
2009 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2010 if (groups
.isEmpty()) {
2015 int max
= groups
.count() - 1;
2018 mid
= (min
+ max
) / 2;
2019 if (index
> groups
[mid
].first
) {
2024 } while (groups
[mid
].first
!= index
&& min
<= max
);
2027 while (groups
[mid
].first
> index
&& mid
> 0) {
2035 void KItemListView::updateAlternateBackgrounds()
2037 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2038 while (it
.hasNext()) {
2040 updateAlternateBackgroundForWidget(it
.value());
2044 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2046 bool enabled
= useAlternateBackgrounds();
2048 const int index
= widget
->index();
2049 enabled
= (index
& 0x1) > 0;
2051 const int groupIndex
= groupIndexForItem(index
);
2052 if (groupIndex
>= 0) {
2053 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2054 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2055 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2056 enabled
= (relativeIndex
& 0x1) > 0;
2060 widget
->setAlternateBackground(enabled
);
2063 bool KItemListView::useAlternateBackgrounds() const
2065 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2068 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2070 QElapsedTimer timer
;
2073 QHash
<QByteArray
, qreal
> widths
;
2075 // Calculate the minimum width for each column that is required
2076 // to show the headline unclipped.
2077 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2078 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2079 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2080 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2081 const QString headerText
= m_model
->roleDescription(visibleRole
);
2082 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2083 widths
.insert(visibleRole
, headerWidth
);
2086 // Calculate the preferred column withs for each item and ignore values
2087 // smaller than the width for showing the headline unclipped.
2088 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2089 int calculatedItemCount
= 0;
2090 bool maxTimeExceeded
= false;
2091 foreach (const KItemRange
& itemRange
, itemRanges
) {
2092 const int startIndex
= itemRange
.index
;
2093 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2095 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2096 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2097 qreal maxWidth
= widths
.value(visibleRole
, 0);
2098 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2099 maxWidth
= qMax(width
, maxWidth
);
2100 widths
.insert(visibleRole
, maxWidth
);
2103 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2104 // When having several thousands of items calculating the sizes can get
2105 // very expensive. We accept a possibly too small role-size in favour
2106 // of having no blocking user interface.
2107 maxTimeExceeded
= true;
2110 ++calculatedItemCount
;
2112 if (maxTimeExceeded
) {
2120 void KItemListView::applyColumnWidthsFromHeader()
2122 // Apply the new size to the layouter
2123 const qreal requiredWidth
= columnWidthsSum();
2124 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2125 m_itemSize
.height());
2126 m_layouter
->setItemSize(dynamicItemSize
);
2128 // Update the role sizes for all visible widgets
2129 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2130 while (it
.hasNext()) {
2132 updateWidgetColumnWidths(it
.value());
2136 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2138 foreach (const QByteArray
& role
, m_visibleRoles
) {
2139 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2143 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2145 Q_ASSERT(m_itemSize
.isEmpty());
2146 const int itemCount
= m_model
->count();
2147 int rangesItemCount
= 0;
2148 foreach (const KItemRange
& range
, itemRanges
) {
2149 rangesItemCount
+= range
.count
;
2152 if (itemCount
== rangesItemCount
) {
2153 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2154 foreach (const QByteArray
& role
, m_visibleRoles
) {
2155 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2158 // Only a sub range of the roles need to be determined.
2159 // The chances are good that the widths of the sub ranges
2160 // already fit into the available widths and hence no
2161 // expensive update might be required.
2162 bool changed
= false;
2164 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2165 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2166 while (it
.hasNext()) {
2168 const QByteArray
& role
= it
.key();
2169 const qreal updatedWidth
= it
.value();
2170 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2171 if (updatedWidth
> currentWidth
) {
2172 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2178 // All the updated sizes are smaller than the current sizes and no change
2179 // of the stretched roles-widths is required
2184 if (m_headerWidget
->automaticColumnResizing()) {
2185 applyAutomaticColumnWidths();
2189 void KItemListView::updatePreferredColumnWidths()
2192 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2196 void KItemListView::applyAutomaticColumnWidths()
2198 Q_ASSERT(m_itemSize
.isEmpty());
2199 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2200 if (m_visibleRoles
.isEmpty()) {
2204 // Calculate the maximum size of an item by considering the
2205 // visible role sizes and apply them to the layouter. If the
2206 // size does not use the available view-size the size of the
2207 // first role will get stretched.
2209 foreach (const QByteArray
& role
, m_visibleRoles
) {
2210 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2211 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2214 const QByteArray firstRole
= m_visibleRoles
.first();
2215 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2216 QSizeF dynamicItemSize
= m_itemSize
;
2218 qreal requiredWidth
= columnWidthsSum();
2219 const qreal availableWidth
= size().width();
2220 if (requiredWidth
< availableWidth
) {
2221 // Stretch the first column to use the whole remaining width
2222 firstColumnWidth
+= availableWidth
- requiredWidth
;
2223 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2224 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2225 // Shrink the first column to be able to show as much other
2226 // columns as possible
2227 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2229 // TODO: A proper calculation of the minimum width depends on the implementation
2230 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2232 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2233 if (shrinkedFirstColumnWidth
< minWidth
) {
2234 shrinkedFirstColumnWidth
= minWidth
;
2237 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2238 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2241 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2243 m_layouter
->setItemSize(dynamicItemSize
);
2245 // Update the role sizes for all visible widgets
2246 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2247 while (it
.hasNext()) {
2249 updateWidgetColumnWidths(it
.value());
2253 qreal
KItemListView::columnWidthsSum() const
2255 qreal widthsSum
= 0;
2256 foreach (const QByteArray
& role
, m_visibleRoles
) {
2257 widthsSum
+= m_headerWidget
->columnWidth(role
);
2262 QRectF
KItemListView::headerBoundaries() const
2264 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2267 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2268 const QSizeF
& newItemSize
,
2269 const QSizeF
& newItemMargin
) const
2271 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2275 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2276 const qreal itemWidth
= m_layouter
->itemSize().width();
2277 if (itemWidth
> 0) {
2278 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2279 newItemSize
.width(),
2280 newItemMargin
.width());
2281 if (m_model
->count() > newColumnCount
) {
2282 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2284 m_layouter
->itemMargin().width());
2285 return oldColumnCount
!= newColumnCount
;
2289 const qreal itemHeight
= m_layouter
->itemSize().height();
2290 if (itemHeight
> 0) {
2291 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2292 newItemSize
.height(),
2293 newItemMargin
.height());
2294 if (m_model
->count() > newRowCount
) {
2295 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2297 m_layouter
->itemMargin().height());
2298 return oldRowCount
!= newRowCount
;
2306 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2308 if (m_itemSize
.isEmpty()) {
2309 // We have only columns or only rows, but no grid: An animation is usually
2310 // welcome when inserting or removing items.
2311 return !supportsItemExpanding();
2314 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2318 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2319 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2320 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2321 // Only animate if up to 2/3 of a row or column are inserted or removed
2322 return changedItemCount
<= maximum
* 2 / 3;
2326 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2328 const QSizeF oldSize
= m_layouter
->size();
2330 m_layouter
->setSize(size
);
2331 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2332 m_layouter
->setSize(oldSize
);
2334 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2335 : maxOffset
> size
.width();
2338 int KItemListView::showDropIndicator(const QPointF
& pos
)
2340 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2341 while (it
.hasNext()) {
2343 const KItemListWidget
* widget
= it
.value();
2345 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2346 const QRectF rect
= itemRect(widget
->index());
2347 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2348 if (m_model
->supportsDropping(widget
->index())) {
2349 const int gap
= qMax(4, m_styleOption
.padding
);
2350 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2355 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2356 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2358 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2359 if (m_dropIndicator
!= draggingInsertIndicator
) {
2360 m_dropIndicator
= draggingInsertIndicator
;
2364 int index
= widget
->index();
2372 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2373 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2376 void KItemListView::hideDropIndicator()
2378 if (!m_dropIndicator
.isNull()) {
2379 m_dropIndicator
= QRectF();
2384 void KItemListView::updateGroupHeaderHeight()
2386 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2387 qreal groupHeaderMargin
= 0;
2389 if (scrollOrientation() == Qt::Horizontal
) {
2390 // The vertical margin above and below the header should be
2391 // equal to the horizontal margin, not the vertical margin
2392 // from m_styleOption.
2393 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2394 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2395 } else if (m_itemSize
.isEmpty()){
2396 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2397 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2399 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2400 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2402 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2403 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2405 updateVisibleGroupHeaders();
2408 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2410 if (!supportsItemExpanding() || !m_model
) {
2414 if (firstIndex
< 0 || lastIndex
< 0) {
2415 firstIndex
= m_layouter
->firstVisibleIndex();
2416 lastIndex
= m_layouter
->lastVisibleIndex();
2418 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2419 lastIndex
>= m_layouter
->firstVisibleIndex());
2420 if (!isRangeVisible
) {
2425 int previousParents
= 0;
2426 QBitArray previousSiblings
;
2428 // The rootIndex describes the first index where the siblings get
2429 // calculated from. For the calculation the upper most parent item
2430 // is required. For performance reasons it is checked first whether
2431 // the visible items before or after the current range already
2432 // contain a siblings information which can be used as base.
2433 int rootIndex
= firstIndex
;
2435 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2437 // There is no visible widget before the range, check whether there
2438 // is one after the range:
2439 widget
= m_visibleItems
.value(lastIndex
+ 1);
2441 // The sibling information of the widget may only be used if
2442 // all items of the range have the same number of parents.
2443 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2444 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2445 if (m_model
->expandedParentsCount(i
) != parents
) {
2454 // Performance optimization: Use the sibling information of the visible
2455 // widget beside the given range.
2456 previousSiblings
= widget
->siblingsInformation();
2457 if (previousSiblings
.isEmpty()) {
2460 previousParents
= previousSiblings
.count() - 1;
2461 previousSiblings
.truncate(previousParents
);
2463 // Potentially slow path: Go back to the upper most parent of firstIndex
2464 // to be able to calculate the initial value for the siblings.
2465 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2470 Q_ASSERT(previousParents
>= 0);
2471 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2472 // Update the parent-siblings in case if the current item represents
2473 // a child or an upper parent.
2474 const int currentParents
= m_model
->expandedParentsCount(i
);
2475 Q_ASSERT(currentParents
>= 0);
2476 if (previousParents
< currentParents
) {
2477 previousParents
= currentParents
;
2478 previousSiblings
.resize(currentParents
);
2479 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2480 } else if (previousParents
> currentParents
) {
2481 previousParents
= currentParents
;
2482 previousSiblings
.truncate(currentParents
);
2485 if (i
>= firstIndex
) {
2486 // The index represents a visible item. Apply the parent-siblings
2487 // and update the sibling of the current item.
2488 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2493 QBitArray siblings
= previousSiblings
;
2494 siblings
.resize(siblings
.count() + 1);
2495 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2497 widget
->setSiblingsInformation(siblings
);
2502 bool KItemListView::hasSiblingSuccessor(int index
) const
2504 bool hasSuccessor
= false;
2505 const int parentsCount
= m_model
->expandedParentsCount(index
);
2506 int successorIndex
= index
+ 1;
2508 // Search the next sibling
2509 const int itemCount
= m_model
->count();
2510 while (successorIndex
< itemCount
) {
2511 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2512 if (currentParentsCount
== parentsCount
) {
2513 hasSuccessor
= true;
2515 } else if (currentParentsCount
< parentsCount
) {
2521 if (m_grouped
&& hasSuccessor
) {
2522 // If the sibling is part of another group, don't mark it as
2523 // successor as the group header is between the sibling connections.
2524 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2525 if (m_layouter
->isFirstGroupItem(i
)) {
2526 hasSuccessor
= false;
2532 return hasSuccessor
;
2535 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2539 const int minSpeed
= 4;
2540 const int maxSpeed
= 128;
2541 const int speedLimiter
= 96;
2542 const int autoScrollBorder
= 64;
2544 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2545 // This assures that the autoscrolling speed grows gradually.
2546 const int incLimiter
= 1;
2548 if (pos
< autoScrollBorder
) {
2549 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2550 inc
= qMax(inc
, -maxSpeed
);
2551 inc
= qMax(inc
, oldInc
- incLimiter
);
2552 } else if (pos
> range
- autoScrollBorder
) {
2553 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2554 inc
= qMin(inc
, maxSpeed
);
2555 inc
= qMin(inc
, oldInc
+ incLimiter
);
2561 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2563 const qreal availableSize
= size
- itemMargin
;
2564 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2570 KItemListCreatorBase::~KItemListCreatorBase()
2572 qDeleteAll(m_recycleableWidgets
);
2573 qDeleteAll(m_createdWidgets
);
2576 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2578 m_createdWidgets
.insert(widget
);
2581 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2583 Q_ASSERT(m_createdWidgets
.contains(widget
));
2584 m_createdWidgets
.remove(widget
);
2586 if (m_recycleableWidgets
.count() < 100) {
2587 m_recycleableWidgets
.append(widget
);
2588 widget
->setVisible(false);
2594 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2596 if (m_recycleableWidgets
.isEmpty()) {
2600 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2601 m_createdWidgets
.insert(widget
);
2605 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2609 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2611 widget
->setParentItem(0);
2612 widget
->setOpacity(1.0);
2613 pushRecycleableWidget(widget
);
2616 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2620 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2622 header
->setOpacity(1.0);
2623 pushRecycleableWidget(header
);
2626 #include "kitemlistview.moc"