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 QAccessibleInterface
* accessibleViewFactory(const QString
&key
, QObject
*object
)
60 if (KItemListView
*view
= qobject_cast
<KItemListView
*>(object
))
61 return new KItemListViewAccessible(view
);
65 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
66 QGraphicsWidget(parent
),
67 m_enabledSelectionToggles(false),
69 m_supportsItemExpanding(false),
71 m_activeTransactions(0),
72 m_endTransactionAnimationHint(Animation
),
78 m_groupHeaderCreator(0),
83 m_sizeHintResolver(0),
88 m_oldMaximumScrollOffset(0),
90 m_oldMaximumItemOffset(0),
91 m_skipAutoScrollForRubberBand(false),
94 m_autoScrollIncrement(0),
100 setAcceptHoverEvents(true);
102 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
104 m_layouter
= new KItemListViewLayouter(this);
105 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
107 m_animation
= new KItemListViewAnimation(this);
108 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
109 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
111 m_layoutTimer
= new QTimer(this);
112 m_layoutTimer
->setInterval(300);
113 m_layoutTimer
->setSingleShot(true);
114 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
116 m_rubberBand
= new KItemListRubberBand(this);
117 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
119 m_headerWidget
= new KItemListHeaderWidget(this);
120 m_headerWidget
->setVisible(false);
122 m_header
= new KItemListHeader(this);
124 QAccessible::installFactory(accessibleViewFactory
);
127 KItemListView::~KItemListView()
129 // The group headers are children of the widgets created by
130 // widgetCreator(). So it is mandatory to delete the group headers
132 delete m_groupHeaderCreator
;
133 m_groupHeaderCreator
= 0;
135 delete m_widgetCreator
;
138 delete m_sizeHintResolver
;
139 m_sizeHintResolver
= 0;
141 QAccessible::removeFactory(accessibleViewFactory
);
144 void KItemListView::setScrollOffset(qreal offset
)
150 const qreal previousOffset
= m_layouter
->scrollOffset();
151 if (offset
== previousOffset
) {
155 m_layouter
->setScrollOffset(offset
);
156 m_animation
->setScrollOffset(offset
);
158 // Don't check whether the m_layoutTimer is active: Changing the
159 // scroll offset must always trigger a synchronous layout, otherwise
160 // the smooth-scrolling might get jerky.
161 doLayout(NoAnimation
);
162 onScrollOffsetChanged(offset
, previousOffset
);
165 qreal
KItemListView::scrollOffset() const
167 return m_layouter
->scrollOffset();
170 qreal
KItemListView::maximumScrollOffset() const
172 return m_layouter
->maximumScrollOffset();
175 void KItemListView::setItemOffset(qreal offset
)
177 if (m_layouter
->itemOffset() == offset
) {
181 m_layouter
->setItemOffset(offset
);
182 if (m_headerWidget
->isVisible()) {
183 m_headerWidget
->setOffset(offset
);
186 // Don't check whether the m_layoutTimer is active: Changing the
187 // item offset must always trigger a synchronous layout, otherwise
188 // the smooth-scrolling might get jerky.
189 doLayout(NoAnimation
);
192 qreal
KItemListView::itemOffset() const
194 return m_layouter
->itemOffset();
197 qreal
KItemListView::maximumItemOffset() const
199 return m_layouter
->maximumItemOffset();
202 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
204 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
205 m_visibleRoles
= roles
;
206 onVisibleRolesChanged(roles
, previousRoles
);
208 m_sizeHintResolver
->clearCache();
209 m_layouter
->markAsDirty();
211 if (m_itemSize
.isEmpty()) {
212 m_headerWidget
->setColumns(roles
);
213 updatePreferredColumnWidths();
214 if (!m_headerWidget
->automaticColumnResizing()) {
215 // The column-width of new roles are still 0. Apply the preferred
216 // column-width as default with.
217 foreach (const QByteArray
& role
, m_visibleRoles
) {
218 if (m_headerWidget
->columnWidth(role
) == 0) {
219 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
220 m_headerWidget
->setColumnWidth(role
, width
);
224 applyColumnWidthsFromHeader();
228 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
229 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
230 (roles
.count() <= 1 && previousRoles
.count() > 1));
232 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
233 while (it
.hasNext()) {
235 KItemListWidget
* widget
= it
.value();
236 widget
->setVisibleRoles(roles
);
237 if (alternateBackgroundsChanged
) {
238 updateAlternateBackgroundForWidget(widget
);
242 doLayout(NoAnimation
);
245 QList
<QByteArray
> KItemListView::visibleRoles() const
247 return m_visibleRoles
;
250 void KItemListView::setAutoScroll(bool enabled
)
252 if (enabled
&& !m_autoScrollTimer
) {
253 m_autoScrollTimer
= new QTimer(this);
254 m_autoScrollTimer
->setSingleShot(true);
255 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
256 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
257 } else if (!enabled
&& m_autoScrollTimer
) {
258 delete m_autoScrollTimer
;
259 m_autoScrollTimer
= 0;
263 bool KItemListView::autoScroll() const
265 return m_autoScrollTimer
!= 0;
268 void KItemListView::setEnabledSelectionToggles(bool enabled
)
270 if (m_enabledSelectionToggles
!= enabled
) {
271 m_enabledSelectionToggles
= enabled
;
273 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
274 while (it
.hasNext()) {
276 it
.value()->setEnabledSelectionToggle(enabled
);
281 bool KItemListView::enabledSelectionToggles() const
283 return m_enabledSelectionToggles
;
286 KItemListController
* KItemListView::controller() const
291 KItemModelBase
* KItemListView::model() const
296 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
298 if (m_widgetCreator
) {
299 delete m_widgetCreator
;
301 m_widgetCreator
= widgetCreator
;
304 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
306 if (!m_widgetCreator
) {
307 m_widgetCreator
= defaultWidgetCreator();
309 return m_widgetCreator
;
312 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
314 if (m_groupHeaderCreator
) {
315 delete m_groupHeaderCreator
;
317 m_groupHeaderCreator
= groupHeaderCreator
;
320 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
322 if (!m_groupHeaderCreator
) {
323 m_groupHeaderCreator
= defaultGroupHeaderCreator();
325 return m_groupHeaderCreator
;
328 QSizeF
KItemListView::itemSize() const
333 const KItemListStyleOption
& KItemListView::styleOption() const
335 return m_styleOption
;
338 void KItemListView::setGeometry(const QRectF
& rect
)
340 QGraphicsWidget::setGeometry(rect
);
346 const QSizeF newSize
= rect
.size();
347 if (m_itemSize
.isEmpty()) {
348 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
349 if (m_headerWidget
->automaticColumnResizing()) {
350 applyAutomaticColumnWidths();
352 const qreal requiredWidth
= columnWidthsSum();
353 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
354 m_itemSize
.height());
355 m_layouter
->setItemSize(dynamicItemSize
);
358 // Triggering a synchronous layout is fine from a performance point of view,
359 // as with dynamic item sizes no moving animation must be done.
360 m_layouter
->setSize(newSize
);
361 doLayout(NoAnimation
);
363 const bool animate
= !changesItemGridLayout(newSize
,
364 m_layouter
->itemSize(),
365 m_layouter
->itemMargin());
366 m_layouter
->setSize(newSize
);
369 // Trigger an asynchronous relayout with m_layoutTimer to prevent
370 // performance bottlenecks. If the timer is exceeded, an animated layout
371 // will be triggered.
372 if (!m_layoutTimer
->isActive()) {
373 m_layoutTimer
->start();
376 m_layoutTimer
->stop();
377 doLayout(NoAnimation
);
382 int KItemListView::itemAt(const QPointF
& pos
) const
384 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
385 while (it
.hasNext()) {
388 const KItemListWidget
* widget
= it
.value();
389 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
390 if (widget
->contains(mappedPos
)) {
398 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
400 if (!m_enabledSelectionToggles
) {
404 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
406 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
407 if (!selectionToggleRect
.isEmpty()) {
408 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
409 return selectionToggleRect
.contains(mappedPos
);
415 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
417 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
419 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
420 if (!expansionToggleRect
.isEmpty()) {
421 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
422 return expansionToggleRect
.contains(mappedPos
);
428 int KItemListView::firstVisibleIndex() const
430 return m_layouter
->firstVisibleIndex();
433 int KItemListView::lastVisibleIndex() const
435 return m_layouter
->lastVisibleIndex();
438 QSizeF
KItemListView::itemSizeHint(int index
) const
440 return widgetCreator()->itemSizeHint(index
, this);
443 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
445 if (m_supportsItemExpanding
!= supportsExpanding
) {
446 m_supportsItemExpanding
= supportsExpanding
;
447 updateSiblingsInformation();
448 onSupportsItemExpandingChanged(supportsExpanding
);
452 bool KItemListView::supportsItemExpanding() const
454 return m_supportsItemExpanding
;
457 QRectF
KItemListView::itemRect(int index
) const
459 return m_layouter
->itemRect(index
);
462 QRectF
KItemListView::itemContextRect(int index
) const
466 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
468 contextRect
= widget
->iconRect() | widget
->textRect();
469 contextRect
.translate(itemRect(index
).topLeft());
475 void KItemListView::scrollToItem(int index
)
477 QRectF viewGeometry
= geometry();
478 if (m_headerWidget
->isVisible()) {
479 const qreal headerHeight
= m_headerWidget
->size().height();
480 viewGeometry
.adjust(0, headerHeight
, 0, 0);
482 const QRectF currentRect
= itemRect(index
);
484 if (!viewGeometry
.contains(currentRect
)) {
485 qreal newOffset
= scrollOffset();
486 if (scrollOrientation() == Qt::Vertical
) {
487 if (currentRect
.top() < viewGeometry
.top()) {
488 newOffset
+= currentRect
.top() - viewGeometry
.top();
489 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
490 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
493 if (currentRect
.left() < viewGeometry
.left()) {
494 newOffset
+= currentRect
.left() - viewGeometry
.left();
495 } else if (currentRect
.right() > viewGeometry
.right()) {
496 newOffset
+= currentRect
.right() - viewGeometry
.right();
500 if (newOffset
!= scrollOffset()) {
501 emit
scrollTo(newOffset
);
506 void KItemListView::beginTransaction()
508 ++m_activeTransactions
;
509 if (m_activeTransactions
== 1) {
510 onTransactionBegin();
514 void KItemListView::endTransaction()
516 --m_activeTransactions
;
517 if (m_activeTransactions
< 0) {
518 m_activeTransactions
= 0;
519 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
522 if (m_activeTransactions
== 0) {
524 doLayout(m_endTransactionAnimationHint
);
525 m_endTransactionAnimationHint
= Animation
;
529 bool KItemListView::isTransactionActive() const
531 return m_activeTransactions
> 0;
534 void KItemListView::setHeaderVisible(bool visible
)
536 if (visible
&& !m_headerWidget
->isVisible()) {
537 QStyleOptionHeader option
;
538 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
541 m_headerWidget
->setPos(0, 0);
542 m_headerWidget
->resize(size().width(), headerSize
.height());
543 m_headerWidget
->setModel(m_model
);
544 m_headerWidget
->setColumns(m_visibleRoles
);
545 m_headerWidget
->setZValue(1);
547 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
548 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
549 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
550 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
551 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
552 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
553 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
554 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
556 m_layouter
->setHeaderHeight(headerSize
.height());
557 m_headerWidget
->setVisible(true);
558 } else if (!visible
&& m_headerWidget
->isVisible()) {
559 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
560 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
561 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
562 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
563 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
564 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
565 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
566 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
568 m_layouter
->setHeaderHeight(0);
569 m_headerWidget
->setVisible(false);
573 bool KItemListView::isHeaderVisible() const
575 return m_headerWidget
->isVisible();
578 KItemListHeader
* KItemListView::header() const
583 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
587 if (indexes
.count() == 1) {
588 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
589 QGraphicsView
* graphicsView
= scene()->views()[0];
590 if (item
&& graphicsView
) {
591 pixmap
= item
->createDragPixmap(0, graphicsView
);
594 // TODO: Not implemented yet. Probably extend the interface
595 // from KItemListWidget::createDragPixmap() to return a pixmap
596 // that can be used for multiple indexes.
602 void KItemListView::editRole(int index
, const QByteArray
& role
)
604 KItemListWidget
* widget
= m_visibleItems
.value(index
);
605 if (!widget
|| m_editingRole
) {
609 m_editingRole
= true;
610 widget
->setEditedRole(role
);
612 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
613 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
614 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
615 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
618 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
620 QGraphicsWidget::paint(painter
, option
, widget
);
622 if (m_rubberBand
->isActive()) {
623 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
624 m_rubberBand
->endPosition()).normalized();
626 const QPointF topLeft
= rubberBandRect
.topLeft();
627 if (scrollOrientation() == Qt::Vertical
) {
628 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
630 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
633 QStyleOptionRubberBand opt
;
634 opt
.initFrom(widget
);
635 opt
.shape
= QRubberBand::Rectangle
;
637 opt
.rect
= rubberBandRect
.toRect();
638 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
641 if (!m_dropIndicator
.isEmpty()) {
642 const QRectF r
= m_dropIndicator
.toRect();
644 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
645 painter
->setPen(color
);
647 // TODO: The following implementation works only for a vertical scroll-orientation
648 // and assumes a height of the m_draggingInsertIndicator of 1.
649 Q_ASSERT(r
.height() == 1);
650 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
653 painter
->setPen(color
);
654 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
658 void KItemListView::setItemSize(const QSizeF
& size
)
660 const QSizeF previousSize
= m_itemSize
;
661 if (size
== previousSize
) {
665 // Skip animations when the number of rows or columns
666 // are changed in the grid layout. Although the animation
667 // engine can handle this usecase, it looks obtrusive.
668 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
670 m_layouter
->itemMargin());
672 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
673 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
674 (!m_itemSize
.isEmpty() && size
.isEmpty()));
678 if (alternateBackgroundsChanged
) {
679 // For an empty item size alternate backgrounds are drawn if more than
680 // one role is shown. Assure that the backgrounds for visible items are
681 // updated when changing the size in this context.
682 updateAlternateBackgrounds();
685 if (size
.isEmpty()) {
686 if (m_headerWidget
->automaticColumnResizing()) {
687 updatePreferredColumnWidths();
689 // Only apply the changed height and respect the header widths
691 const qreal currentWidth
= m_layouter
->itemSize().width();
692 const QSizeF
newSize(currentWidth
, size
.height());
693 m_layouter
->setItemSize(newSize
);
696 m_layouter
->setItemSize(size
);
699 m_sizeHintResolver
->clearCache();
700 doLayout(animate
? Animation
: NoAnimation
);
701 onItemSizeChanged(size
, previousSize
);
704 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
706 const KItemListStyleOption previousOption
= m_styleOption
;
707 m_styleOption
= option
;
710 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
711 if (margin
!= m_layouter
->itemMargin()) {
712 // Skip animations when the number of rows or columns
713 // are changed in the grid layout. Although the animation
714 // engine can handle this usecase, it looks obtrusive.
715 animate
= !changesItemGridLayout(m_layouter
->size(),
716 m_layouter
->itemSize(),
718 m_layouter
->setItemMargin(margin
);
722 updateGroupHeaderHeight();
725 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
726 // Animating a change of the maximum text size just results in expensive
727 // temporary eliding and clipping operations and does not look good visually.
731 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
732 while (it
.hasNext()) {
734 it
.value()->setStyleOption(option
);
737 m_sizeHintResolver
->clearCache();
738 m_layouter
->markAsDirty();
739 doLayout(animate
? Animation
: NoAnimation
);
741 if (m_itemSize
.isEmpty()) {
742 updatePreferredColumnWidths();
745 onStyleOptionChanged(option
, previousOption
);
748 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
750 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
751 if (orientation
== previousOrientation
) {
755 m_layouter
->setScrollOrientation(orientation
);
756 m_animation
->setScrollOrientation(orientation
);
757 m_sizeHintResolver
->clearCache();
760 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
761 while (it
.hasNext()) {
763 it
.value()->setScrollOrientation(orientation
);
765 updateGroupHeaderHeight();
769 doLayout(NoAnimation
);
771 onScrollOrientationChanged(orientation
, previousOrientation
);
772 emit
scrollOrientationChanged(orientation
, previousOrientation
);
775 Qt::Orientation
KItemListView::scrollOrientation() const
777 return m_layouter
->scrollOrientation();
780 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
785 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
790 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
795 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
797 Q_UNUSED(changedRoles
);
801 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
807 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
813 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
819 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
825 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
831 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
837 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
843 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
845 Q_UNUSED(supportsExpanding
);
848 void KItemListView::onTransactionBegin()
852 void KItemListView::onTransactionEnd()
856 bool KItemListView::event(QEvent
* event
)
858 // Forward all events to the controller and handle them there
859 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
863 return QGraphicsWidget::event(event
);
866 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
868 m_mousePos
= transform().map(event
->pos());
872 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
874 QGraphicsWidget::mouseMoveEvent(event
);
876 m_mousePos
= transform().map(event
->pos());
877 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
878 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
882 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
884 event
->setAccepted(true);
888 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
890 QGraphicsWidget::dragMoveEvent(event
);
892 m_mousePos
= transform().map(event
->pos());
893 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
894 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
898 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
900 QGraphicsWidget::dragLeaveEvent(event
);
901 setAutoScroll(false);
904 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
906 QGraphicsWidget::dropEvent(event
);
907 setAutoScroll(false);
910 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
912 return m_visibleItems
.values();
915 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
917 if (m_itemSize
.isEmpty()) {
918 updatePreferredColumnWidths(itemRanges
);
921 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
922 if (hasMultipleRanges
) {
926 m_layouter
->markAsDirty();
928 int previouslyInsertedCount
= 0;
929 foreach (const KItemRange
& range
, itemRanges
) {
930 // range.index is related to the model before anything has been inserted.
931 // As in each loop the current item-range gets inserted the index must
932 // be increased by the already previously inserted items.
933 const int index
= range
.index
+ previouslyInsertedCount
;
934 const int count
= range
.count
;
935 if (index
< 0 || count
<= 0) {
936 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
939 previouslyInsertedCount
+= count
;
941 m_sizeHintResolver
->itemsInserted(index
, count
);
943 // Determine which visible items must be moved
944 QList
<int> itemsToMove
;
945 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
946 while (it
.hasNext()) {
948 const int visibleItemIndex
= it
.key();
949 if (visibleItemIndex
>= index
) {
950 itemsToMove
.append(visibleItemIndex
);
954 // Update the indexes of all KItemListWidget instances that are located
955 // after the inserted items. It is important to adjust the indexes in the order
956 // from the highest index to the lowest index to prevent overlaps when setting the new index.
958 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
959 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
961 const int newIndex
= widget
->index() + count
;
962 if (hasMultipleRanges
) {
963 setWidgetIndex(widget
, newIndex
);
965 // Try to animate the moving of the item
966 moveWidgetToIndex(widget
, newIndex
);
970 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
971 // Check whether a scrollbar is required to show the inserted items. In this case
972 // the size of the layouter will be decreased before calling doLayout(): This prevents
973 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
974 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
975 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
976 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
977 if (decreaseLayouterSize
) {
978 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
979 QSizeF layouterSize
= m_layouter
->size();
980 if (verticalScrollOrientation
) {
981 layouterSize
.rwidth() -= scrollBarExtent
;
983 layouterSize
.rheight() -= scrollBarExtent
;
985 m_layouter
->setSize(layouterSize
);
989 if (!hasMultipleRanges
) {
990 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
991 updateSiblingsInformation();
996 m_controller
->selectionManager()->itemsInserted(itemRanges
);
999 if (hasMultipleRanges
) {
1001 // Important: Don't read any m_layouter-property inside the for-loop in case if
1002 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1003 // updated in each loop-cycle and has only a consistent state after the loop.
1004 Q_ASSERT(m_layouter
->isDirty());
1006 m_endTransactionAnimationHint
= NoAnimation
;
1009 updateSiblingsInformation();
1012 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1013 // In case if items of the same group have been inserted before an item that
1014 // currently represents the first item of the group, the group header of
1015 // this item must be removed.
1016 updateVisibleGroupHeaders();
1019 if (useAlternateBackgrounds()) {
1020 updateAlternateBackgrounds();
1024 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1026 if (m_itemSize
.isEmpty()) {
1027 // Don't pass the item-range: The preferred column-widths of
1028 // all items must be adjusted when removing items.
1029 updatePreferredColumnWidths();
1032 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1033 if (hasMultipleRanges
) {
1037 m_layouter
->markAsDirty();
1039 int removedItemsCount
= 0;
1040 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1041 removedItemsCount
+= itemRanges
[i
].count
;
1044 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1045 const KItemRange
& range
= itemRanges
[i
];
1046 const int index
= range
.index
;
1047 const int count
= range
.count
;
1048 if (index
< 0 || count
<= 0) {
1049 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1053 m_sizeHintResolver
->itemsRemoved(index
, count
);
1055 const int firstRemovedIndex
= index
;
1056 const int lastRemovedIndex
= index
+ count
- 1;
1057 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1058 removedItemsCount
-= count
;
1060 // Remove all KItemListWidget instances that got deleted
1061 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1062 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1067 m_animation
->stop(widget
);
1068 // Stopping the animation might lead to recycling the widget if
1069 // it is invisible (see slotAnimationFinished()).
1070 // Check again whether it is still visible:
1071 if (!m_visibleItems
.contains(i
)) {
1075 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1076 // Remove the widget without animation
1077 recycleWidget(widget
);
1079 // Animate the removing of the items. Special case: When removing an item there
1080 // is no valid model index available anymore. For the
1081 // remove-animation the item gets removed from m_visibleItems but the widget
1082 // will stay alive until the animation has been finished and will
1083 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1084 m_visibleItems
.remove(i
);
1085 widget
->setIndex(-1);
1086 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1090 // Update the indexes of all KItemListWidget instances that are located
1091 // after the deleted items
1092 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1093 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1095 const int newIndex
= i
- count
;
1096 if (hasMultipleRanges
) {
1097 setWidgetIndex(widget
, newIndex
);
1099 // Try to animate the moving of the item
1100 moveWidgetToIndex(widget
, newIndex
);
1105 if (!hasMultipleRanges
) {
1106 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1107 // assumes an updated geometry. If items are removed during an active transaction,
1108 // the transaction will be temporary deactivated so that doLayout() triggers a
1109 // geometry update if necessary.
1110 const int activeTransactions
= m_activeTransactions
;
1111 m_activeTransactions
= 0;
1112 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1113 m_activeTransactions
= activeTransactions
;
1114 updateSiblingsInformation();
1119 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1122 if (hasMultipleRanges
) {
1124 // Important: Don't read any m_layouter-property inside the for-loop in case if
1125 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1126 // updated in each loop-cycle and has only a consistent state after the loop.
1127 Q_ASSERT(m_layouter
->isDirty());
1129 m_endTransactionAnimationHint
= NoAnimation
;
1131 updateSiblingsInformation();
1134 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1135 // In case if the first item of a group has been removed, the group header
1136 // must be applied to the next visible item.
1137 updateVisibleGroupHeaders();
1140 if (useAlternateBackgrounds()) {
1141 updateAlternateBackgrounds();
1145 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1147 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1148 m_layouter
->markAsDirty();
1151 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1154 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1155 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1157 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1158 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1160 updateWidgetProperties(widget
, index
);
1161 initializeItemListWidget(widget
);
1165 doLayout(NoAnimation
);
1166 updateSiblingsInformation();
1169 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1170 const QSet
<QByteArray
>& roles
)
1172 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1173 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1174 updatePreferredColumnWidths(itemRanges
);
1177 foreach (const KItemRange
& itemRange
, itemRanges
) {
1178 const int index
= itemRange
.index
;
1179 const int count
= itemRange
.count
;
1181 if (updateSizeHints
) {
1182 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1183 m_layouter
->markAsDirty();
1185 if (!m_layoutTimer
->isActive()) {
1186 m_layoutTimer
->start();
1190 // Apply the changed roles to the visible item-widgets
1191 const int lastIndex
= index
+ count
- 1;
1192 for (int i
= index
; i
<= lastIndex
; ++i
) {
1193 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1195 widget
->setData(m_model
->data(i
), roles
);
1199 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1200 // The sort-role has been changed which might result
1201 // in modified group headers
1202 updateVisibleGroupHeaders();
1203 doLayout(NoAnimation
);
1208 void KItemListView::slotGroupedSortingChanged(bool current
)
1210 m_grouped
= current
;
1211 m_layouter
->markAsDirty();
1214 updateGroupHeaderHeight();
1216 // Clear all visible headers
1217 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1218 while (it
.hasNext()) {
1220 recycleGroupHeaderForWidget(it
.key());
1222 Q_ASSERT(m_visibleGroups
.isEmpty());
1225 if (useAlternateBackgrounds()) {
1226 // Changing the group mode requires to update the alternate backgrounds
1227 // as with the enabled group mode the altering is done on base of the first
1229 updateAlternateBackgrounds();
1231 updateSiblingsInformation();
1232 doLayout(NoAnimation
);
1235 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1240 updateVisibleGroupHeaders();
1241 doLayout(NoAnimation
);
1245 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1250 updateVisibleGroupHeaders();
1251 doLayout(NoAnimation
);
1255 void KItemListView::slotCurrentChanged(int current
, int previous
)
1259 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1260 if (previousWidget
) {
1261 previousWidget
->setCurrent(false);
1264 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1265 if (currentWidget
) {
1266 currentWidget
->setCurrent(true);
1270 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1274 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1275 while (it
.hasNext()) {
1277 const int index
= it
.key();
1278 KItemListWidget
* widget
= it
.value();
1279 widget
->setSelected(current
.contains(index
));
1283 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1284 KItemListViewAnimation::AnimationType type
)
1286 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1287 Q_ASSERT(itemListWidget
);
1290 case KItemListViewAnimation::DeleteAnimation
: {
1291 // As we recycle the widget in this case it is important to assure that no
1292 // other animation has been started. This is a convention in KItemListView and
1293 // not a requirement defined by KItemListViewAnimation.
1294 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1296 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1297 // by m_visibleWidgets and must be deleted manually after the animation has
1299 recycleGroupHeaderForWidget(itemListWidget
);
1300 widgetCreator()->recycle(itemListWidget
);
1304 case KItemListViewAnimation::CreateAnimation
:
1305 case KItemListViewAnimation::MovingAnimation
:
1306 case KItemListViewAnimation::ResizeAnimation
: {
1307 const int index
= itemListWidget
->index();
1308 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1309 (index
> m_layouter
->lastVisibleIndex());
1310 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1311 recycleWidget(itemListWidget
);
1320 void KItemListView::slotLayoutTimerFinished()
1322 m_layouter
->setSize(geometry().size());
1323 doLayout(Animation
);
1326 void KItemListView::slotRubberBandPosChanged()
1331 void KItemListView::slotRubberBandActivationChanged(bool active
)
1334 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1335 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1336 m_skipAutoScrollForRubberBand
= true;
1338 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1339 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1340 m_skipAutoScrollForRubberBand
= false;
1346 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1348 qreal previousWidth
)
1351 Q_UNUSED(currentWidth
);
1352 Q_UNUSED(previousWidth
);
1354 m_headerWidget
->setAutomaticColumnResizing(false);
1355 applyColumnWidthsFromHeader();
1356 doLayout(NoAnimation
);
1359 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1363 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1365 const QList
<QByteArray
> previous
= m_visibleRoles
;
1367 QList
<QByteArray
> current
= m_visibleRoles
;
1368 current
.removeAt(previousIndex
);
1369 current
.insert(currentIndex
, role
);
1371 setVisibleRoles(current
);
1373 emit
visibleRolesChanged(current
, previous
);
1376 void KItemListView::triggerAutoScrolling()
1378 if (!m_autoScrollTimer
) {
1383 int visibleSize
= 0;
1384 if (scrollOrientation() == Qt::Vertical
) {
1385 pos
= m_mousePos
.y();
1386 visibleSize
= size().height();
1388 pos
= m_mousePos
.x();
1389 visibleSize
= size().width();
1392 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1393 m_autoScrollIncrement
= 0;
1396 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1397 if (m_autoScrollIncrement
== 0) {
1398 // The mouse position is not above an autoscroll margin (the autoscroll timer
1399 // will be restarted in mouseMoveEvent())
1400 m_autoScrollTimer
->stop();
1404 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1405 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1406 // if the direction of the rubberband is similar to the autoscroll direction. This
1407 // prevents that starting to create a rubberband within the autoscroll margins starts
1408 // an autoscrolling.
1410 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1411 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1412 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1413 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1414 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1415 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1416 // been moved up although the autoscroll direction might be down)
1417 m_autoScrollTimer
->stop();
1422 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1423 // the autoscrolling may not get skipped anymore until a new rubberband is created
1424 m_skipAutoScrollForRubberBand
= false;
1426 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1427 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1428 setScrollOffset(newScrollOffset
);
1430 // Trigger the autoscroll timer which will periodically call
1431 // triggerAutoScrolling()
1432 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1435 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1437 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1439 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1440 Q_ASSERT(groupHeader
);
1441 updateGroupHeaderLayout(widget
);
1444 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1446 emit
roleEditingCanceled(index
, role
, value
);
1447 m_editingRole
= false;
1450 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1452 emit
roleEditingFinished(index
, role
, value
);
1453 m_editingRole
= false;
1456 void KItemListView::setController(KItemListController
* controller
)
1458 if (m_controller
!= controller
) {
1459 KItemListController
* previous
= m_controller
;
1461 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1462 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1463 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1466 m_controller
= controller
;
1469 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1470 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1471 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1474 onControllerChanged(controller
, previous
);
1478 void KItemListView::setModel(KItemModelBase
* model
)
1480 if (m_model
== model
) {
1484 KItemModelBase
* previous
= m_model
;
1487 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1488 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1489 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1490 this, SLOT(slotItemsInserted(KItemRangeList
)));
1491 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1492 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1493 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1494 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1495 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1496 this, SLOT(slotGroupedSortingChanged(bool)));
1497 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1498 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1499 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1500 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1503 m_sizeHintResolver
->clearCache();
1506 m_layouter
->setModel(model
);
1507 m_grouped
= model
->groupedSorting();
1510 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1511 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1512 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1513 this, SLOT(slotItemsInserted(KItemRangeList
)));
1514 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1515 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1516 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1517 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1518 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1519 this, SLOT(slotGroupedSortingChanged(bool)));
1520 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1521 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1522 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1523 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1525 const int itemCount
= m_model
->count();
1526 if (itemCount
> 0) {
1527 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1528 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1532 onModelChanged(model
, previous
);
1535 KItemListRubberBand
* KItemListView::rubberBand() const
1537 return m_rubberBand
;
1540 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1542 if (m_layoutTimer
->isActive()) {
1543 m_layoutTimer
->stop();
1546 if (m_activeTransactions
> 0) {
1547 if (hint
== NoAnimation
) {
1548 // As soon as at least one property change should be done without animation,
1549 // the whole transaction will be marked as not animated.
1550 m_endTransactionAnimationHint
= NoAnimation
;
1555 if (!m_model
|| m_model
->count() < 0) {
1559 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1560 if (firstVisibleIndex
< 0) {
1561 emitOffsetChanges();
1565 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1566 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1567 // is still shown if the maximum offset got decreased.
1568 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1569 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1570 if (scrollOffset() > maxOffsetToShowFullRange
) {
1571 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1572 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1575 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1577 int firstSibblingIndex
= -1;
1578 int lastSibblingIndex
= -1;
1579 const bool supportsExpanding
= supportsItemExpanding();
1581 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1583 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1584 // instances from invisible items are reused. If no reusable items are
1585 // found then new KItemListWidget instances get created.
1586 const bool animate
= (hint
== Animation
);
1587 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1588 bool applyNewPos
= true;
1589 bool wasHidden
= false;
1591 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1592 const QPointF newPos
= itemBounds
.topLeft();
1593 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1596 if (!reusableItems
.isEmpty()) {
1597 // Reuse a KItemListWidget instance from an invisible item
1598 const int oldIndex
= reusableItems
.takeLast();
1599 widget
= m_visibleItems
.value(oldIndex
);
1600 setWidgetIndex(widget
, i
);
1601 updateWidgetProperties(widget
, i
);
1602 initializeItemListWidget(widget
);
1604 // No reusable KItemListWidget instance is available, create a new one
1605 widget
= createWidget(i
);
1607 widget
->resize(itemBounds
.size());
1609 if (animate
&& changedCount
< 0) {
1610 // Items have been deleted, move the created item to the
1611 // imaginary old position. They will get animated to the new position
1613 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1614 if (itemRect
.isEmpty()) {
1615 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1616 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1617 widget
->setPos(invisibleOldPos
);
1619 widget
->setPos(itemRect
.topLeft());
1621 applyNewPos
= false;
1624 if (supportsExpanding
&& changedCount
== 0) {
1625 if (firstSibblingIndex
< 0) {
1626 firstSibblingIndex
= i
;
1628 lastSibblingIndex
= i
;
1633 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1634 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1635 applyNewPos
= false;
1638 const bool itemsRemoved
= (changedCount
< 0);
1639 const bool itemsInserted
= (changedCount
> 0);
1640 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1641 // The item is located after the removed items. Animate the moving of the position.
1642 applyNewPos
= !moveWidget(widget
, newPos
);
1643 } else if (itemsInserted
&& i
>= changedIndex
) {
1644 // The item is located after the first inserted item
1645 if (i
<= changedIndex
+ changedCount
- 1) {
1646 // The item is an inserted item. Animate the appearing of the item.
1647 // For performance reasons no animation is done when changedCount is equal
1648 // to all available items.
1649 if (changedCount
< m_model
->count()) {
1650 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1652 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1653 // The item was already there before, so animate the moving of the position.
1654 // No moving animation is done if the item is animated by a create animation: This
1655 // prevents a "move animation mess" when inserting several ranges in parallel.
1656 applyNewPos
= !moveWidget(widget
, newPos
);
1658 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1659 // The size of the view might have been changed. Animate the moving of the position.
1660 applyNewPos
= !moveWidget(widget
, newPos
);
1663 m_animation
->stop(widget
);
1667 widget
->setPos(newPos
);
1670 Q_ASSERT(widget
->index() == i
);
1671 widget
->setVisible(true);
1673 if (widget
->size() != itemBounds
.size()) {
1674 // Resize the widget for the item to the changed size.
1676 // If a dynamic item size is used then no animation is done in the direction
1677 // of the dynamic size.
1678 if (m_itemSize
.width() <= 0) {
1679 // The width is dynamic, apply the new width without animation.
1680 widget
->resize(itemBounds
.width(), widget
->size().height());
1681 } else if (m_itemSize
.height() <= 0) {
1682 // The height is dynamic, apply the new height without animation.
1683 widget
->resize(widget
->size().width(), itemBounds
.height());
1685 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1687 widget
->resize(itemBounds
.size());
1691 // Updating the cell-information must be done as last step: The decision whether the
1692 // moving-animation should be started at all is based on the previous cell-information.
1693 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1694 m_visibleCells
.insert(i
, cell
);
1697 // Delete invisible KItemListWidget instances that have not been reused
1698 foreach (int index
, reusableItems
) {
1699 recycleWidget(m_visibleItems
.value(index
));
1702 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1703 Q_ASSERT(lastSibblingIndex
>= 0);
1704 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1708 // Update the layout of all visible group headers
1709 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1710 while (it
.hasNext()) {
1712 updateGroupHeaderLayout(it
.key());
1716 emitOffsetChanges();
1719 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1720 int lastVisibleIndex
,
1721 LayoutAnimationHint hint
)
1723 // Determine all items that are completely invisible and might be
1724 // reused for items that just got (at least partly) visible. If the
1725 // animation hint is set to 'Animation' items that do e.g. an animated
1726 // moving of their position are not marked as invisible: This assures
1727 // that a scrolling inside the view can be done without breaking an animation.
1731 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1732 while (it
.hasNext()) {
1735 KItemListWidget
* widget
= it
.value();
1736 const int index
= widget
->index();
1737 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1740 if (m_animation
->isStarted(widget
)) {
1741 if (hint
== NoAnimation
) {
1742 // Stopping the animation will call KItemListView::slotAnimationFinished()
1743 // and the widget will be recycled if necessary there.
1744 m_animation
->stop(widget
);
1747 widget
->setVisible(false);
1748 items
.append(index
);
1751 recycleGroupHeaderForWidget(widget
);
1760 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1762 if (widget
->pos() == newPos
) {
1766 bool startMovingAnim
= false;
1768 if (m_itemSize
.isEmpty()) {
1769 // The items are not aligned in a grid but either as columns or rows.
1770 startMovingAnim
= true;
1772 // When having a grid the moving-animation should only be started, if it is done within
1773 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1774 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1775 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1776 const int index
= widget
->index();
1777 const Cell cell
= m_visibleCells
.value(index
);
1778 if (cell
.column
>= 0 && cell
.row
>= 0) {
1779 if (scrollOrientation() == Qt::Vertical
) {
1780 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1782 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1787 if (startMovingAnim
) {
1788 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1792 m_animation
->stop(widget
);
1793 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1797 void KItemListView::emitOffsetChanges()
1799 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1800 if (m_oldScrollOffset
!= newScrollOffset
) {
1801 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1802 m_oldScrollOffset
= newScrollOffset
;
1805 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1806 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1807 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1808 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1811 const qreal newItemOffset
= m_layouter
->itemOffset();
1812 if (m_oldItemOffset
!= newItemOffset
) {
1813 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1814 m_oldItemOffset
= newItemOffset
;
1817 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1818 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1819 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1820 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1824 KItemListWidget
* KItemListView::createWidget(int index
)
1826 KItemListWidget
* widget
= widgetCreator()->create(this);
1827 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1829 m_visibleItems
.insert(index
, widget
);
1830 m_visibleCells
.insert(index
, Cell());
1831 updateWidgetProperties(widget
, index
);
1832 initializeItemListWidget(widget
);
1836 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1839 recycleGroupHeaderForWidget(widget
);
1842 const int index
= widget
->index();
1843 m_visibleItems
.remove(index
);
1844 m_visibleCells
.remove(index
);
1846 widgetCreator()->recycle(widget
);
1849 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1851 const int oldIndex
= widget
->index();
1852 m_visibleItems
.remove(oldIndex
);
1853 m_visibleCells
.remove(oldIndex
);
1855 m_visibleItems
.insert(index
, widget
);
1856 m_visibleCells
.insert(index
, Cell());
1858 widget
->setIndex(index
);
1861 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1863 const int oldIndex
= widget
->index();
1864 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1866 setWidgetIndex(widget
, index
);
1868 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1869 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1870 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1871 (!vertical
&& oldCell
.column
== newCell
.column
);
1873 m_visibleCells
.insert(index
, newCell
);
1877 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1880 case LayouterSize
: m_layouter
->setSize(size
); break;
1881 case ItemSize
: m_layouter
->setItemSize(size
); break;
1886 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1888 widget
->setVisibleRoles(m_visibleRoles
);
1889 updateWidgetColumnWidths(widget
);
1890 widget
->setStyleOption(m_styleOption
);
1892 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1893 widget
->setCurrent(index
== selectionManager
->currentItem());
1894 widget
->setSelected(selectionManager
->isSelected(index
));
1895 widget
->setHovered(false);
1896 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1897 widget
->setIndex(index
);
1898 widget
->setData(m_model
->data(index
));
1899 widget
->setSiblingsInformation(QBitArray());
1900 updateAlternateBackgroundForWidget(widget
);
1903 updateGroupHeaderForWidget(widget
);
1907 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1909 Q_ASSERT(m_grouped
);
1911 const int index
= widget
->index();
1912 if (!m_layouter
->isFirstGroupItem(index
)) {
1913 // The widget does not represent the first item of a group
1914 // and hence requires no header
1915 recycleGroupHeaderForWidget(widget
);
1919 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1920 if (groups
.isEmpty() || !groupHeaderCreator()) {
1924 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1926 groupHeader
= groupHeaderCreator()->create(this);
1927 groupHeader
->setParentItem(widget
);
1928 m_visibleGroups
.insert(widget
, groupHeader
);
1929 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1931 Q_ASSERT(groupHeader
->parentItem() == widget
);
1933 const int groupIndex
= groupIndexForItem(index
);
1934 Q_ASSERT(groupIndex
>= 0);
1935 groupHeader
->setData(groups
.at(groupIndex
).second
);
1936 groupHeader
->setRole(model()->sortRole());
1937 groupHeader
->setStyleOption(m_styleOption
);
1938 groupHeader
->setScrollOrientation(scrollOrientation());
1939 groupHeader
->setItemIndex(index
);
1941 groupHeader
->show();
1944 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1946 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1947 Q_ASSERT(groupHeader
);
1949 const int index
= widget
->index();
1950 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1951 const QRectF itemRect
= m_layouter
->itemRect(index
);
1953 // The group-header is a child of the itemlist widget. Translate the
1954 // group header position to the relative position.
1955 if (scrollOrientation() == Qt::Vertical
) {
1956 // In the vertical scroll orientation the group header should always span
1957 // the whole width no matter which temporary position the parent widget
1958 // has. In this case the x-position and width will be adjusted manually.
1959 const qreal x
= -widget
->x() - itemOffset();
1960 const qreal width
= maximumItemOffset();
1961 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1962 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1964 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1965 groupHeader
->resize(groupHeaderRect
.size());
1969 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1971 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1973 header
->setParentItem(0);
1974 groupHeaderCreator()->recycle(header
);
1975 m_visibleGroups
.remove(widget
);
1976 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1980 void KItemListView::updateVisibleGroupHeaders()
1982 Q_ASSERT(m_grouped
);
1983 m_layouter
->markAsDirty();
1985 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1986 while (it
.hasNext()) {
1988 updateGroupHeaderForWidget(it
.value());
1992 int KItemListView::groupIndexForItem(int index
) const
1994 Q_ASSERT(m_grouped
);
1996 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1997 if (groups
.isEmpty()) {
2002 int max
= groups
.count() - 1;
2005 mid
= (min
+ max
) / 2;
2006 if (index
> groups
[mid
].first
) {
2011 } while (groups
[mid
].first
!= index
&& min
<= max
);
2014 while (groups
[mid
].first
> index
&& mid
> 0) {
2022 void KItemListView::updateAlternateBackgrounds()
2024 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2025 while (it
.hasNext()) {
2027 updateAlternateBackgroundForWidget(it
.value());
2031 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2033 bool enabled
= useAlternateBackgrounds();
2035 const int index
= widget
->index();
2036 enabled
= (index
& 0x1) > 0;
2038 const int groupIndex
= groupIndexForItem(index
);
2039 if (groupIndex
>= 0) {
2040 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2041 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2042 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2043 enabled
= (relativeIndex
& 0x1) > 0;
2047 widget
->setAlternateBackground(enabled
);
2050 bool KItemListView::useAlternateBackgrounds() const
2052 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2055 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2057 QElapsedTimer timer
;
2060 QHash
<QByteArray
, qreal
> widths
;
2062 // Calculate the minimum width for each column that is required
2063 // to show the headline unclipped.
2064 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2065 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2066 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2067 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2068 const QString headerText
= m_model
->roleDescription(visibleRole
);
2069 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2070 widths
.insert(visibleRole
, headerWidth
);
2073 // Calculate the preferred column withs for each item and ignore values
2074 // smaller than the width for showing the headline unclipped.
2075 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2076 int calculatedItemCount
= 0;
2077 bool maxTimeExceeded
= false;
2078 foreach (const KItemRange
& itemRange
, itemRanges
) {
2079 const int startIndex
= itemRange
.index
;
2080 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2082 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2083 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2084 qreal maxWidth
= widths
.value(visibleRole
, 0);
2085 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2086 maxWidth
= qMax(width
, maxWidth
);
2087 widths
.insert(visibleRole
, maxWidth
);
2090 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2091 // When having several thousands of items calculating the sizes can get
2092 // very expensive. We accept a possibly too small role-size in favour
2093 // of having no blocking user interface.
2094 maxTimeExceeded
= true;
2097 ++calculatedItemCount
;
2099 if (maxTimeExceeded
) {
2107 void KItemListView::applyColumnWidthsFromHeader()
2109 // Apply the new size to the layouter
2110 const qreal requiredWidth
= columnWidthsSum();
2111 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2112 m_itemSize
.height());
2113 m_layouter
->setItemSize(dynamicItemSize
);
2115 // Update the role sizes for all visible widgets
2116 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2117 while (it
.hasNext()) {
2119 updateWidgetColumnWidths(it
.value());
2123 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2125 foreach (const QByteArray
& role
, m_visibleRoles
) {
2126 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2130 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2132 Q_ASSERT(m_itemSize
.isEmpty());
2133 const int itemCount
= m_model
->count();
2134 int rangesItemCount
= 0;
2135 foreach (const KItemRange
& range
, itemRanges
) {
2136 rangesItemCount
+= range
.count
;
2139 if (itemCount
== rangesItemCount
) {
2140 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2141 foreach (const QByteArray
& role
, m_visibleRoles
) {
2142 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2145 // Only a sub range of the roles need to be determined.
2146 // The chances are good that the widths of the sub ranges
2147 // already fit into the available widths and hence no
2148 // expensive update might be required.
2149 bool changed
= false;
2151 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2152 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2153 while (it
.hasNext()) {
2155 const QByteArray
& role
= it
.key();
2156 const qreal updatedWidth
= it
.value();
2157 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2158 if (updatedWidth
> currentWidth
) {
2159 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2165 // All the updated sizes are smaller than the current sizes and no change
2166 // of the stretched roles-widths is required
2171 if (m_headerWidget
->automaticColumnResizing()) {
2172 applyAutomaticColumnWidths();
2176 void KItemListView::updatePreferredColumnWidths()
2179 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2183 void KItemListView::applyAutomaticColumnWidths()
2185 Q_ASSERT(m_itemSize
.isEmpty());
2186 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2187 if (m_visibleRoles
.isEmpty()) {
2191 // Calculate the maximum size of an item by considering the
2192 // visible role sizes and apply them to the layouter. If the
2193 // size does not use the available view-size the size of the
2194 // first role will get stretched.
2196 foreach (const QByteArray
& role
, m_visibleRoles
) {
2197 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2198 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2201 const QByteArray firstRole
= m_visibleRoles
.first();
2202 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2203 QSizeF dynamicItemSize
= m_itemSize
;
2205 qreal requiredWidth
= columnWidthsSum();
2206 const qreal availableWidth
= size().width();
2207 if (requiredWidth
< availableWidth
) {
2208 // Stretch the first column to use the whole remaining width
2209 firstColumnWidth
+= availableWidth
- requiredWidth
;
2210 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2211 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2212 // Shrink the first column to be able to show as much other
2213 // columns as possible
2214 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2216 // TODO: A proper calculation of the minimum width depends on the implementation
2217 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2219 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2220 if (shrinkedFirstColumnWidth
< minWidth
) {
2221 shrinkedFirstColumnWidth
= minWidth
;
2224 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2225 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2228 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2230 m_layouter
->setItemSize(dynamicItemSize
);
2232 // Update the role sizes for all visible widgets
2233 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2234 while (it
.hasNext()) {
2236 updateWidgetColumnWidths(it
.value());
2240 qreal
KItemListView::columnWidthsSum() const
2242 qreal widthsSum
= 0;
2243 foreach (const QByteArray
& role
, m_visibleRoles
) {
2244 widthsSum
+= m_headerWidget
->columnWidth(role
);
2249 QRectF
KItemListView::headerBoundaries() const
2251 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2254 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2255 const QSizeF
& newItemSize
,
2256 const QSizeF
& newItemMargin
) const
2258 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2262 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2263 const qreal itemWidth
= m_layouter
->itemSize().width();
2264 if (itemWidth
> 0) {
2265 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2266 newItemSize
.width(),
2267 newItemMargin
.width());
2268 if (m_model
->count() > newColumnCount
) {
2269 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2271 m_layouter
->itemMargin().width());
2272 return oldColumnCount
!= newColumnCount
;
2276 const qreal itemHeight
= m_layouter
->itemSize().height();
2277 if (itemHeight
> 0) {
2278 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2279 newItemSize
.height(),
2280 newItemMargin
.height());
2281 if (m_model
->count() > newRowCount
) {
2282 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2284 m_layouter
->itemMargin().height());
2285 return oldRowCount
!= newRowCount
;
2293 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2295 if (m_itemSize
.isEmpty()) {
2296 // We have only columns or only rows, but no grid: An animation is usually
2297 // welcome when inserting or removing items.
2298 return !supportsItemExpanding();
2301 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2305 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2306 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2307 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2308 // Only animate if up to 2/3 of a row or column are inserted or removed
2309 return changedItemCount
<= maximum
* 2 / 3;
2313 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2315 const QSizeF oldSize
= m_layouter
->size();
2317 m_layouter
->setSize(size
);
2318 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2319 m_layouter
->setSize(oldSize
);
2321 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2322 : maxOffset
> size
.width();
2325 int KItemListView::showDropIndicator(const QPointF
& pos
)
2327 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2328 while (it
.hasNext()) {
2330 const KItemListWidget
* widget
= it
.value();
2332 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2333 const QRectF rect
= itemRect(widget
->index());
2334 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2335 if (m_model
->supportsDropping(widget
->index())) {
2336 const int gap
= qMax(4, m_styleOption
.padding
);
2337 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2342 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2343 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2345 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2346 if (m_dropIndicator
!= draggingInsertIndicator
) {
2347 m_dropIndicator
= draggingInsertIndicator
;
2351 int index
= widget
->index();
2359 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2360 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2363 void KItemListView::hideDropIndicator()
2365 if (!m_dropIndicator
.isNull()) {
2366 m_dropIndicator
= QRectF();
2371 void KItemListView::updateGroupHeaderHeight()
2373 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2374 qreal groupHeaderMargin
= 0;
2376 if (scrollOrientation() == Qt::Horizontal
) {
2377 // The vertical margin above and below the header should be
2378 // equal to the horizontal margin, not the vertical margin
2379 // from m_styleOption.
2380 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2381 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2382 } else if (m_itemSize
.isEmpty()){
2383 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2384 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2386 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2387 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2389 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2390 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2392 updateVisibleGroupHeaders();
2395 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2397 if (!supportsItemExpanding() || !m_model
) {
2401 if (firstIndex
< 0 || lastIndex
< 0) {
2402 firstIndex
= m_layouter
->firstVisibleIndex();
2403 lastIndex
= m_layouter
->lastVisibleIndex();
2405 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2406 lastIndex
>= m_layouter
->firstVisibleIndex());
2407 if (!isRangeVisible
) {
2412 int previousParents
= 0;
2413 QBitArray previousSiblings
;
2415 // The rootIndex describes the first index where the siblings get
2416 // calculated from. For the calculation the upper most parent item
2417 // is required. For performance reasons it is checked first whether
2418 // the visible items before or after the current range already
2419 // contain a siblings information which can be used as base.
2420 int rootIndex
= firstIndex
;
2422 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2424 // There is no visible widget before the range, check whether there
2425 // is one after the range:
2426 widget
= m_visibleItems
.value(lastIndex
+ 1);
2428 // The sibling information of the widget may only be used if
2429 // all items of the range have the same number of parents.
2430 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2431 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2432 if (m_model
->expandedParentsCount(i
) != parents
) {
2441 // Performance optimization: Use the sibling information of the visible
2442 // widget beside the given range.
2443 previousSiblings
= widget
->siblingsInformation();
2444 if (previousSiblings
.isEmpty()) {
2447 previousParents
= previousSiblings
.count() - 1;
2448 previousSiblings
.truncate(previousParents
);
2450 // Potentially slow path: Go back to the upper most parent of firstIndex
2451 // to be able to calculate the initial value for the siblings.
2452 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2457 Q_ASSERT(previousParents
>= 0);
2458 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2459 // Update the parent-siblings in case if the current item represents
2460 // a child or an upper parent.
2461 const int currentParents
= m_model
->expandedParentsCount(i
);
2462 Q_ASSERT(currentParents
>= 0);
2463 if (previousParents
< currentParents
) {
2464 previousParents
= currentParents
;
2465 previousSiblings
.resize(currentParents
);
2466 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2467 } else if (previousParents
> currentParents
) {
2468 previousParents
= currentParents
;
2469 previousSiblings
.truncate(currentParents
);
2472 if (i
>= firstIndex
) {
2473 // The index represents a visible item. Apply the parent-siblings
2474 // and update the sibling of the current item.
2475 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2480 QBitArray siblings
= previousSiblings
;
2481 siblings
.resize(siblings
.count() + 1);
2482 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2484 widget
->setSiblingsInformation(siblings
);
2489 bool KItemListView::hasSiblingSuccessor(int index
) const
2491 bool hasSuccessor
= false;
2492 const int parentsCount
= m_model
->expandedParentsCount(index
);
2493 int successorIndex
= index
+ 1;
2495 // Search the next sibling
2496 const int itemCount
= m_model
->count();
2497 while (successorIndex
< itemCount
) {
2498 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2499 if (currentParentsCount
== parentsCount
) {
2500 hasSuccessor
= true;
2502 } else if (currentParentsCount
< parentsCount
) {
2508 if (m_grouped
&& hasSuccessor
) {
2509 // If the sibling is part of another group, don't mark it as
2510 // successor as the group header is between the sibling connections.
2511 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2512 if (m_layouter
->isFirstGroupItem(i
)) {
2513 hasSuccessor
= false;
2519 return hasSuccessor
;
2522 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2526 const int minSpeed
= 4;
2527 const int maxSpeed
= 128;
2528 const int speedLimiter
= 96;
2529 const int autoScrollBorder
= 64;
2531 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2532 // This assures that the autoscrolling speed grows gradually.
2533 const int incLimiter
= 1;
2535 if (pos
< autoScrollBorder
) {
2536 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2537 inc
= qMax(inc
, -maxSpeed
);
2538 inc
= qMax(inc
, oldInc
- incLimiter
);
2539 } else if (pos
> range
- autoScrollBorder
) {
2540 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2541 inc
= qMin(inc
, maxSpeed
);
2542 inc
= qMin(inc
, oldInc
+ incLimiter
);
2548 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2550 const qreal availableSize
= size
- itemMargin
;
2551 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2557 KItemListCreatorBase::~KItemListCreatorBase()
2559 qDeleteAll(m_recycleableWidgets
);
2560 qDeleteAll(m_createdWidgets
);
2563 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2565 m_createdWidgets
.insert(widget
);
2568 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2570 Q_ASSERT(m_createdWidgets
.contains(widget
));
2571 m_createdWidgets
.remove(widget
);
2573 if (m_recycleableWidgets
.count() < 100) {
2574 m_recycleableWidgets
.append(widget
);
2575 widget
->setVisible(false);
2581 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2583 if (m_recycleableWidgets
.isEmpty()) {
2587 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2588 m_createdWidgets
.insert(widget
);
2592 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2596 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2598 widget
->setParentItem(0);
2599 widget
->setOpacity(1.0);
2600 pushRecycleableWidget(widget
);
2603 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2607 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2609 header
->setOpacity(1.0);
2610 pushRecycleableWidget(header
);
2613 #include "kitemlistview.moc"