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 void KItemListView::setItemSize(const QSizeF
& size
)
667 const QSizeF previousSize
= m_itemSize
;
668 if (size
== previousSize
) {
672 // Skip animations when the number of rows or columns
673 // are changed in the grid layout. Although the animation
674 // engine can handle this usecase, it looks obtrusive.
675 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
677 m_layouter
->itemMargin());
679 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
680 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
681 (!m_itemSize
.isEmpty() && size
.isEmpty()));
685 if (alternateBackgroundsChanged
) {
686 // For an empty item size alternate backgrounds are drawn if more than
687 // one role is shown. Assure that the backgrounds for visible items are
688 // updated when changing the size in this context.
689 updateAlternateBackgrounds();
692 if (size
.isEmpty()) {
693 if (m_headerWidget
->automaticColumnResizing()) {
694 updatePreferredColumnWidths();
696 // Only apply the changed height and respect the header widths
698 const qreal currentWidth
= m_layouter
->itemSize().width();
699 const QSizeF
newSize(currentWidth
, size
.height());
700 m_layouter
->setItemSize(newSize
);
703 m_layouter
->setItemSize(size
);
706 m_sizeHintResolver
->clearCache();
707 doLayout(animate
? Animation
: NoAnimation
);
708 onItemSizeChanged(size
, previousSize
);
711 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
713 const KItemListStyleOption previousOption
= m_styleOption
;
714 m_styleOption
= option
;
717 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
718 if (margin
!= m_layouter
->itemMargin()) {
719 // Skip animations when the number of rows or columns
720 // are changed in the grid layout. Although the animation
721 // engine can handle this usecase, it looks obtrusive.
722 animate
= !changesItemGridLayout(m_layouter
->size(),
723 m_layouter
->itemSize(),
725 m_layouter
->setItemMargin(margin
);
729 updateGroupHeaderHeight();
732 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
733 // Animating a change of the maximum text size just results in expensive
734 // temporary eliding and clipping operations and does not look good visually.
738 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
739 while (it
.hasNext()) {
741 it
.value()->setStyleOption(option
);
744 m_sizeHintResolver
->clearCache();
745 m_layouter
->markAsDirty();
746 doLayout(animate
? Animation
: NoAnimation
);
748 if (m_itemSize
.isEmpty()) {
749 updatePreferredColumnWidths();
752 onStyleOptionChanged(option
, previousOption
);
755 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
757 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
758 if (orientation
== previousOrientation
) {
762 m_layouter
->setScrollOrientation(orientation
);
763 m_animation
->setScrollOrientation(orientation
);
764 m_sizeHintResolver
->clearCache();
767 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
768 while (it
.hasNext()) {
770 it
.value()->setScrollOrientation(orientation
);
772 updateGroupHeaderHeight();
776 doLayout(NoAnimation
);
778 onScrollOrientationChanged(orientation
, previousOrientation
);
779 emit
scrollOrientationChanged(orientation
, previousOrientation
);
782 Qt::Orientation
KItemListView::scrollOrientation() const
784 return m_layouter
->scrollOrientation();
787 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
792 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
797 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
802 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
804 Q_UNUSED(changedRoles
);
808 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
814 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
820 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
826 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
832 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
838 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
844 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
850 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
852 Q_UNUSED(supportsExpanding
);
855 void KItemListView::onTransactionBegin()
859 void KItemListView::onTransactionEnd()
863 bool KItemListView::event(QEvent
* event
)
865 // Forward all events to the controller and handle them there
866 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
870 return QGraphicsWidget::event(event
);
873 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
875 m_mousePos
= transform().map(event
->pos());
879 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
881 QGraphicsWidget::mouseMoveEvent(event
);
883 m_mousePos
= transform().map(event
->pos());
884 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
885 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
889 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
891 event
->setAccepted(true);
895 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
897 QGraphicsWidget::dragMoveEvent(event
);
899 m_mousePos
= transform().map(event
->pos());
900 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
901 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
905 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
907 QGraphicsWidget::dragLeaveEvent(event
);
908 setAutoScroll(false);
911 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
913 QGraphicsWidget::dropEvent(event
);
914 setAutoScroll(false);
917 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
919 return m_visibleItems
.values();
922 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
924 if (m_itemSize
.isEmpty()) {
925 updatePreferredColumnWidths(itemRanges
);
928 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
929 if (hasMultipleRanges
) {
933 m_layouter
->markAsDirty();
935 int previouslyInsertedCount
= 0;
936 foreach (const KItemRange
& range
, itemRanges
) {
937 // range.index is related to the model before anything has been inserted.
938 // As in each loop the current item-range gets inserted the index must
939 // be increased by the already previously inserted items.
940 const int index
= range
.index
+ previouslyInsertedCount
;
941 const int count
= range
.count
;
942 if (index
< 0 || count
<= 0) {
943 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
946 previouslyInsertedCount
+= count
;
948 m_sizeHintResolver
->itemsInserted(index
, count
);
950 // Determine which visible items must be moved
951 QList
<int> itemsToMove
;
952 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
953 while (it
.hasNext()) {
955 const int visibleItemIndex
= it
.key();
956 if (visibleItemIndex
>= index
) {
957 itemsToMove
.append(visibleItemIndex
);
961 // Update the indexes of all KItemListWidget instances that are located
962 // after the inserted items. It is important to adjust the indexes in the order
963 // from the highest index to the lowest index to prevent overlaps when setting the new index.
965 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
966 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
968 const int newIndex
= widget
->index() + count
;
969 if (hasMultipleRanges
) {
970 setWidgetIndex(widget
, newIndex
);
972 // Try to animate the moving of the item
973 moveWidgetToIndex(widget
, newIndex
);
977 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
978 // Check whether a scrollbar is required to show the inserted items. In this case
979 // the size of the layouter will be decreased before calling doLayout(): This prevents
980 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
981 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
982 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
983 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
984 if (decreaseLayouterSize
) {
985 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
986 QSizeF layouterSize
= m_layouter
->size();
987 if (verticalScrollOrientation
) {
988 layouterSize
.rwidth() -= scrollBarExtent
;
990 layouterSize
.rheight() -= scrollBarExtent
;
992 m_layouter
->setSize(layouterSize
);
996 if (!hasMultipleRanges
) {
997 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
998 updateSiblingsInformation();
1003 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1006 if (hasMultipleRanges
) {
1008 // Important: Don't read any m_layouter-property inside the for-loop in case if
1009 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1010 // updated in each loop-cycle and has only a consistent state after the loop.
1011 Q_ASSERT(m_layouter
->isDirty());
1013 m_endTransactionAnimationHint
= NoAnimation
;
1016 updateSiblingsInformation();
1019 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1020 // In case if items of the same group have been inserted before an item that
1021 // currently represents the first item of the group, the group header of
1022 // this item must be removed.
1023 updateVisibleGroupHeaders();
1026 if (useAlternateBackgrounds()) {
1027 updateAlternateBackgrounds();
1031 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1033 if (m_itemSize
.isEmpty()) {
1034 // Don't pass the item-range: The preferred column-widths of
1035 // all items must be adjusted when removing items.
1036 updatePreferredColumnWidths();
1039 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1040 if (hasMultipleRanges
) {
1044 m_layouter
->markAsDirty();
1046 int removedItemsCount
= 0;
1047 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1048 removedItemsCount
+= itemRanges
[i
].count
;
1051 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1052 const KItemRange
& range
= itemRanges
[i
];
1053 const int index
= range
.index
;
1054 const int count
= range
.count
;
1055 if (index
< 0 || count
<= 0) {
1056 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1060 m_sizeHintResolver
->itemsRemoved(index
, count
);
1062 const int firstRemovedIndex
= index
;
1063 const int lastRemovedIndex
= index
+ count
- 1;
1064 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1065 removedItemsCount
-= count
;
1067 // Remove all KItemListWidget instances that got deleted
1068 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1069 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1074 m_animation
->stop(widget
);
1075 // Stopping the animation might lead to recycling the widget if
1076 // it is invisible (see slotAnimationFinished()).
1077 // Check again whether it is still visible:
1078 if (!m_visibleItems
.contains(i
)) {
1082 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1083 // Remove the widget without animation
1084 recycleWidget(widget
);
1086 // Animate the removing of the items. Special case: When removing an item there
1087 // is no valid model index available anymore. For the
1088 // remove-animation the item gets removed from m_visibleItems but the widget
1089 // will stay alive until the animation has been finished and will
1090 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1091 m_visibleItems
.remove(i
);
1092 widget
->setIndex(-1);
1093 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1097 // Update the indexes of all KItemListWidget instances that are located
1098 // after the deleted items
1099 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1100 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1102 const int newIndex
= i
- count
;
1103 if (hasMultipleRanges
) {
1104 setWidgetIndex(widget
, newIndex
);
1106 // Try to animate the moving of the item
1107 moveWidgetToIndex(widget
, newIndex
);
1112 if (!hasMultipleRanges
) {
1113 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1114 // assumes an updated geometry. If items are removed during an active transaction,
1115 // the transaction will be temporary deactivated so that doLayout() triggers a
1116 // geometry update if necessary.
1117 const int activeTransactions
= m_activeTransactions
;
1118 m_activeTransactions
= 0;
1119 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1120 m_activeTransactions
= activeTransactions
;
1121 updateSiblingsInformation();
1126 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1129 if (hasMultipleRanges
) {
1131 // Important: Don't read any m_layouter-property inside the for-loop in case if
1132 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1133 // updated in each loop-cycle and has only a consistent state after the loop.
1134 Q_ASSERT(m_layouter
->isDirty());
1136 m_endTransactionAnimationHint
= NoAnimation
;
1138 updateSiblingsInformation();
1141 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1142 // In case if the first item of a group has been removed, the group header
1143 // must be applied to the next visible item.
1144 updateVisibleGroupHeaders();
1147 if (useAlternateBackgrounds()) {
1148 updateAlternateBackgrounds();
1152 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1154 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1155 m_layouter
->markAsDirty();
1158 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1161 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1162 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1164 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1165 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1167 updateWidgetProperties(widget
, index
);
1168 initializeItemListWidget(widget
);
1172 doLayout(NoAnimation
);
1173 updateSiblingsInformation();
1176 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1177 const QSet
<QByteArray
>& roles
)
1179 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1180 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1181 updatePreferredColumnWidths(itemRanges
);
1184 foreach (const KItemRange
& itemRange
, itemRanges
) {
1185 const int index
= itemRange
.index
;
1186 const int count
= itemRange
.count
;
1188 if (updateSizeHints
) {
1189 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1190 m_layouter
->markAsDirty();
1192 if (!m_layoutTimer
->isActive()) {
1193 m_layoutTimer
->start();
1197 // Apply the changed roles to the visible item-widgets
1198 const int lastIndex
= index
+ count
- 1;
1199 for (int i
= index
; i
<= lastIndex
; ++i
) {
1200 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1202 widget
->setData(m_model
->data(i
), roles
);
1206 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1207 // The sort-role has been changed which might result
1208 // in modified group headers
1209 updateVisibleGroupHeaders();
1210 doLayout(NoAnimation
);
1213 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1216 void KItemListView::slotGroupedSortingChanged(bool current
)
1218 m_grouped
= current
;
1219 m_layouter
->markAsDirty();
1222 updateGroupHeaderHeight();
1224 // Clear all visible headers
1225 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1226 while (it
.hasNext()) {
1228 recycleGroupHeaderForWidget(it
.key());
1230 Q_ASSERT(m_visibleGroups
.isEmpty());
1233 if (useAlternateBackgrounds()) {
1234 // Changing the group mode requires to update the alternate backgrounds
1235 // as with the enabled group mode the altering is done on base of the first
1237 updateAlternateBackgrounds();
1239 updateSiblingsInformation();
1240 doLayout(NoAnimation
);
1243 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1248 updateVisibleGroupHeaders();
1249 doLayout(NoAnimation
);
1253 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1258 updateVisibleGroupHeaders();
1259 doLayout(NoAnimation
);
1263 void KItemListView::slotCurrentChanged(int current
, int previous
)
1267 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1268 if (previousWidget
) {
1269 previousWidget
->setCurrent(false);
1272 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1273 if (currentWidget
) {
1274 currentWidget
->setCurrent(true);
1276 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1279 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1283 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1284 while (it
.hasNext()) {
1286 const int index
= it
.key();
1287 KItemListWidget
* widget
= it
.value();
1288 widget
->setSelected(current
.contains(index
));
1292 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1293 KItemListViewAnimation::AnimationType type
)
1295 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1296 Q_ASSERT(itemListWidget
);
1299 case KItemListViewAnimation::DeleteAnimation
: {
1300 // As we recycle the widget in this case it is important to assure that no
1301 // other animation has been started. This is a convention in KItemListView and
1302 // not a requirement defined by KItemListViewAnimation.
1303 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1305 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1306 // by m_visibleWidgets and must be deleted manually after the animation has
1308 recycleGroupHeaderForWidget(itemListWidget
);
1309 widgetCreator()->recycle(itemListWidget
);
1313 case KItemListViewAnimation::CreateAnimation
:
1314 case KItemListViewAnimation::MovingAnimation
:
1315 case KItemListViewAnimation::ResizeAnimation
: {
1316 const int index
= itemListWidget
->index();
1317 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1318 (index
> m_layouter
->lastVisibleIndex());
1319 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1320 recycleWidget(itemListWidget
);
1329 void KItemListView::slotLayoutTimerFinished()
1331 m_layouter
->setSize(geometry().size());
1332 doLayout(Animation
);
1335 void KItemListView::slotRubberBandPosChanged()
1340 void KItemListView::slotRubberBandActivationChanged(bool active
)
1343 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1344 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1345 m_skipAutoScrollForRubberBand
= true;
1347 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1348 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1349 m_skipAutoScrollForRubberBand
= false;
1355 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1357 qreal previousWidth
)
1360 Q_UNUSED(currentWidth
);
1361 Q_UNUSED(previousWidth
);
1363 m_headerWidget
->setAutomaticColumnResizing(false);
1364 applyColumnWidthsFromHeader();
1365 doLayout(NoAnimation
);
1368 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1372 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1374 const QList
<QByteArray
> previous
= m_visibleRoles
;
1376 QList
<QByteArray
> current
= m_visibleRoles
;
1377 current
.removeAt(previousIndex
);
1378 current
.insert(currentIndex
, role
);
1380 setVisibleRoles(current
);
1382 emit
visibleRolesChanged(current
, previous
);
1385 void KItemListView::triggerAutoScrolling()
1387 if (!m_autoScrollTimer
) {
1392 int visibleSize
= 0;
1393 if (scrollOrientation() == Qt::Vertical
) {
1394 pos
= m_mousePos
.y();
1395 visibleSize
= size().height();
1397 pos
= m_mousePos
.x();
1398 visibleSize
= size().width();
1401 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1402 m_autoScrollIncrement
= 0;
1405 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1406 if (m_autoScrollIncrement
== 0) {
1407 // The mouse position is not above an autoscroll margin (the autoscroll timer
1408 // will be restarted in mouseMoveEvent())
1409 m_autoScrollTimer
->stop();
1413 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1414 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1415 // if the direction of the rubberband is similar to the autoscroll direction. This
1416 // prevents that starting to create a rubberband within the autoscroll margins starts
1417 // an autoscrolling.
1419 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1420 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1421 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1422 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1423 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1424 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1425 // been moved up although the autoscroll direction might be down)
1426 m_autoScrollTimer
->stop();
1431 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1432 // the autoscrolling may not get skipped anymore until a new rubberband is created
1433 m_skipAutoScrollForRubberBand
= false;
1435 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1436 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1437 setScrollOffset(newScrollOffset
);
1439 // Trigger the autoscroll timer which will periodically call
1440 // triggerAutoScrolling()
1441 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1444 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1446 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1448 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1449 Q_ASSERT(groupHeader
);
1450 updateGroupHeaderLayout(widget
);
1453 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1455 emit
roleEditingCanceled(index
, role
, value
);
1456 m_editingRole
= false;
1459 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1461 emit
roleEditingFinished(index
, role
, value
);
1462 m_editingRole
= false;
1465 void KItemListView::setController(KItemListController
* controller
)
1467 if (m_controller
!= controller
) {
1468 KItemListController
* previous
= m_controller
;
1470 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1471 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1472 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1475 m_controller
= controller
;
1478 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1479 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1480 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1483 onControllerChanged(controller
, previous
);
1487 void KItemListView::setModel(KItemModelBase
* model
)
1489 if (m_model
== model
) {
1493 KItemModelBase
* previous
= m_model
;
1496 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1497 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1498 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1499 this, SLOT(slotItemsInserted(KItemRangeList
)));
1500 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1501 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1502 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1503 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1504 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1505 this, SLOT(slotGroupedSortingChanged(bool)));
1506 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1507 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1508 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1509 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1512 m_sizeHintResolver
->clearCache();
1515 m_layouter
->setModel(model
);
1516 m_grouped
= model
->groupedSorting();
1519 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1520 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1521 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1522 this, SLOT(slotItemsInserted(KItemRangeList
)));
1523 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1524 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1525 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1526 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1527 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1528 this, SLOT(slotGroupedSortingChanged(bool)));
1529 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1530 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1531 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1532 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1534 const int itemCount
= m_model
->count();
1535 if (itemCount
> 0) {
1536 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1537 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1541 onModelChanged(model
, previous
);
1544 KItemListRubberBand
* KItemListView::rubberBand() const
1546 return m_rubberBand
;
1549 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1551 if (m_layoutTimer
->isActive()) {
1552 m_layoutTimer
->stop();
1555 if (m_activeTransactions
> 0) {
1556 if (hint
== NoAnimation
) {
1557 // As soon as at least one property change should be done without animation,
1558 // the whole transaction will be marked as not animated.
1559 m_endTransactionAnimationHint
= NoAnimation
;
1564 if (!m_model
|| m_model
->count() < 0) {
1568 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1569 if (firstVisibleIndex
< 0) {
1570 emitOffsetChanges();
1574 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1575 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1576 // is still shown if the maximum offset got decreased.
1577 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1578 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1579 if (scrollOffset() > maxOffsetToShowFullRange
) {
1580 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1581 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1584 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1586 int firstSibblingIndex
= -1;
1587 int lastSibblingIndex
= -1;
1588 const bool supportsExpanding
= supportsItemExpanding();
1590 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1592 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1593 // instances from invisible items are reused. If no reusable items are
1594 // found then new KItemListWidget instances get created.
1595 const bool animate
= (hint
== Animation
);
1596 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1597 bool applyNewPos
= true;
1598 bool wasHidden
= false;
1600 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1601 const QPointF newPos
= itemBounds
.topLeft();
1602 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1605 if (!reusableItems
.isEmpty()) {
1606 // Reuse a KItemListWidget instance from an invisible item
1607 const int oldIndex
= reusableItems
.takeLast();
1608 widget
= m_visibleItems
.value(oldIndex
);
1609 setWidgetIndex(widget
, i
);
1610 updateWidgetProperties(widget
, i
);
1611 initializeItemListWidget(widget
);
1613 // No reusable KItemListWidget instance is available, create a new one
1614 widget
= createWidget(i
);
1616 widget
->resize(itemBounds
.size());
1618 if (animate
&& changedCount
< 0) {
1619 // Items have been deleted, move the created item to the
1620 // imaginary old position. They will get animated to the new position
1622 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1623 if (itemRect
.isEmpty()) {
1624 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1625 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1626 widget
->setPos(invisibleOldPos
);
1628 widget
->setPos(itemRect
.topLeft());
1630 applyNewPos
= false;
1633 if (supportsExpanding
&& changedCount
== 0) {
1634 if (firstSibblingIndex
< 0) {
1635 firstSibblingIndex
= i
;
1637 lastSibblingIndex
= i
;
1642 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1643 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1644 applyNewPos
= false;
1647 const bool itemsRemoved
= (changedCount
< 0);
1648 const bool itemsInserted
= (changedCount
> 0);
1649 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1650 // The item is located after the removed items. Animate the moving of the position.
1651 applyNewPos
= !moveWidget(widget
, newPos
);
1652 } else if (itemsInserted
&& i
>= changedIndex
) {
1653 // The item is located after the first inserted item
1654 if (i
<= changedIndex
+ changedCount
- 1) {
1655 // The item is an inserted item. Animate the appearing of the item.
1656 // For performance reasons no animation is done when changedCount is equal
1657 // to all available items.
1658 if (changedCount
< m_model
->count()) {
1659 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1661 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1662 // The item was already there before, so animate the moving of the position.
1663 // No moving animation is done if the item is animated by a create animation: This
1664 // prevents a "move animation mess" when inserting several ranges in parallel.
1665 applyNewPos
= !moveWidget(widget
, newPos
);
1667 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1668 // The size of the view might have been changed. Animate the moving of the position.
1669 applyNewPos
= !moveWidget(widget
, newPos
);
1672 m_animation
->stop(widget
);
1676 widget
->setPos(newPos
);
1679 Q_ASSERT(widget
->index() == i
);
1680 widget
->setVisible(true);
1682 if (widget
->size() != itemBounds
.size()) {
1683 // Resize the widget for the item to the changed size.
1685 // If a dynamic item size is used then no animation is done in the direction
1686 // of the dynamic size.
1687 if (m_itemSize
.width() <= 0) {
1688 // The width is dynamic, apply the new width without animation.
1689 widget
->resize(itemBounds
.width(), widget
->size().height());
1690 } else if (m_itemSize
.height() <= 0) {
1691 // The height is dynamic, apply the new height without animation.
1692 widget
->resize(widget
->size().width(), itemBounds
.height());
1694 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1696 widget
->resize(itemBounds
.size());
1700 // Updating the cell-information must be done as last step: The decision whether the
1701 // moving-animation should be started at all is based on the previous cell-information.
1702 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1703 m_visibleCells
.insert(i
, cell
);
1706 // Delete invisible KItemListWidget instances that have not been reused
1707 foreach (int index
, reusableItems
) {
1708 recycleWidget(m_visibleItems
.value(index
));
1711 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1712 Q_ASSERT(lastSibblingIndex
>= 0);
1713 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1717 // Update the layout of all visible group headers
1718 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1719 while (it
.hasNext()) {
1721 updateGroupHeaderLayout(it
.key());
1725 emitOffsetChanges();
1728 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1729 int lastVisibleIndex
,
1730 LayoutAnimationHint hint
)
1732 // Determine all items that are completely invisible and might be
1733 // reused for items that just got (at least partly) visible. If the
1734 // animation hint is set to 'Animation' items that do e.g. an animated
1735 // moving of their position are not marked as invisible: This assures
1736 // that a scrolling inside the view can be done without breaking an animation.
1740 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1741 while (it
.hasNext()) {
1744 KItemListWidget
* widget
= it
.value();
1745 const int index
= widget
->index();
1746 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1749 if (m_animation
->isStarted(widget
)) {
1750 if (hint
== NoAnimation
) {
1751 // Stopping the animation will call KItemListView::slotAnimationFinished()
1752 // and the widget will be recycled if necessary there.
1753 m_animation
->stop(widget
);
1756 widget
->setVisible(false);
1757 items
.append(index
);
1760 recycleGroupHeaderForWidget(widget
);
1769 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1771 if (widget
->pos() == newPos
) {
1775 bool startMovingAnim
= false;
1777 if (m_itemSize
.isEmpty()) {
1778 // The items are not aligned in a grid but either as columns or rows.
1779 startMovingAnim
= true;
1781 // When having a grid the moving-animation should only be started, if it is done within
1782 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1783 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1784 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1785 const int index
= widget
->index();
1786 const Cell cell
= m_visibleCells
.value(index
);
1787 if (cell
.column
>= 0 && cell
.row
>= 0) {
1788 if (scrollOrientation() == Qt::Vertical
) {
1789 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1791 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1796 if (startMovingAnim
) {
1797 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1801 m_animation
->stop(widget
);
1802 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1806 void KItemListView::emitOffsetChanges()
1808 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1809 if (m_oldScrollOffset
!= newScrollOffset
) {
1810 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1811 m_oldScrollOffset
= newScrollOffset
;
1814 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1815 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1816 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1817 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1820 const qreal newItemOffset
= m_layouter
->itemOffset();
1821 if (m_oldItemOffset
!= newItemOffset
) {
1822 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1823 m_oldItemOffset
= newItemOffset
;
1826 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1827 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1828 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1829 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1833 KItemListWidget
* KItemListView::createWidget(int index
)
1835 KItemListWidget
* widget
= widgetCreator()->create(this);
1836 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1838 m_visibleItems
.insert(index
, widget
);
1839 m_visibleCells
.insert(index
, Cell());
1840 updateWidgetProperties(widget
, index
);
1841 initializeItemListWidget(widget
);
1845 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1848 recycleGroupHeaderForWidget(widget
);
1851 const int index
= widget
->index();
1852 m_visibleItems
.remove(index
);
1853 m_visibleCells
.remove(index
);
1855 widgetCreator()->recycle(widget
);
1858 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1860 const int oldIndex
= widget
->index();
1861 m_visibleItems
.remove(oldIndex
);
1862 m_visibleCells
.remove(oldIndex
);
1864 m_visibleItems
.insert(index
, widget
);
1865 m_visibleCells
.insert(index
, Cell());
1867 widget
->setIndex(index
);
1870 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1872 const int oldIndex
= widget
->index();
1873 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1875 setWidgetIndex(widget
, index
);
1877 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1878 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1879 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1880 (!vertical
&& oldCell
.column
== newCell
.column
);
1882 m_visibleCells
.insert(index
, newCell
);
1886 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1889 case LayouterSize
: m_layouter
->setSize(size
); break;
1890 case ItemSize
: m_layouter
->setItemSize(size
); break;
1895 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1897 widget
->setVisibleRoles(m_visibleRoles
);
1898 updateWidgetColumnWidths(widget
);
1899 widget
->setStyleOption(m_styleOption
);
1901 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1902 widget
->setCurrent(index
== selectionManager
->currentItem());
1903 widget
->setSelected(selectionManager
->isSelected(index
));
1904 widget
->setHovered(false);
1905 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1906 widget
->setIndex(index
);
1907 widget
->setData(m_model
->data(index
));
1908 widget
->setSiblingsInformation(QBitArray());
1909 updateAlternateBackgroundForWidget(widget
);
1912 updateGroupHeaderForWidget(widget
);
1916 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1918 Q_ASSERT(m_grouped
);
1920 const int index
= widget
->index();
1921 if (!m_layouter
->isFirstGroupItem(index
)) {
1922 // The widget does not represent the first item of a group
1923 // and hence requires no header
1924 recycleGroupHeaderForWidget(widget
);
1928 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1929 if (groups
.isEmpty() || !groupHeaderCreator()) {
1933 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1935 groupHeader
= groupHeaderCreator()->create(this);
1936 groupHeader
->setParentItem(widget
);
1937 m_visibleGroups
.insert(widget
, groupHeader
);
1938 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1940 Q_ASSERT(groupHeader
->parentItem() == widget
);
1942 const int groupIndex
= groupIndexForItem(index
);
1943 Q_ASSERT(groupIndex
>= 0);
1944 groupHeader
->setData(groups
.at(groupIndex
).second
);
1945 groupHeader
->setRole(model()->sortRole());
1946 groupHeader
->setStyleOption(m_styleOption
);
1947 groupHeader
->setScrollOrientation(scrollOrientation());
1948 groupHeader
->setItemIndex(index
);
1950 groupHeader
->show();
1953 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1955 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1956 Q_ASSERT(groupHeader
);
1958 const int index
= widget
->index();
1959 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1960 const QRectF itemRect
= m_layouter
->itemRect(index
);
1962 // The group-header is a child of the itemlist widget. Translate the
1963 // group header position to the relative position.
1964 if (scrollOrientation() == Qt::Vertical
) {
1965 // In the vertical scroll orientation the group header should always span
1966 // the whole width no matter which temporary position the parent widget
1967 // has. In this case the x-position and width will be adjusted manually.
1968 const qreal x
= -widget
->x() - itemOffset();
1969 const qreal width
= maximumItemOffset();
1970 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1971 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1973 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1974 groupHeader
->resize(groupHeaderRect
.size());
1978 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1980 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1982 header
->setParentItem(0);
1983 groupHeaderCreator()->recycle(header
);
1984 m_visibleGroups
.remove(widget
);
1985 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1989 void KItemListView::updateVisibleGroupHeaders()
1991 Q_ASSERT(m_grouped
);
1992 m_layouter
->markAsDirty();
1994 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1995 while (it
.hasNext()) {
1997 updateGroupHeaderForWidget(it
.value());
2001 int KItemListView::groupIndexForItem(int index
) const
2003 Q_ASSERT(m_grouped
);
2005 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2006 if (groups
.isEmpty()) {
2011 int max
= groups
.count() - 1;
2014 mid
= (min
+ max
) / 2;
2015 if (index
> groups
[mid
].first
) {
2020 } while (groups
[mid
].first
!= index
&& min
<= max
);
2023 while (groups
[mid
].first
> index
&& mid
> 0) {
2031 void KItemListView::updateAlternateBackgrounds()
2033 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2034 while (it
.hasNext()) {
2036 updateAlternateBackgroundForWidget(it
.value());
2040 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2042 bool enabled
= useAlternateBackgrounds();
2044 const int index
= widget
->index();
2045 enabled
= (index
& 0x1) > 0;
2047 const int groupIndex
= groupIndexForItem(index
);
2048 if (groupIndex
>= 0) {
2049 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2050 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2051 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2052 enabled
= (relativeIndex
& 0x1) > 0;
2056 widget
->setAlternateBackground(enabled
);
2059 bool KItemListView::useAlternateBackgrounds() const
2061 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2064 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2066 QElapsedTimer timer
;
2069 QHash
<QByteArray
, qreal
> widths
;
2071 // Calculate the minimum width for each column that is required
2072 // to show the headline unclipped.
2073 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2074 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2075 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2076 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2077 const QString headerText
= m_model
->roleDescription(visibleRole
);
2078 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2079 widths
.insert(visibleRole
, headerWidth
);
2082 // Calculate the preferred column withs for each item and ignore values
2083 // smaller than the width for showing the headline unclipped.
2084 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2085 int calculatedItemCount
= 0;
2086 bool maxTimeExceeded
= false;
2087 foreach (const KItemRange
& itemRange
, itemRanges
) {
2088 const int startIndex
= itemRange
.index
;
2089 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2091 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2092 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2093 qreal maxWidth
= widths
.value(visibleRole
, 0);
2094 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2095 maxWidth
= qMax(width
, maxWidth
);
2096 widths
.insert(visibleRole
, maxWidth
);
2099 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2100 // When having several thousands of items calculating the sizes can get
2101 // very expensive. We accept a possibly too small role-size in favour
2102 // of having no blocking user interface.
2103 maxTimeExceeded
= true;
2106 ++calculatedItemCount
;
2108 if (maxTimeExceeded
) {
2116 void KItemListView::applyColumnWidthsFromHeader()
2118 // Apply the new size to the layouter
2119 const qreal requiredWidth
= columnWidthsSum();
2120 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2121 m_itemSize
.height());
2122 m_layouter
->setItemSize(dynamicItemSize
);
2124 // Update the role sizes for all visible widgets
2125 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2126 while (it
.hasNext()) {
2128 updateWidgetColumnWidths(it
.value());
2132 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2134 foreach (const QByteArray
& role
, m_visibleRoles
) {
2135 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2139 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2141 Q_ASSERT(m_itemSize
.isEmpty());
2142 const int itemCount
= m_model
->count();
2143 int rangesItemCount
= 0;
2144 foreach (const KItemRange
& range
, itemRanges
) {
2145 rangesItemCount
+= range
.count
;
2148 if (itemCount
== rangesItemCount
) {
2149 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2150 foreach (const QByteArray
& role
, m_visibleRoles
) {
2151 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2154 // Only a sub range of the roles need to be determined.
2155 // The chances are good that the widths of the sub ranges
2156 // already fit into the available widths and hence no
2157 // expensive update might be required.
2158 bool changed
= false;
2160 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2161 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2162 while (it
.hasNext()) {
2164 const QByteArray
& role
= it
.key();
2165 const qreal updatedWidth
= it
.value();
2166 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2167 if (updatedWidth
> currentWidth
) {
2168 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2174 // All the updated sizes are smaller than the current sizes and no change
2175 // of the stretched roles-widths is required
2180 if (m_headerWidget
->automaticColumnResizing()) {
2181 applyAutomaticColumnWidths();
2185 void KItemListView::updatePreferredColumnWidths()
2188 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2192 void KItemListView::applyAutomaticColumnWidths()
2194 Q_ASSERT(m_itemSize
.isEmpty());
2195 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2196 if (m_visibleRoles
.isEmpty()) {
2200 // Calculate the maximum size of an item by considering the
2201 // visible role sizes and apply them to the layouter. If the
2202 // size does not use the available view-size the size of the
2203 // first role will get stretched.
2205 foreach (const QByteArray
& role
, m_visibleRoles
) {
2206 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2207 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2210 const QByteArray firstRole
= m_visibleRoles
.first();
2211 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2212 QSizeF dynamicItemSize
= m_itemSize
;
2214 qreal requiredWidth
= columnWidthsSum();
2215 const qreal availableWidth
= size().width();
2216 if (requiredWidth
< availableWidth
) {
2217 // Stretch the first column to use the whole remaining width
2218 firstColumnWidth
+= availableWidth
- requiredWidth
;
2219 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2220 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2221 // Shrink the first column to be able to show as much other
2222 // columns as possible
2223 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2225 // TODO: A proper calculation of the minimum width depends on the implementation
2226 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2228 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2229 if (shrinkedFirstColumnWidth
< minWidth
) {
2230 shrinkedFirstColumnWidth
= minWidth
;
2233 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2234 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2237 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2239 m_layouter
->setItemSize(dynamicItemSize
);
2241 // Update the role sizes for all visible widgets
2242 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2243 while (it
.hasNext()) {
2245 updateWidgetColumnWidths(it
.value());
2249 qreal
KItemListView::columnWidthsSum() const
2251 qreal widthsSum
= 0;
2252 foreach (const QByteArray
& role
, m_visibleRoles
) {
2253 widthsSum
+= m_headerWidget
->columnWidth(role
);
2258 QRectF
KItemListView::headerBoundaries() const
2260 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2263 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2264 const QSizeF
& newItemSize
,
2265 const QSizeF
& newItemMargin
) const
2267 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2271 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2272 const qreal itemWidth
= m_layouter
->itemSize().width();
2273 if (itemWidth
> 0) {
2274 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2275 newItemSize
.width(),
2276 newItemMargin
.width());
2277 if (m_model
->count() > newColumnCount
) {
2278 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2280 m_layouter
->itemMargin().width());
2281 return oldColumnCount
!= newColumnCount
;
2285 const qreal itemHeight
= m_layouter
->itemSize().height();
2286 if (itemHeight
> 0) {
2287 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2288 newItemSize
.height(),
2289 newItemMargin
.height());
2290 if (m_model
->count() > newRowCount
) {
2291 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2293 m_layouter
->itemMargin().height());
2294 return oldRowCount
!= newRowCount
;
2302 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2304 if (m_itemSize
.isEmpty()) {
2305 // We have only columns or only rows, but no grid: An animation is usually
2306 // welcome when inserting or removing items.
2307 return !supportsItemExpanding();
2310 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2314 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2315 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2316 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2317 // Only animate if up to 2/3 of a row or column are inserted or removed
2318 return changedItemCount
<= maximum
* 2 / 3;
2322 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2324 const QSizeF oldSize
= m_layouter
->size();
2326 m_layouter
->setSize(size
);
2327 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2328 m_layouter
->setSize(oldSize
);
2330 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2331 : maxOffset
> size
.width();
2334 int KItemListView::showDropIndicator(const QPointF
& pos
)
2336 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2337 while (it
.hasNext()) {
2339 const KItemListWidget
* widget
= it
.value();
2341 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2342 const QRectF rect
= itemRect(widget
->index());
2343 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2344 if (m_model
->supportsDropping(widget
->index())) {
2345 const int gap
= qMax(4, m_styleOption
.padding
);
2346 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2351 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2352 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2354 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2355 if (m_dropIndicator
!= draggingInsertIndicator
) {
2356 m_dropIndicator
= draggingInsertIndicator
;
2360 int index
= widget
->index();
2368 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2369 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2372 void KItemListView::hideDropIndicator()
2374 if (!m_dropIndicator
.isNull()) {
2375 m_dropIndicator
= QRectF();
2380 void KItemListView::updateGroupHeaderHeight()
2382 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2383 qreal groupHeaderMargin
= 0;
2385 if (scrollOrientation() == Qt::Horizontal
) {
2386 // The vertical margin above and below the header should be
2387 // equal to the horizontal margin, not the vertical margin
2388 // from m_styleOption.
2389 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2390 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2391 } else if (m_itemSize
.isEmpty()){
2392 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2393 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2395 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2396 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2398 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2399 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2401 updateVisibleGroupHeaders();
2404 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2406 if (!supportsItemExpanding() || !m_model
) {
2410 if (firstIndex
< 0 || lastIndex
< 0) {
2411 firstIndex
= m_layouter
->firstVisibleIndex();
2412 lastIndex
= m_layouter
->lastVisibleIndex();
2414 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2415 lastIndex
>= m_layouter
->firstVisibleIndex());
2416 if (!isRangeVisible
) {
2421 int previousParents
= 0;
2422 QBitArray previousSiblings
;
2424 // The rootIndex describes the first index where the siblings get
2425 // calculated from. For the calculation the upper most parent item
2426 // is required. For performance reasons it is checked first whether
2427 // the visible items before or after the current range already
2428 // contain a siblings information which can be used as base.
2429 int rootIndex
= firstIndex
;
2431 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2433 // There is no visible widget before the range, check whether there
2434 // is one after the range:
2435 widget
= m_visibleItems
.value(lastIndex
+ 1);
2437 // The sibling information of the widget may only be used if
2438 // all items of the range have the same number of parents.
2439 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2440 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2441 if (m_model
->expandedParentsCount(i
) != parents
) {
2450 // Performance optimization: Use the sibling information of the visible
2451 // widget beside the given range.
2452 previousSiblings
= widget
->siblingsInformation();
2453 if (previousSiblings
.isEmpty()) {
2456 previousParents
= previousSiblings
.count() - 1;
2457 previousSiblings
.truncate(previousParents
);
2459 // Potentially slow path: Go back to the upper most parent of firstIndex
2460 // to be able to calculate the initial value for the siblings.
2461 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2466 Q_ASSERT(previousParents
>= 0);
2467 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2468 // Update the parent-siblings in case if the current item represents
2469 // a child or an upper parent.
2470 const int currentParents
= m_model
->expandedParentsCount(i
);
2471 Q_ASSERT(currentParents
>= 0);
2472 if (previousParents
< currentParents
) {
2473 previousParents
= currentParents
;
2474 previousSiblings
.resize(currentParents
);
2475 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2476 } else if (previousParents
> currentParents
) {
2477 previousParents
= currentParents
;
2478 previousSiblings
.truncate(currentParents
);
2481 if (i
>= firstIndex
) {
2482 // The index represents a visible item. Apply the parent-siblings
2483 // and update the sibling of the current item.
2484 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2489 QBitArray siblings
= previousSiblings
;
2490 siblings
.resize(siblings
.count() + 1);
2491 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2493 widget
->setSiblingsInformation(siblings
);
2498 bool KItemListView::hasSiblingSuccessor(int index
) const
2500 bool hasSuccessor
= false;
2501 const int parentsCount
= m_model
->expandedParentsCount(index
);
2502 int successorIndex
= index
+ 1;
2504 // Search the next sibling
2505 const int itemCount
= m_model
->count();
2506 while (successorIndex
< itemCount
) {
2507 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2508 if (currentParentsCount
== parentsCount
) {
2509 hasSuccessor
= true;
2511 } else if (currentParentsCount
< parentsCount
) {
2517 if (m_grouped
&& hasSuccessor
) {
2518 // If the sibling is part of another group, don't mark it as
2519 // successor as the group header is between the sibling connections.
2520 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2521 if (m_layouter
->isFirstGroupItem(i
)) {
2522 hasSuccessor
= false;
2528 return hasSuccessor
;
2531 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2535 const int minSpeed
= 4;
2536 const int maxSpeed
= 128;
2537 const int speedLimiter
= 96;
2538 const int autoScrollBorder
= 64;
2540 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2541 // This assures that the autoscrolling speed grows gradually.
2542 const int incLimiter
= 1;
2544 if (pos
< autoScrollBorder
) {
2545 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2546 inc
= qMax(inc
, -maxSpeed
);
2547 inc
= qMax(inc
, oldInc
- incLimiter
);
2548 } else if (pos
> range
- autoScrollBorder
) {
2549 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2550 inc
= qMin(inc
, maxSpeed
);
2551 inc
= qMin(inc
, oldInc
+ incLimiter
);
2557 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2559 const qreal availableSize
= size
- itemMargin
;
2560 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2566 KItemListCreatorBase::~KItemListCreatorBase()
2568 qDeleteAll(m_recycleableWidgets
);
2569 qDeleteAll(m_createdWidgets
);
2572 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2574 m_createdWidgets
.insert(widget
);
2577 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2579 Q_ASSERT(m_createdWidgets
.contains(widget
));
2580 m_createdWidgets
.remove(widget
);
2582 if (m_recycleableWidgets
.count() < 100) {
2583 m_recycleableWidgets
.append(widget
);
2584 widget
->setVisible(false);
2590 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2592 if (m_recycleableWidgets
.isEmpty()) {
2596 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2597 m_createdWidgets
.insert(widget
);
2601 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2605 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2607 widget
->setParentItem(0);
2608 widget
->setOpacity(1.0);
2609 pushRecycleableWidget(widget
);
2612 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2616 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2618 header
->setOpacity(1.0);
2619 pushRecycleableWidget(header
);
2622 #include "kitemlistview.moc"