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);
123 #ifndef QT_NO_ACCESSIBILITY
124 QAccessible::installFactory(accessibleViewFactory
);
128 KItemListView::~KItemListView()
130 // The group headers are children of the widgets created by
131 // widgetCreator(). So it is mandatory to delete the group headers
133 delete m_groupHeaderCreator
;
134 m_groupHeaderCreator
= 0;
136 delete m_widgetCreator
;
139 delete m_sizeHintResolver
;
140 m_sizeHintResolver
= 0;
141 #ifndef QT_NO_ACCESSIBILITY
142 QAccessible::removeFactory(accessibleViewFactory
);
146 void KItemListView::setScrollOffset(qreal offset
)
152 const qreal previousOffset
= m_layouter
->scrollOffset();
153 if (offset
== previousOffset
) {
157 m_layouter
->setScrollOffset(offset
);
158 m_animation
->setScrollOffset(offset
);
160 // Don't check whether the m_layoutTimer is active: Changing the
161 // scroll offset must always trigger a synchronous layout, otherwise
162 // the smooth-scrolling might get jerky.
163 doLayout(NoAnimation
);
164 onScrollOffsetChanged(offset
, previousOffset
);
167 qreal
KItemListView::scrollOffset() const
169 return m_layouter
->scrollOffset();
172 qreal
KItemListView::maximumScrollOffset() const
174 return m_layouter
->maximumScrollOffset();
177 void KItemListView::setItemOffset(qreal offset
)
179 if (m_layouter
->itemOffset() == offset
) {
183 m_layouter
->setItemOffset(offset
);
184 if (m_headerWidget
->isVisible()) {
185 m_headerWidget
->setOffset(offset
);
188 // Don't check whether the m_layoutTimer is active: Changing the
189 // item offset must always trigger a synchronous layout, otherwise
190 // the smooth-scrolling might get jerky.
191 doLayout(NoAnimation
);
194 qreal
KItemListView::itemOffset() const
196 return m_layouter
->itemOffset();
199 qreal
KItemListView::maximumItemOffset() const
201 return m_layouter
->maximumItemOffset();
204 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
206 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
207 m_visibleRoles
= roles
;
208 onVisibleRolesChanged(roles
, previousRoles
);
210 m_sizeHintResolver
->clearCache();
211 m_layouter
->markAsDirty();
213 if (m_itemSize
.isEmpty()) {
214 m_headerWidget
->setColumns(roles
);
215 updatePreferredColumnWidths();
216 if (!m_headerWidget
->automaticColumnResizing()) {
217 // The column-width of new roles are still 0. Apply the preferred
218 // column-width as default with.
219 foreach (const QByteArray
& role
, m_visibleRoles
) {
220 if (m_headerWidget
->columnWidth(role
) == 0) {
221 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
222 m_headerWidget
->setColumnWidth(role
, width
);
226 applyColumnWidthsFromHeader();
230 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
231 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
232 (roles
.count() <= 1 && previousRoles
.count() > 1));
234 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
235 while (it
.hasNext()) {
237 KItemListWidget
* widget
= it
.value();
238 widget
->setVisibleRoles(roles
);
239 if (alternateBackgroundsChanged
) {
240 updateAlternateBackgroundForWidget(widget
);
244 doLayout(NoAnimation
);
247 QList
<QByteArray
> KItemListView::visibleRoles() const
249 return m_visibleRoles
;
252 void KItemListView::setAutoScroll(bool enabled
)
254 if (enabled
&& !m_autoScrollTimer
) {
255 m_autoScrollTimer
= new QTimer(this);
256 m_autoScrollTimer
->setSingleShot(true);
257 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
258 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
259 } else if (!enabled
&& m_autoScrollTimer
) {
260 delete m_autoScrollTimer
;
261 m_autoScrollTimer
= 0;
265 bool KItemListView::autoScroll() const
267 return m_autoScrollTimer
!= 0;
270 void KItemListView::setEnabledSelectionToggles(bool enabled
)
272 if (m_enabledSelectionToggles
!= enabled
) {
273 m_enabledSelectionToggles
= enabled
;
275 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
276 while (it
.hasNext()) {
278 it
.value()->setEnabledSelectionToggle(enabled
);
283 bool KItemListView::enabledSelectionToggles() const
285 return m_enabledSelectionToggles
;
288 KItemListController
* KItemListView::controller() const
293 KItemModelBase
* KItemListView::model() const
298 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
300 if (m_widgetCreator
) {
301 delete m_widgetCreator
;
303 m_widgetCreator
= widgetCreator
;
306 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
308 if (!m_widgetCreator
) {
309 m_widgetCreator
= defaultWidgetCreator();
311 return m_widgetCreator
;
314 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
316 if (m_groupHeaderCreator
) {
317 delete m_groupHeaderCreator
;
319 m_groupHeaderCreator
= groupHeaderCreator
;
322 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
324 if (!m_groupHeaderCreator
) {
325 m_groupHeaderCreator
= defaultGroupHeaderCreator();
327 return m_groupHeaderCreator
;
330 QSizeF
KItemListView::itemSize() const
335 const KItemListStyleOption
& KItemListView::styleOption() const
337 return m_styleOption
;
340 void KItemListView::setGeometry(const QRectF
& rect
)
342 QGraphicsWidget::setGeometry(rect
);
348 const QSizeF newSize
= rect
.size();
349 if (m_itemSize
.isEmpty()) {
350 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
351 if (m_headerWidget
->automaticColumnResizing()) {
352 applyAutomaticColumnWidths();
354 const qreal requiredWidth
= columnWidthsSum();
355 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
356 m_itemSize
.height());
357 m_layouter
->setItemSize(dynamicItemSize
);
360 // Triggering a synchronous layout is fine from a performance point of view,
361 // as with dynamic item sizes no moving animation must be done.
362 m_layouter
->setSize(newSize
);
363 doLayout(NoAnimation
);
365 const bool animate
= !changesItemGridLayout(newSize
,
366 m_layouter
->itemSize(),
367 m_layouter
->itemMargin());
368 m_layouter
->setSize(newSize
);
371 // Trigger an asynchronous relayout with m_layoutTimer to prevent
372 // performance bottlenecks. If the timer is exceeded, an animated layout
373 // will be triggered.
374 if (!m_layoutTimer
->isActive()) {
375 m_layoutTimer
->start();
378 m_layoutTimer
->stop();
379 doLayout(NoAnimation
);
384 int KItemListView::itemAt(const QPointF
& pos
) const
386 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
387 while (it
.hasNext()) {
390 const KItemListWidget
* widget
= it
.value();
391 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
392 if (widget
->contains(mappedPos
)) {
400 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
402 if (!m_enabledSelectionToggles
) {
406 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
408 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
409 if (!selectionToggleRect
.isEmpty()) {
410 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
411 return selectionToggleRect
.contains(mappedPos
);
417 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
419 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
421 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
422 if (!expansionToggleRect
.isEmpty()) {
423 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
424 return expansionToggleRect
.contains(mappedPos
);
430 int KItemListView::firstVisibleIndex() const
432 return m_layouter
->firstVisibleIndex();
435 int KItemListView::lastVisibleIndex() const
437 return m_layouter
->lastVisibleIndex();
440 QSizeF
KItemListView::itemSizeHint(int index
) const
442 return widgetCreator()->itemSizeHint(index
, this);
445 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
447 if (m_supportsItemExpanding
!= supportsExpanding
) {
448 m_supportsItemExpanding
= supportsExpanding
;
449 updateSiblingsInformation();
450 onSupportsItemExpandingChanged(supportsExpanding
);
454 bool KItemListView::supportsItemExpanding() const
456 return m_supportsItemExpanding
;
459 QRectF
KItemListView::itemRect(int index
) const
461 return m_layouter
->itemRect(index
);
464 QRectF
KItemListView::itemContextRect(int index
) const
468 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
470 contextRect
= widget
->iconRect() | widget
->textRect();
471 contextRect
.translate(itemRect(index
).topLeft());
477 void KItemListView::scrollToItem(int index
)
479 QRectF viewGeometry
= geometry();
480 if (m_headerWidget
->isVisible()) {
481 const qreal headerHeight
= m_headerWidget
->size().height();
482 viewGeometry
.adjust(0, headerHeight
, 0, 0);
484 const QRectF currentRect
= itemRect(index
);
486 if (!viewGeometry
.contains(currentRect
)) {
487 qreal newOffset
= scrollOffset();
488 if (scrollOrientation() == Qt::Vertical
) {
489 if (currentRect
.top() < viewGeometry
.top()) {
490 newOffset
+= currentRect
.top() - viewGeometry
.top();
491 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
492 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
495 if (currentRect
.left() < viewGeometry
.left()) {
496 newOffset
+= currentRect
.left() - viewGeometry
.left();
497 } else if (currentRect
.right() > viewGeometry
.right()) {
498 newOffset
+= currentRect
.right() - viewGeometry
.right();
502 if (newOffset
!= scrollOffset()) {
503 emit
scrollTo(newOffset
);
508 void KItemListView::beginTransaction()
510 ++m_activeTransactions
;
511 if (m_activeTransactions
== 1) {
512 onTransactionBegin();
516 void KItemListView::endTransaction()
518 --m_activeTransactions
;
519 if (m_activeTransactions
< 0) {
520 m_activeTransactions
= 0;
521 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
524 if (m_activeTransactions
== 0) {
526 doLayout(m_endTransactionAnimationHint
);
527 m_endTransactionAnimationHint
= Animation
;
531 bool KItemListView::isTransactionActive() const
533 return m_activeTransactions
> 0;
536 void KItemListView::setHeaderVisible(bool visible
)
538 if (visible
&& !m_headerWidget
->isVisible()) {
539 QStyleOptionHeader option
;
540 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
543 m_headerWidget
->setPos(0, 0);
544 m_headerWidget
->resize(size().width(), headerSize
.height());
545 m_headerWidget
->setModel(m_model
);
546 m_headerWidget
->setColumns(m_visibleRoles
);
547 m_headerWidget
->setZValue(1);
549 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
550 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
551 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
552 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
553 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
554 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
555 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
556 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
558 m_layouter
->setHeaderHeight(headerSize
.height());
559 m_headerWidget
->setVisible(true);
560 } else if (!visible
&& m_headerWidget
->isVisible()) {
561 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
562 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
563 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
564 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
565 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
566 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
567 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
568 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
570 m_layouter
->setHeaderHeight(0);
571 m_headerWidget
->setVisible(false);
575 bool KItemListView::isHeaderVisible() const
577 return m_headerWidget
->isVisible();
580 KItemListHeader
* KItemListView::header() const
585 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
589 if (indexes
.count() == 1) {
590 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
591 QGraphicsView
* graphicsView
= scene()->views()[0];
592 if (item
&& graphicsView
) {
593 pixmap
= item
->createDragPixmap(0, graphicsView
);
596 // TODO: Not implemented yet. Probably extend the interface
597 // from KItemListWidget::createDragPixmap() to return a pixmap
598 // that can be used for multiple indexes.
604 void KItemListView::editRole(int index
, const QByteArray
& role
)
606 KItemListWidget
* widget
= m_visibleItems
.value(index
);
607 if (!widget
|| m_editingRole
) {
611 m_editingRole
= true;
612 widget
->setEditedRole(role
);
614 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
615 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
616 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
617 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
620 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
622 QGraphicsWidget::paint(painter
, option
, widget
);
624 if (m_rubberBand
->isActive()) {
625 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
626 m_rubberBand
->endPosition()).normalized();
628 const QPointF topLeft
= rubberBandRect
.topLeft();
629 if (scrollOrientation() == Qt::Vertical
) {
630 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
632 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
635 QStyleOptionRubberBand opt
;
636 opt
.initFrom(widget
);
637 opt
.shape
= QRubberBand::Rectangle
;
639 opt
.rect
= rubberBandRect
.toRect();
640 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
643 if (!m_dropIndicator
.isEmpty()) {
644 const QRectF r
= m_dropIndicator
.toRect();
646 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
647 painter
->setPen(color
);
649 // TODO: The following implementation works only for a vertical scroll-orientation
650 // and assumes a height of the m_draggingInsertIndicator of 1.
651 Q_ASSERT(r
.height() == 1);
652 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
655 painter
->setPen(color
);
656 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
660 void KItemListView::setItemSize(const QSizeF
& size
)
662 const QSizeF previousSize
= m_itemSize
;
663 if (size
== previousSize
) {
667 // Skip animations when the number of rows or columns
668 // are changed in the grid layout. Although the animation
669 // engine can handle this usecase, it looks obtrusive.
670 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
672 m_layouter
->itemMargin());
674 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
675 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
676 (!m_itemSize
.isEmpty() && size
.isEmpty()));
680 if (alternateBackgroundsChanged
) {
681 // For an empty item size alternate backgrounds are drawn if more than
682 // one role is shown. Assure that the backgrounds for visible items are
683 // updated when changing the size in this context.
684 updateAlternateBackgrounds();
687 if (size
.isEmpty()) {
688 if (m_headerWidget
->automaticColumnResizing()) {
689 updatePreferredColumnWidths();
691 // Only apply the changed height and respect the header widths
693 const qreal currentWidth
= m_layouter
->itemSize().width();
694 const QSizeF
newSize(currentWidth
, size
.height());
695 m_layouter
->setItemSize(newSize
);
698 m_layouter
->setItemSize(size
);
701 m_sizeHintResolver
->clearCache();
702 doLayout(animate
? Animation
: NoAnimation
);
703 onItemSizeChanged(size
, previousSize
);
706 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
708 const KItemListStyleOption previousOption
= m_styleOption
;
709 m_styleOption
= option
;
712 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
713 if (margin
!= m_layouter
->itemMargin()) {
714 // Skip animations when the number of rows or columns
715 // are changed in the grid layout. Although the animation
716 // engine can handle this usecase, it looks obtrusive.
717 animate
= !changesItemGridLayout(m_layouter
->size(),
718 m_layouter
->itemSize(),
720 m_layouter
->setItemMargin(margin
);
724 updateGroupHeaderHeight();
727 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
728 // Animating a change of the maximum text size just results in expensive
729 // temporary eliding and clipping operations and does not look good visually.
733 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
734 while (it
.hasNext()) {
736 it
.value()->setStyleOption(option
);
739 m_sizeHintResolver
->clearCache();
740 m_layouter
->markAsDirty();
741 doLayout(animate
? Animation
: NoAnimation
);
743 if (m_itemSize
.isEmpty()) {
744 updatePreferredColumnWidths();
747 onStyleOptionChanged(option
, previousOption
);
750 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
752 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
753 if (orientation
== previousOrientation
) {
757 m_layouter
->setScrollOrientation(orientation
);
758 m_animation
->setScrollOrientation(orientation
);
759 m_sizeHintResolver
->clearCache();
762 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
763 while (it
.hasNext()) {
765 it
.value()->setScrollOrientation(orientation
);
767 updateGroupHeaderHeight();
771 doLayout(NoAnimation
);
773 onScrollOrientationChanged(orientation
, previousOrientation
);
774 emit
scrollOrientationChanged(orientation
, previousOrientation
);
777 Qt::Orientation
KItemListView::scrollOrientation() const
779 return m_layouter
->scrollOrientation();
782 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
787 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
792 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
797 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
799 Q_UNUSED(changedRoles
);
803 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
809 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
815 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
821 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
827 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
833 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
839 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
845 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
847 Q_UNUSED(supportsExpanding
);
850 void KItemListView::onTransactionBegin()
854 void KItemListView::onTransactionEnd()
858 bool KItemListView::event(QEvent
* event
)
860 // Forward all events to the controller and handle them there
861 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
865 return QGraphicsWidget::event(event
);
868 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
870 m_mousePos
= transform().map(event
->pos());
874 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
876 QGraphicsWidget::mouseMoveEvent(event
);
878 m_mousePos
= transform().map(event
->pos());
879 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
880 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
884 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
886 event
->setAccepted(true);
890 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
892 QGraphicsWidget::dragMoveEvent(event
);
894 m_mousePos
= transform().map(event
->pos());
895 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
896 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
900 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
902 QGraphicsWidget::dragLeaveEvent(event
);
903 setAutoScroll(false);
906 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
908 QGraphicsWidget::dropEvent(event
);
909 setAutoScroll(false);
912 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
914 return m_visibleItems
.values();
917 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
919 if (m_itemSize
.isEmpty()) {
920 updatePreferredColumnWidths(itemRanges
);
923 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
924 if (hasMultipleRanges
) {
928 m_layouter
->markAsDirty();
930 int previouslyInsertedCount
= 0;
931 foreach (const KItemRange
& range
, itemRanges
) {
932 // range.index is related to the model before anything has been inserted.
933 // As in each loop the current item-range gets inserted the index must
934 // be increased by the already previously inserted items.
935 const int index
= range
.index
+ previouslyInsertedCount
;
936 const int count
= range
.count
;
937 if (index
< 0 || count
<= 0) {
938 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
941 previouslyInsertedCount
+= count
;
943 m_sizeHintResolver
->itemsInserted(index
, count
);
945 // Determine which visible items must be moved
946 QList
<int> itemsToMove
;
947 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
948 while (it
.hasNext()) {
950 const int visibleItemIndex
= it
.key();
951 if (visibleItemIndex
>= index
) {
952 itemsToMove
.append(visibleItemIndex
);
956 // Update the indexes of all KItemListWidget instances that are located
957 // after the inserted items. It is important to adjust the indexes in the order
958 // from the highest index to the lowest index to prevent overlaps when setting the new index.
960 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
961 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
963 const int newIndex
= widget
->index() + count
;
964 if (hasMultipleRanges
) {
965 setWidgetIndex(widget
, newIndex
);
967 // Try to animate the moving of the item
968 moveWidgetToIndex(widget
, newIndex
);
972 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
973 // Check whether a scrollbar is required to show the inserted items. In this case
974 // the size of the layouter will be decreased before calling doLayout(): This prevents
975 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
976 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
977 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
978 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
979 if (decreaseLayouterSize
) {
980 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
981 QSizeF layouterSize
= m_layouter
->size();
982 if (verticalScrollOrientation
) {
983 layouterSize
.rwidth() -= scrollBarExtent
;
985 layouterSize
.rheight() -= scrollBarExtent
;
987 m_layouter
->setSize(layouterSize
);
991 if (!hasMultipleRanges
) {
992 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
993 updateSiblingsInformation();
998 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1001 if (hasMultipleRanges
) {
1003 // Important: Don't read any m_layouter-property inside the for-loop in case if
1004 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1005 // updated in each loop-cycle and has only a consistent state after the loop.
1006 Q_ASSERT(m_layouter
->isDirty());
1008 m_endTransactionAnimationHint
= NoAnimation
;
1011 updateSiblingsInformation();
1014 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1015 // In case if items of the same group have been inserted before an item that
1016 // currently represents the first item of the group, the group header of
1017 // this item must be removed.
1018 updateVisibleGroupHeaders();
1021 if (useAlternateBackgrounds()) {
1022 updateAlternateBackgrounds();
1026 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1028 if (m_itemSize
.isEmpty()) {
1029 // Don't pass the item-range: The preferred column-widths of
1030 // all items must be adjusted when removing items.
1031 updatePreferredColumnWidths();
1034 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1035 if (hasMultipleRanges
) {
1039 m_layouter
->markAsDirty();
1041 int removedItemsCount
= 0;
1042 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1043 removedItemsCount
+= itemRanges
[i
].count
;
1046 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1047 const KItemRange
& range
= itemRanges
[i
];
1048 const int index
= range
.index
;
1049 const int count
= range
.count
;
1050 if (index
< 0 || count
<= 0) {
1051 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1055 m_sizeHintResolver
->itemsRemoved(index
, count
);
1057 const int firstRemovedIndex
= index
;
1058 const int lastRemovedIndex
= index
+ count
- 1;
1059 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1060 removedItemsCount
-= count
;
1062 // Remove all KItemListWidget instances that got deleted
1063 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1064 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1069 m_animation
->stop(widget
);
1070 // Stopping the animation might lead to recycling the widget if
1071 // it is invisible (see slotAnimationFinished()).
1072 // Check again whether it is still visible:
1073 if (!m_visibleItems
.contains(i
)) {
1077 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1078 // Remove the widget without animation
1079 recycleWidget(widget
);
1081 // Animate the removing of the items. Special case: When removing an item there
1082 // is no valid model index available anymore. For the
1083 // remove-animation the item gets removed from m_visibleItems but the widget
1084 // will stay alive until the animation has been finished and will
1085 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1086 m_visibleItems
.remove(i
);
1087 widget
->setIndex(-1);
1088 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1092 // Update the indexes of all KItemListWidget instances that are located
1093 // after the deleted items
1094 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1095 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1097 const int newIndex
= i
- count
;
1098 if (hasMultipleRanges
) {
1099 setWidgetIndex(widget
, newIndex
);
1101 // Try to animate the moving of the item
1102 moveWidgetToIndex(widget
, newIndex
);
1107 if (!hasMultipleRanges
) {
1108 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1109 // assumes an updated geometry. If items are removed during an active transaction,
1110 // the transaction will be temporary deactivated so that doLayout() triggers a
1111 // geometry update if necessary.
1112 const int activeTransactions
= m_activeTransactions
;
1113 m_activeTransactions
= 0;
1114 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1115 m_activeTransactions
= activeTransactions
;
1116 updateSiblingsInformation();
1121 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1124 if (hasMultipleRanges
) {
1126 // Important: Don't read any m_layouter-property inside the for-loop in case if
1127 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1128 // updated in each loop-cycle and has only a consistent state after the loop.
1129 Q_ASSERT(m_layouter
->isDirty());
1131 m_endTransactionAnimationHint
= NoAnimation
;
1133 updateSiblingsInformation();
1136 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1137 // In case if the first item of a group has been removed, the group header
1138 // must be applied to the next visible item.
1139 updateVisibleGroupHeaders();
1142 if (useAlternateBackgrounds()) {
1143 updateAlternateBackgrounds();
1147 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1149 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1150 m_layouter
->markAsDirty();
1153 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1156 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1157 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1159 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1160 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1162 updateWidgetProperties(widget
, index
);
1163 initializeItemListWidget(widget
);
1167 doLayout(NoAnimation
);
1168 updateSiblingsInformation();
1171 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1172 const QSet
<QByteArray
>& roles
)
1174 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1175 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1176 updatePreferredColumnWidths(itemRanges
);
1179 foreach (const KItemRange
& itemRange
, itemRanges
) {
1180 const int index
= itemRange
.index
;
1181 const int count
= itemRange
.count
;
1183 if (updateSizeHints
) {
1184 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1185 m_layouter
->markAsDirty();
1187 if (!m_layoutTimer
->isActive()) {
1188 m_layoutTimer
->start();
1192 // Apply the changed roles to the visible item-widgets
1193 const int lastIndex
= index
+ count
- 1;
1194 for (int i
= index
; i
<= lastIndex
; ++i
) {
1195 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1197 widget
->setData(m_model
->data(i
), roles
);
1201 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1202 // The sort-role has been changed which might result
1203 // in modified group headers
1204 updateVisibleGroupHeaders();
1205 doLayout(NoAnimation
);
1210 void KItemListView::slotGroupedSortingChanged(bool current
)
1212 m_grouped
= current
;
1213 m_layouter
->markAsDirty();
1216 updateGroupHeaderHeight();
1218 // Clear all visible headers
1219 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1220 while (it
.hasNext()) {
1222 recycleGroupHeaderForWidget(it
.key());
1224 Q_ASSERT(m_visibleGroups
.isEmpty());
1227 if (useAlternateBackgrounds()) {
1228 // Changing the group mode requires to update the alternate backgrounds
1229 // as with the enabled group mode the altering is done on base of the first
1231 updateAlternateBackgrounds();
1233 updateSiblingsInformation();
1234 doLayout(NoAnimation
);
1237 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1242 updateVisibleGroupHeaders();
1243 doLayout(NoAnimation
);
1247 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1252 updateVisibleGroupHeaders();
1253 doLayout(NoAnimation
);
1257 void KItemListView::slotCurrentChanged(int current
, int previous
)
1261 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1262 if (previousWidget
) {
1263 previousWidget
->setCurrent(false);
1266 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1267 if (currentWidget
) {
1268 currentWidget
->setCurrent(true);
1270 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1273 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1277 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1278 while (it
.hasNext()) {
1280 const int index
= it
.key();
1281 KItemListWidget
* widget
= it
.value();
1282 widget
->setSelected(current
.contains(index
));
1286 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1287 KItemListViewAnimation::AnimationType type
)
1289 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1290 Q_ASSERT(itemListWidget
);
1293 case KItemListViewAnimation::DeleteAnimation
: {
1294 // As we recycle the widget in this case it is important to assure that no
1295 // other animation has been started. This is a convention in KItemListView and
1296 // not a requirement defined by KItemListViewAnimation.
1297 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1299 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1300 // by m_visibleWidgets and must be deleted manually after the animation has
1302 recycleGroupHeaderForWidget(itemListWidget
);
1303 widgetCreator()->recycle(itemListWidget
);
1307 case KItemListViewAnimation::CreateAnimation
:
1308 case KItemListViewAnimation::MovingAnimation
:
1309 case KItemListViewAnimation::ResizeAnimation
: {
1310 const int index
= itemListWidget
->index();
1311 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1312 (index
> m_layouter
->lastVisibleIndex());
1313 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1314 recycleWidget(itemListWidget
);
1323 void KItemListView::slotLayoutTimerFinished()
1325 m_layouter
->setSize(geometry().size());
1326 doLayout(Animation
);
1329 void KItemListView::slotRubberBandPosChanged()
1334 void KItemListView::slotRubberBandActivationChanged(bool active
)
1337 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1338 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1339 m_skipAutoScrollForRubberBand
= true;
1341 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1342 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1343 m_skipAutoScrollForRubberBand
= false;
1349 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1351 qreal previousWidth
)
1354 Q_UNUSED(currentWidth
);
1355 Q_UNUSED(previousWidth
);
1357 m_headerWidget
->setAutomaticColumnResizing(false);
1358 applyColumnWidthsFromHeader();
1359 doLayout(NoAnimation
);
1362 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1366 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1368 const QList
<QByteArray
> previous
= m_visibleRoles
;
1370 QList
<QByteArray
> current
= m_visibleRoles
;
1371 current
.removeAt(previousIndex
);
1372 current
.insert(currentIndex
, role
);
1374 setVisibleRoles(current
);
1376 emit
visibleRolesChanged(current
, previous
);
1379 void KItemListView::triggerAutoScrolling()
1381 if (!m_autoScrollTimer
) {
1386 int visibleSize
= 0;
1387 if (scrollOrientation() == Qt::Vertical
) {
1388 pos
= m_mousePos
.y();
1389 visibleSize
= size().height();
1391 pos
= m_mousePos
.x();
1392 visibleSize
= size().width();
1395 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1396 m_autoScrollIncrement
= 0;
1399 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1400 if (m_autoScrollIncrement
== 0) {
1401 // The mouse position is not above an autoscroll margin (the autoscroll timer
1402 // will be restarted in mouseMoveEvent())
1403 m_autoScrollTimer
->stop();
1407 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1408 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1409 // if the direction of the rubberband is similar to the autoscroll direction. This
1410 // prevents that starting to create a rubberband within the autoscroll margins starts
1411 // an autoscrolling.
1413 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1414 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1415 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1416 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1417 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1418 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1419 // been moved up although the autoscroll direction might be down)
1420 m_autoScrollTimer
->stop();
1425 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1426 // the autoscrolling may not get skipped anymore until a new rubberband is created
1427 m_skipAutoScrollForRubberBand
= false;
1429 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1430 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1431 setScrollOffset(newScrollOffset
);
1433 // Trigger the autoscroll timer which will periodically call
1434 // triggerAutoScrolling()
1435 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1438 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1440 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1442 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1443 Q_ASSERT(groupHeader
);
1444 updateGroupHeaderLayout(widget
);
1447 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1449 emit
roleEditingCanceled(index
, role
, value
);
1450 m_editingRole
= false;
1453 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1455 emit
roleEditingFinished(index
, role
, value
);
1456 m_editingRole
= false;
1459 void KItemListView::setController(KItemListController
* controller
)
1461 if (m_controller
!= controller
) {
1462 KItemListController
* previous
= m_controller
;
1464 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1465 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1466 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1469 m_controller
= controller
;
1472 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1473 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1474 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1477 onControllerChanged(controller
, previous
);
1481 void KItemListView::setModel(KItemModelBase
* model
)
1483 if (m_model
== model
) {
1487 KItemModelBase
* previous
= m_model
;
1490 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1491 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1492 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1493 this, SLOT(slotItemsInserted(KItemRangeList
)));
1494 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1495 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1496 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1497 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1498 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1499 this, SLOT(slotGroupedSortingChanged(bool)));
1500 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1501 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1502 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1503 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1506 m_sizeHintResolver
->clearCache();
1509 m_layouter
->setModel(model
);
1510 m_grouped
= model
->groupedSorting();
1513 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1514 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1515 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1516 this, SLOT(slotItemsInserted(KItemRangeList
)));
1517 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1518 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1519 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1520 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1521 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1522 this, SLOT(slotGroupedSortingChanged(bool)));
1523 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1524 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1525 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1526 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1528 const int itemCount
= m_model
->count();
1529 if (itemCount
> 0) {
1530 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1531 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1535 onModelChanged(model
, previous
);
1538 KItemListRubberBand
* KItemListView::rubberBand() const
1540 return m_rubberBand
;
1543 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1545 if (m_layoutTimer
->isActive()) {
1546 m_layoutTimer
->stop();
1549 if (m_activeTransactions
> 0) {
1550 if (hint
== NoAnimation
) {
1551 // As soon as at least one property change should be done without animation,
1552 // the whole transaction will be marked as not animated.
1553 m_endTransactionAnimationHint
= NoAnimation
;
1558 if (!m_model
|| m_model
->count() < 0) {
1562 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1563 if (firstVisibleIndex
< 0) {
1564 emitOffsetChanges();
1568 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1569 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1570 // is still shown if the maximum offset got decreased.
1571 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1572 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1573 if (scrollOffset() > maxOffsetToShowFullRange
) {
1574 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1575 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1578 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1580 int firstSibblingIndex
= -1;
1581 int lastSibblingIndex
= -1;
1582 const bool supportsExpanding
= supportsItemExpanding();
1584 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1586 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1587 // instances from invisible items are reused. If no reusable items are
1588 // found then new KItemListWidget instances get created.
1589 const bool animate
= (hint
== Animation
);
1590 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1591 bool applyNewPos
= true;
1592 bool wasHidden
= false;
1594 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1595 const QPointF newPos
= itemBounds
.topLeft();
1596 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1599 if (!reusableItems
.isEmpty()) {
1600 // Reuse a KItemListWidget instance from an invisible item
1601 const int oldIndex
= reusableItems
.takeLast();
1602 widget
= m_visibleItems
.value(oldIndex
);
1603 setWidgetIndex(widget
, i
);
1604 updateWidgetProperties(widget
, i
);
1605 initializeItemListWidget(widget
);
1607 // No reusable KItemListWidget instance is available, create a new one
1608 widget
= createWidget(i
);
1610 widget
->resize(itemBounds
.size());
1612 if (animate
&& changedCount
< 0) {
1613 // Items have been deleted, move the created item to the
1614 // imaginary old position. They will get animated to the new position
1616 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1617 if (itemRect
.isEmpty()) {
1618 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1619 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1620 widget
->setPos(invisibleOldPos
);
1622 widget
->setPos(itemRect
.topLeft());
1624 applyNewPos
= false;
1627 if (supportsExpanding
&& changedCount
== 0) {
1628 if (firstSibblingIndex
< 0) {
1629 firstSibblingIndex
= i
;
1631 lastSibblingIndex
= i
;
1636 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1637 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1638 applyNewPos
= false;
1641 const bool itemsRemoved
= (changedCount
< 0);
1642 const bool itemsInserted
= (changedCount
> 0);
1643 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1644 // The item is located after the removed items. Animate the moving of the position.
1645 applyNewPos
= !moveWidget(widget
, newPos
);
1646 } else if (itemsInserted
&& i
>= changedIndex
) {
1647 // The item is located after the first inserted item
1648 if (i
<= changedIndex
+ changedCount
- 1) {
1649 // The item is an inserted item. Animate the appearing of the item.
1650 // For performance reasons no animation is done when changedCount is equal
1651 // to all available items.
1652 if (changedCount
< m_model
->count()) {
1653 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1655 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1656 // The item was already there before, so animate the moving of the position.
1657 // No moving animation is done if the item is animated by a create animation: This
1658 // prevents a "move animation mess" when inserting several ranges in parallel.
1659 applyNewPos
= !moveWidget(widget
, newPos
);
1661 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1662 // The size of the view might have been changed. Animate the moving of the position.
1663 applyNewPos
= !moveWidget(widget
, newPos
);
1666 m_animation
->stop(widget
);
1670 widget
->setPos(newPos
);
1673 Q_ASSERT(widget
->index() == i
);
1674 widget
->setVisible(true);
1676 if (widget
->size() != itemBounds
.size()) {
1677 // Resize the widget for the item to the changed size.
1679 // If a dynamic item size is used then no animation is done in the direction
1680 // of the dynamic size.
1681 if (m_itemSize
.width() <= 0) {
1682 // The width is dynamic, apply the new width without animation.
1683 widget
->resize(itemBounds
.width(), widget
->size().height());
1684 } else if (m_itemSize
.height() <= 0) {
1685 // The height is dynamic, apply the new height without animation.
1686 widget
->resize(widget
->size().width(), itemBounds
.height());
1688 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1690 widget
->resize(itemBounds
.size());
1694 // Updating the cell-information must be done as last step: The decision whether the
1695 // moving-animation should be started at all is based on the previous cell-information.
1696 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1697 m_visibleCells
.insert(i
, cell
);
1700 // Delete invisible KItemListWidget instances that have not been reused
1701 foreach (int index
, reusableItems
) {
1702 recycleWidget(m_visibleItems
.value(index
));
1705 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1706 Q_ASSERT(lastSibblingIndex
>= 0);
1707 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1711 // Update the layout of all visible group headers
1712 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1713 while (it
.hasNext()) {
1715 updateGroupHeaderLayout(it
.key());
1719 emitOffsetChanges();
1722 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1723 int lastVisibleIndex
,
1724 LayoutAnimationHint hint
)
1726 // Determine all items that are completely invisible and might be
1727 // reused for items that just got (at least partly) visible. If the
1728 // animation hint is set to 'Animation' items that do e.g. an animated
1729 // moving of their position are not marked as invisible: This assures
1730 // that a scrolling inside the view can be done without breaking an animation.
1734 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1735 while (it
.hasNext()) {
1738 KItemListWidget
* widget
= it
.value();
1739 const int index
= widget
->index();
1740 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1743 if (m_animation
->isStarted(widget
)) {
1744 if (hint
== NoAnimation
) {
1745 // Stopping the animation will call KItemListView::slotAnimationFinished()
1746 // and the widget will be recycled if necessary there.
1747 m_animation
->stop(widget
);
1750 widget
->setVisible(false);
1751 items
.append(index
);
1754 recycleGroupHeaderForWidget(widget
);
1763 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1765 if (widget
->pos() == newPos
) {
1769 bool startMovingAnim
= false;
1771 if (m_itemSize
.isEmpty()) {
1772 // The items are not aligned in a grid but either as columns or rows.
1773 startMovingAnim
= true;
1775 // When having a grid the moving-animation should only be started, if it is done within
1776 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1777 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1778 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1779 const int index
= widget
->index();
1780 const Cell cell
= m_visibleCells
.value(index
);
1781 if (cell
.column
>= 0 && cell
.row
>= 0) {
1782 if (scrollOrientation() == Qt::Vertical
) {
1783 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1785 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1790 if (startMovingAnim
) {
1791 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1795 m_animation
->stop(widget
);
1796 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1800 void KItemListView::emitOffsetChanges()
1802 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1803 if (m_oldScrollOffset
!= newScrollOffset
) {
1804 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1805 m_oldScrollOffset
= newScrollOffset
;
1808 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1809 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1810 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1811 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1814 const qreal newItemOffset
= m_layouter
->itemOffset();
1815 if (m_oldItemOffset
!= newItemOffset
) {
1816 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1817 m_oldItemOffset
= newItemOffset
;
1820 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1821 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1822 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1823 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1827 KItemListWidget
* KItemListView::createWidget(int index
)
1829 KItemListWidget
* widget
= widgetCreator()->create(this);
1830 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1832 m_visibleItems
.insert(index
, widget
);
1833 m_visibleCells
.insert(index
, Cell());
1834 updateWidgetProperties(widget
, index
);
1835 initializeItemListWidget(widget
);
1839 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1842 recycleGroupHeaderForWidget(widget
);
1845 const int index
= widget
->index();
1846 m_visibleItems
.remove(index
);
1847 m_visibleCells
.remove(index
);
1849 widgetCreator()->recycle(widget
);
1852 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1854 const int oldIndex
= widget
->index();
1855 m_visibleItems
.remove(oldIndex
);
1856 m_visibleCells
.remove(oldIndex
);
1858 m_visibleItems
.insert(index
, widget
);
1859 m_visibleCells
.insert(index
, Cell());
1861 widget
->setIndex(index
);
1864 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1866 const int oldIndex
= widget
->index();
1867 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1869 setWidgetIndex(widget
, index
);
1871 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1872 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1873 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1874 (!vertical
&& oldCell
.column
== newCell
.column
);
1876 m_visibleCells
.insert(index
, newCell
);
1880 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1883 case LayouterSize
: m_layouter
->setSize(size
); break;
1884 case ItemSize
: m_layouter
->setItemSize(size
); break;
1889 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1891 widget
->setVisibleRoles(m_visibleRoles
);
1892 updateWidgetColumnWidths(widget
);
1893 widget
->setStyleOption(m_styleOption
);
1895 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1896 widget
->setCurrent(index
== selectionManager
->currentItem());
1897 widget
->setSelected(selectionManager
->isSelected(index
));
1898 widget
->setHovered(false);
1899 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1900 widget
->setIndex(index
);
1901 widget
->setData(m_model
->data(index
));
1902 widget
->setSiblingsInformation(QBitArray());
1903 updateAlternateBackgroundForWidget(widget
);
1906 updateGroupHeaderForWidget(widget
);
1910 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1912 Q_ASSERT(m_grouped
);
1914 const int index
= widget
->index();
1915 if (!m_layouter
->isFirstGroupItem(index
)) {
1916 // The widget does not represent the first item of a group
1917 // and hence requires no header
1918 recycleGroupHeaderForWidget(widget
);
1922 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1923 if (groups
.isEmpty() || !groupHeaderCreator()) {
1927 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1929 groupHeader
= groupHeaderCreator()->create(this);
1930 groupHeader
->setParentItem(widget
);
1931 m_visibleGroups
.insert(widget
, groupHeader
);
1932 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1934 Q_ASSERT(groupHeader
->parentItem() == widget
);
1936 const int groupIndex
= groupIndexForItem(index
);
1937 Q_ASSERT(groupIndex
>= 0);
1938 groupHeader
->setData(groups
.at(groupIndex
).second
);
1939 groupHeader
->setRole(model()->sortRole());
1940 groupHeader
->setStyleOption(m_styleOption
);
1941 groupHeader
->setScrollOrientation(scrollOrientation());
1942 groupHeader
->setItemIndex(index
);
1944 groupHeader
->show();
1947 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1949 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1950 Q_ASSERT(groupHeader
);
1952 const int index
= widget
->index();
1953 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1954 const QRectF itemRect
= m_layouter
->itemRect(index
);
1956 // The group-header is a child of the itemlist widget. Translate the
1957 // group header position to the relative position.
1958 if (scrollOrientation() == Qt::Vertical
) {
1959 // In the vertical scroll orientation the group header should always span
1960 // the whole width no matter which temporary position the parent widget
1961 // has. In this case the x-position and width will be adjusted manually.
1962 const qreal x
= -widget
->x() - itemOffset();
1963 const qreal width
= maximumItemOffset();
1964 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1965 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1967 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1968 groupHeader
->resize(groupHeaderRect
.size());
1972 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1974 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1976 header
->setParentItem(0);
1977 groupHeaderCreator()->recycle(header
);
1978 m_visibleGroups
.remove(widget
);
1979 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1983 void KItemListView::updateVisibleGroupHeaders()
1985 Q_ASSERT(m_grouped
);
1986 m_layouter
->markAsDirty();
1988 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1989 while (it
.hasNext()) {
1991 updateGroupHeaderForWidget(it
.value());
1995 int KItemListView::groupIndexForItem(int index
) const
1997 Q_ASSERT(m_grouped
);
1999 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2000 if (groups
.isEmpty()) {
2005 int max
= groups
.count() - 1;
2008 mid
= (min
+ max
) / 2;
2009 if (index
> groups
[mid
].first
) {
2014 } while (groups
[mid
].first
!= index
&& min
<= max
);
2017 while (groups
[mid
].first
> index
&& mid
> 0) {
2025 void KItemListView::updateAlternateBackgrounds()
2027 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2028 while (it
.hasNext()) {
2030 updateAlternateBackgroundForWidget(it
.value());
2034 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2036 bool enabled
= useAlternateBackgrounds();
2038 const int index
= widget
->index();
2039 enabled
= (index
& 0x1) > 0;
2041 const int groupIndex
= groupIndexForItem(index
);
2042 if (groupIndex
>= 0) {
2043 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2044 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2045 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2046 enabled
= (relativeIndex
& 0x1) > 0;
2050 widget
->setAlternateBackground(enabled
);
2053 bool KItemListView::useAlternateBackgrounds() const
2055 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2058 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2060 QElapsedTimer timer
;
2063 QHash
<QByteArray
, qreal
> widths
;
2065 // Calculate the minimum width for each column that is required
2066 // to show the headline unclipped.
2067 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2068 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2069 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2070 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2071 const QString headerText
= m_model
->roleDescription(visibleRole
);
2072 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2073 widths
.insert(visibleRole
, headerWidth
);
2076 // Calculate the preferred column withs for each item and ignore values
2077 // smaller than the width for showing the headline unclipped.
2078 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2079 int calculatedItemCount
= 0;
2080 bool maxTimeExceeded
= false;
2081 foreach (const KItemRange
& itemRange
, itemRanges
) {
2082 const int startIndex
= itemRange
.index
;
2083 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2085 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2086 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2087 qreal maxWidth
= widths
.value(visibleRole
, 0);
2088 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2089 maxWidth
= qMax(width
, maxWidth
);
2090 widths
.insert(visibleRole
, maxWidth
);
2093 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2094 // When having several thousands of items calculating the sizes can get
2095 // very expensive. We accept a possibly too small role-size in favour
2096 // of having no blocking user interface.
2097 maxTimeExceeded
= true;
2100 ++calculatedItemCount
;
2102 if (maxTimeExceeded
) {
2110 void KItemListView::applyColumnWidthsFromHeader()
2112 // Apply the new size to the layouter
2113 const qreal requiredWidth
= columnWidthsSum();
2114 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2115 m_itemSize
.height());
2116 m_layouter
->setItemSize(dynamicItemSize
);
2118 // Update the role sizes for all visible widgets
2119 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2120 while (it
.hasNext()) {
2122 updateWidgetColumnWidths(it
.value());
2126 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2128 foreach (const QByteArray
& role
, m_visibleRoles
) {
2129 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2133 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2135 Q_ASSERT(m_itemSize
.isEmpty());
2136 const int itemCount
= m_model
->count();
2137 int rangesItemCount
= 0;
2138 foreach (const KItemRange
& range
, itemRanges
) {
2139 rangesItemCount
+= range
.count
;
2142 if (itemCount
== rangesItemCount
) {
2143 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2144 foreach (const QByteArray
& role
, m_visibleRoles
) {
2145 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2148 // Only a sub range of the roles need to be determined.
2149 // The chances are good that the widths of the sub ranges
2150 // already fit into the available widths and hence no
2151 // expensive update might be required.
2152 bool changed
= false;
2154 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2155 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2156 while (it
.hasNext()) {
2158 const QByteArray
& role
= it
.key();
2159 const qreal updatedWidth
= it
.value();
2160 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2161 if (updatedWidth
> currentWidth
) {
2162 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2168 // All the updated sizes are smaller than the current sizes and no change
2169 // of the stretched roles-widths is required
2174 if (m_headerWidget
->automaticColumnResizing()) {
2175 applyAutomaticColumnWidths();
2179 void KItemListView::updatePreferredColumnWidths()
2182 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2186 void KItemListView::applyAutomaticColumnWidths()
2188 Q_ASSERT(m_itemSize
.isEmpty());
2189 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2190 if (m_visibleRoles
.isEmpty()) {
2194 // Calculate the maximum size of an item by considering the
2195 // visible role sizes and apply them to the layouter. If the
2196 // size does not use the available view-size the size of the
2197 // first role will get stretched.
2199 foreach (const QByteArray
& role
, m_visibleRoles
) {
2200 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2201 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2204 const QByteArray firstRole
= m_visibleRoles
.first();
2205 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2206 QSizeF dynamicItemSize
= m_itemSize
;
2208 qreal requiredWidth
= columnWidthsSum();
2209 const qreal availableWidth
= size().width();
2210 if (requiredWidth
< availableWidth
) {
2211 // Stretch the first column to use the whole remaining width
2212 firstColumnWidth
+= availableWidth
- requiredWidth
;
2213 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2214 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2215 // Shrink the first column to be able to show as much other
2216 // columns as possible
2217 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2219 // TODO: A proper calculation of the minimum width depends on the implementation
2220 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2222 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2223 if (shrinkedFirstColumnWidth
< minWidth
) {
2224 shrinkedFirstColumnWidth
= minWidth
;
2227 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2228 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2231 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2233 m_layouter
->setItemSize(dynamicItemSize
);
2235 // Update the role sizes for all visible widgets
2236 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2237 while (it
.hasNext()) {
2239 updateWidgetColumnWidths(it
.value());
2243 qreal
KItemListView::columnWidthsSum() const
2245 qreal widthsSum
= 0;
2246 foreach (const QByteArray
& role
, m_visibleRoles
) {
2247 widthsSum
+= m_headerWidget
->columnWidth(role
);
2252 QRectF
KItemListView::headerBoundaries() const
2254 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2257 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2258 const QSizeF
& newItemSize
,
2259 const QSizeF
& newItemMargin
) const
2261 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2265 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2266 const qreal itemWidth
= m_layouter
->itemSize().width();
2267 if (itemWidth
> 0) {
2268 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2269 newItemSize
.width(),
2270 newItemMargin
.width());
2271 if (m_model
->count() > newColumnCount
) {
2272 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2274 m_layouter
->itemMargin().width());
2275 return oldColumnCount
!= newColumnCount
;
2279 const qreal itemHeight
= m_layouter
->itemSize().height();
2280 if (itemHeight
> 0) {
2281 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2282 newItemSize
.height(),
2283 newItemMargin
.height());
2284 if (m_model
->count() > newRowCount
) {
2285 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2287 m_layouter
->itemMargin().height());
2288 return oldRowCount
!= newRowCount
;
2296 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2298 if (m_itemSize
.isEmpty()) {
2299 // We have only columns or only rows, but no grid: An animation is usually
2300 // welcome when inserting or removing items.
2301 return !supportsItemExpanding();
2304 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2308 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2309 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2310 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2311 // Only animate if up to 2/3 of a row or column are inserted or removed
2312 return changedItemCount
<= maximum
* 2 / 3;
2316 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2318 const QSizeF oldSize
= m_layouter
->size();
2320 m_layouter
->setSize(size
);
2321 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2322 m_layouter
->setSize(oldSize
);
2324 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2325 : maxOffset
> size
.width();
2328 int KItemListView::showDropIndicator(const QPointF
& pos
)
2330 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2331 while (it
.hasNext()) {
2333 const KItemListWidget
* widget
= it
.value();
2335 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2336 const QRectF rect
= itemRect(widget
->index());
2337 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2338 if (m_model
->supportsDropping(widget
->index())) {
2339 const int gap
= qMax(4, m_styleOption
.padding
);
2340 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2345 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2346 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2348 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2349 if (m_dropIndicator
!= draggingInsertIndicator
) {
2350 m_dropIndicator
= draggingInsertIndicator
;
2354 int index
= widget
->index();
2362 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2363 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2366 void KItemListView::hideDropIndicator()
2368 if (!m_dropIndicator
.isNull()) {
2369 m_dropIndicator
= QRectF();
2374 void KItemListView::updateGroupHeaderHeight()
2376 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2377 qreal groupHeaderMargin
= 0;
2379 if (scrollOrientation() == Qt::Horizontal
) {
2380 // The vertical margin above and below the header should be
2381 // equal to the horizontal margin, not the vertical margin
2382 // from m_styleOption.
2383 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2384 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2385 } else if (m_itemSize
.isEmpty()){
2386 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2387 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2389 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2390 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2392 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2393 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2395 updateVisibleGroupHeaders();
2398 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2400 if (!supportsItemExpanding() || !m_model
) {
2404 if (firstIndex
< 0 || lastIndex
< 0) {
2405 firstIndex
= m_layouter
->firstVisibleIndex();
2406 lastIndex
= m_layouter
->lastVisibleIndex();
2408 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2409 lastIndex
>= m_layouter
->firstVisibleIndex());
2410 if (!isRangeVisible
) {
2415 int previousParents
= 0;
2416 QBitArray previousSiblings
;
2418 // The rootIndex describes the first index where the siblings get
2419 // calculated from. For the calculation the upper most parent item
2420 // is required. For performance reasons it is checked first whether
2421 // the visible items before or after the current range already
2422 // contain a siblings information which can be used as base.
2423 int rootIndex
= firstIndex
;
2425 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2427 // There is no visible widget before the range, check whether there
2428 // is one after the range:
2429 widget
= m_visibleItems
.value(lastIndex
+ 1);
2431 // The sibling information of the widget may only be used if
2432 // all items of the range have the same number of parents.
2433 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2434 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2435 if (m_model
->expandedParentsCount(i
) != parents
) {
2444 // Performance optimization: Use the sibling information of the visible
2445 // widget beside the given range.
2446 previousSiblings
= widget
->siblingsInformation();
2447 if (previousSiblings
.isEmpty()) {
2450 previousParents
= previousSiblings
.count() - 1;
2451 previousSiblings
.truncate(previousParents
);
2453 // Potentially slow path: Go back to the upper most parent of firstIndex
2454 // to be able to calculate the initial value for the siblings.
2455 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2460 Q_ASSERT(previousParents
>= 0);
2461 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2462 // Update the parent-siblings in case if the current item represents
2463 // a child or an upper parent.
2464 const int currentParents
= m_model
->expandedParentsCount(i
);
2465 Q_ASSERT(currentParents
>= 0);
2466 if (previousParents
< currentParents
) {
2467 previousParents
= currentParents
;
2468 previousSiblings
.resize(currentParents
);
2469 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2470 } else if (previousParents
> currentParents
) {
2471 previousParents
= currentParents
;
2472 previousSiblings
.truncate(currentParents
);
2475 if (i
>= firstIndex
) {
2476 // The index represents a visible item. Apply the parent-siblings
2477 // and update the sibling of the current item.
2478 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2483 QBitArray siblings
= previousSiblings
;
2484 siblings
.resize(siblings
.count() + 1);
2485 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2487 widget
->setSiblingsInformation(siblings
);
2492 bool KItemListView::hasSiblingSuccessor(int index
) const
2494 bool hasSuccessor
= false;
2495 const int parentsCount
= m_model
->expandedParentsCount(index
);
2496 int successorIndex
= index
+ 1;
2498 // Search the next sibling
2499 const int itemCount
= m_model
->count();
2500 while (successorIndex
< itemCount
) {
2501 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2502 if (currentParentsCount
== parentsCount
) {
2503 hasSuccessor
= true;
2505 } else if (currentParentsCount
< parentsCount
) {
2511 if (m_grouped
&& hasSuccessor
) {
2512 // If the sibling is part of another group, don't mark it as
2513 // successor as the group header is between the sibling connections.
2514 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2515 if (m_layouter
->isFirstGroupItem(i
)) {
2516 hasSuccessor
= false;
2522 return hasSuccessor
;
2525 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2529 const int minSpeed
= 4;
2530 const int maxSpeed
= 128;
2531 const int speedLimiter
= 96;
2532 const int autoScrollBorder
= 64;
2534 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2535 // This assures that the autoscrolling speed grows gradually.
2536 const int incLimiter
= 1;
2538 if (pos
< autoScrollBorder
) {
2539 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2540 inc
= qMax(inc
, -maxSpeed
);
2541 inc
= qMax(inc
, oldInc
- incLimiter
);
2542 } else if (pos
> range
- autoScrollBorder
) {
2543 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2544 inc
= qMin(inc
, maxSpeed
);
2545 inc
= qMin(inc
, oldInc
+ incLimiter
);
2551 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2553 const qreal availableSize
= size
- itemMargin
;
2554 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2560 KItemListCreatorBase::~KItemListCreatorBase()
2562 qDeleteAll(m_recycleableWidgets
);
2563 qDeleteAll(m_createdWidgets
);
2566 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2568 m_createdWidgets
.insert(widget
);
2571 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2573 Q_ASSERT(m_createdWidgets
.contains(widget
));
2574 m_createdWidgets
.remove(widget
);
2576 if (m_recycleableWidgets
.count() < 100) {
2577 m_recycleableWidgets
.append(widget
);
2578 widget
->setVisible(false);
2584 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2586 if (m_recycleableWidgets
.isEmpty()) {
2590 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2591 m_createdWidgets
.insert(widget
);
2595 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2599 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2601 widget
->setParentItem(0);
2602 widget
->setOpacity(1.0);
2603 pushRecycleableWidget(widget
);
2606 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2610 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2612 header
->setOpacity(1.0);
2613 pushRecycleableWidget(header
);
2616 #include "kitemlistview.moc"