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 "kitemlistcontainer.h"
27 #include "kitemlistcontroller.h"
28 #include "kitemlistheader.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
36 #include "private/kitemlistviewanimation.h"
39 #include <QGraphicsSceneMouseEvent>
40 #include <QGraphicsView>
42 #include <QPropertyAnimation>
44 #include <QStyleOptionRubberBand>
47 #include "kitemlistviewaccessible.h"
50 // Time in ms until reaching the autoscroll margin triggers
51 // an initial autoscrolling
52 const int InitialAutoScrollDelay
= 700;
54 // Delay in ms for triggering the next autoscroll
55 const int RepeatingAutoScrollDelay
= 1000 / 60;
58 #ifndef QT_NO_ACCESSIBILITY
59 QAccessibleInterface
* accessibleInterfaceFactory(const QString
&key
, QObject
*object
)
63 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
64 return new KItemListContainerAccessible(container
);
65 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
66 return new KItemListViewAccessible(view
);
73 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
74 QGraphicsWidget(parent
),
75 m_enabledSelectionToggles(false),
77 m_supportsItemExpanding(false),
79 m_activeTransactions(0),
80 m_endTransactionAnimationHint(Animation
),
86 m_groupHeaderCreator(0),
91 m_sizeHintResolver(0),
96 m_oldMaximumScrollOffset(0),
98 m_oldMaximumItemOffset(0),
99 m_skipAutoScrollForRubberBand(false),
102 m_autoScrollIncrement(0),
103 m_autoScrollTimer(0),
108 setAcceptHoverEvents(true);
110 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
112 m_layouter
= new KItemListViewLayouter(this);
113 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
115 m_animation
= new KItemListViewAnimation(this);
116 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
117 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
119 m_layoutTimer
= new QTimer(this);
120 m_layoutTimer
->setInterval(300);
121 m_layoutTimer
->setSingleShot(true);
122 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
124 m_rubberBand
= new KItemListRubberBand(this);
125 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
127 m_headerWidget
= new KItemListHeaderWidget(this);
128 m_headerWidget
->setVisible(false);
130 m_header
= new KItemListHeader(this);
132 #ifndef QT_NO_ACCESSIBILITY
133 QAccessible::installFactory(accessibleInterfaceFactory
);
138 KItemListView::~KItemListView()
140 // The group headers are children of the widgets created by
141 // widgetCreator(). So it is mandatory to delete the group headers
143 delete m_groupHeaderCreator
;
144 m_groupHeaderCreator
= 0;
146 delete m_widgetCreator
;
149 delete m_sizeHintResolver
;
150 m_sizeHintResolver
= 0;
153 void KItemListView::setScrollOffset(qreal offset
)
159 const qreal previousOffset
= m_layouter
->scrollOffset();
160 if (offset
== previousOffset
) {
164 m_layouter
->setScrollOffset(offset
);
165 m_animation
->setScrollOffset(offset
);
167 // Don't check whether the m_layoutTimer is active: Changing the
168 // scroll offset must always trigger a synchronous layout, otherwise
169 // the smooth-scrolling might get jerky.
170 doLayout(NoAnimation
);
171 onScrollOffsetChanged(offset
, previousOffset
);
174 qreal
KItemListView::scrollOffset() const
176 return m_layouter
->scrollOffset();
179 qreal
KItemListView::maximumScrollOffset() const
181 return m_layouter
->maximumScrollOffset();
184 void KItemListView::setItemOffset(qreal offset
)
186 if (m_layouter
->itemOffset() == offset
) {
190 m_layouter
->setItemOffset(offset
);
191 if (m_headerWidget
->isVisible()) {
192 m_headerWidget
->setOffset(offset
);
195 // Don't check whether the m_layoutTimer is active: Changing the
196 // item offset must always trigger a synchronous layout, otherwise
197 // the smooth-scrolling might get jerky.
198 doLayout(NoAnimation
);
201 qreal
KItemListView::itemOffset() const
203 return m_layouter
->itemOffset();
206 qreal
KItemListView::maximumItemOffset() const
208 return m_layouter
->maximumItemOffset();
211 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
213 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
214 m_visibleRoles
= roles
;
215 onVisibleRolesChanged(roles
, previousRoles
);
217 m_sizeHintResolver
->clearCache();
218 m_layouter
->markAsDirty();
220 if (m_itemSize
.isEmpty()) {
221 m_headerWidget
->setColumns(roles
);
222 updatePreferredColumnWidths();
223 if (!m_headerWidget
->automaticColumnResizing()) {
224 // The column-width of new roles are still 0. Apply the preferred
225 // column-width as default with.
226 foreach (const QByteArray
& role
, m_visibleRoles
) {
227 if (m_headerWidget
->columnWidth(role
) == 0) {
228 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
229 m_headerWidget
->setColumnWidth(role
, width
);
233 applyColumnWidthsFromHeader();
237 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
238 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
239 (roles
.count() <= 1 && previousRoles
.count() > 1));
241 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
242 while (it
.hasNext()) {
244 KItemListWidget
* widget
= it
.value();
245 widget
->setVisibleRoles(roles
);
246 if (alternateBackgroundsChanged
) {
247 updateAlternateBackgroundForWidget(widget
);
251 doLayout(NoAnimation
);
254 QList
<QByteArray
> KItemListView::visibleRoles() const
256 return m_visibleRoles
;
259 void KItemListView::setAutoScroll(bool enabled
)
261 if (enabled
&& !m_autoScrollTimer
) {
262 m_autoScrollTimer
= new QTimer(this);
263 m_autoScrollTimer
->setSingleShot(true);
264 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
265 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
266 } else if (!enabled
&& m_autoScrollTimer
) {
267 delete m_autoScrollTimer
;
268 m_autoScrollTimer
= 0;
272 bool KItemListView::autoScroll() const
274 return m_autoScrollTimer
!= 0;
277 void KItemListView::setEnabledSelectionToggles(bool enabled
)
279 if (m_enabledSelectionToggles
!= enabled
) {
280 m_enabledSelectionToggles
= enabled
;
282 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
283 while (it
.hasNext()) {
285 it
.value()->setEnabledSelectionToggle(enabled
);
290 bool KItemListView::enabledSelectionToggles() const
292 return m_enabledSelectionToggles
;
295 KItemListController
* KItemListView::controller() const
300 KItemModelBase
* KItemListView::model() const
305 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
307 if (m_widgetCreator
) {
308 delete m_widgetCreator
;
310 m_widgetCreator
= widgetCreator
;
313 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
315 if (!m_widgetCreator
) {
316 m_widgetCreator
= defaultWidgetCreator();
318 return m_widgetCreator
;
321 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
323 if (m_groupHeaderCreator
) {
324 delete m_groupHeaderCreator
;
326 m_groupHeaderCreator
= groupHeaderCreator
;
329 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
331 if (!m_groupHeaderCreator
) {
332 m_groupHeaderCreator
= defaultGroupHeaderCreator();
334 return m_groupHeaderCreator
;
337 QSizeF
KItemListView::itemSize() const
342 const KItemListStyleOption
& KItemListView::styleOption() const
344 return m_styleOption
;
347 void KItemListView::setGeometry(const QRectF
& rect
)
349 QGraphicsWidget::setGeometry(rect
);
355 const QSizeF newSize
= rect
.size();
356 if (m_itemSize
.isEmpty()) {
357 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
358 if (m_headerWidget
->automaticColumnResizing()) {
359 applyAutomaticColumnWidths();
361 const qreal requiredWidth
= columnWidthsSum();
362 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
363 m_itemSize
.height());
364 m_layouter
->setItemSize(dynamicItemSize
);
367 // Triggering a synchronous layout is fine from a performance point of view,
368 // as with dynamic item sizes no moving animation must be done.
369 m_layouter
->setSize(newSize
);
370 doLayout(NoAnimation
);
372 const bool animate
= !changesItemGridLayout(newSize
,
373 m_layouter
->itemSize(),
374 m_layouter
->itemMargin());
375 m_layouter
->setSize(newSize
);
378 // Trigger an asynchronous relayout with m_layoutTimer to prevent
379 // performance bottlenecks. If the timer is exceeded, an animated layout
380 // will be triggered.
381 if (!m_layoutTimer
->isActive()) {
382 m_layoutTimer
->start();
385 m_layoutTimer
->stop();
386 doLayout(NoAnimation
);
391 qreal
KItemListView::verticalPageStep() const
393 qreal headerHeight
= 0;
394 if (m_headerWidget
->isVisible()) {
395 headerHeight
= m_headerWidget
->size().height();
397 return size().height() - headerHeight
;
400 int KItemListView::itemAt(const QPointF
& pos
) const
402 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
403 while (it
.hasNext()) {
406 const KItemListWidget
* widget
= it
.value();
407 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
408 if (widget
->contains(mappedPos
)) {
416 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
418 if (!m_enabledSelectionToggles
) {
422 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
424 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
425 if (!selectionToggleRect
.isEmpty()) {
426 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
427 return selectionToggleRect
.contains(mappedPos
);
433 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
435 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
437 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
438 if (!expansionToggleRect
.isEmpty()) {
439 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
440 return expansionToggleRect
.contains(mappedPos
);
446 int KItemListView::firstVisibleIndex() const
448 return m_layouter
->firstVisibleIndex();
451 int KItemListView::lastVisibleIndex() const
453 return m_layouter
->lastVisibleIndex();
456 QSizeF
KItemListView::itemSizeHint(int index
) const
458 return widgetCreator()->itemSizeHint(index
, this);
461 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
463 if (m_supportsItemExpanding
!= supportsExpanding
) {
464 m_supportsItemExpanding
= supportsExpanding
;
465 updateSiblingsInformation();
466 onSupportsItemExpandingChanged(supportsExpanding
);
470 bool KItemListView::supportsItemExpanding() const
472 return m_supportsItemExpanding
;
475 QRectF
KItemListView::itemRect(int index
) const
477 return m_layouter
->itemRect(index
);
480 QRectF
KItemListView::itemContextRect(int index
) const
484 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
486 contextRect
= widget
->iconRect() | widget
->textRect();
487 contextRect
.translate(itemRect(index
).topLeft());
493 void KItemListView::scrollToItem(int index
)
495 QRectF viewGeometry
= geometry();
496 if (m_headerWidget
->isVisible()) {
497 const qreal headerHeight
= m_headerWidget
->size().height();
498 viewGeometry
.adjust(0, headerHeight
, 0, 0);
500 const QRectF currentRect
= itemRect(index
);
502 if (!viewGeometry
.contains(currentRect
)) {
503 qreal newOffset
= scrollOffset();
504 if (scrollOrientation() == Qt::Vertical
) {
505 if (currentRect
.top() < viewGeometry
.top()) {
506 newOffset
+= currentRect
.top() - viewGeometry
.top();
507 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
508 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
511 if (currentRect
.left() < viewGeometry
.left()) {
512 newOffset
+= currentRect
.left() - viewGeometry
.left();
513 } else if (currentRect
.right() > viewGeometry
.right()) {
514 newOffset
+= currentRect
.right() - viewGeometry
.right();
518 if (newOffset
!= scrollOffset()) {
519 emit
scrollTo(newOffset
);
524 void KItemListView::beginTransaction()
526 ++m_activeTransactions
;
527 if (m_activeTransactions
== 1) {
528 onTransactionBegin();
532 void KItemListView::endTransaction()
534 --m_activeTransactions
;
535 if (m_activeTransactions
< 0) {
536 m_activeTransactions
= 0;
537 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
540 if (m_activeTransactions
== 0) {
542 doLayout(m_endTransactionAnimationHint
);
543 m_endTransactionAnimationHint
= Animation
;
547 bool KItemListView::isTransactionActive() const
549 return m_activeTransactions
> 0;
552 void KItemListView::setHeaderVisible(bool visible
)
554 if (visible
&& !m_headerWidget
->isVisible()) {
555 QStyleOptionHeader option
;
556 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
559 m_headerWidget
->setPos(0, 0);
560 m_headerWidget
->resize(size().width(), headerSize
.height());
561 m_headerWidget
->setModel(m_model
);
562 m_headerWidget
->setColumns(m_visibleRoles
);
563 m_headerWidget
->setZValue(1);
565 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
566 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
567 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
568 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
569 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
570 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
571 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
572 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
574 m_layouter
->setHeaderHeight(headerSize
.height());
575 m_headerWidget
->setVisible(true);
576 } else if (!visible
&& m_headerWidget
->isVisible()) {
577 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
578 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
579 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
580 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
581 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
582 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
583 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
584 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
586 m_layouter
->setHeaderHeight(0);
587 m_headerWidget
->setVisible(false);
591 bool KItemListView::isHeaderVisible() const
593 return m_headerWidget
->isVisible();
596 KItemListHeader
* KItemListView::header() const
601 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
605 if (indexes
.count() == 1) {
606 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
607 QGraphicsView
* graphicsView
= scene()->views()[0];
608 if (item
&& graphicsView
) {
609 pixmap
= item
->createDragPixmap(0, graphicsView
);
612 // TODO: Not implemented yet. Probably extend the interface
613 // from KItemListWidget::createDragPixmap() to return a pixmap
614 // that can be used for multiple indexes.
620 void KItemListView::editRole(int index
, const QByteArray
& role
)
622 KItemListWidget
* widget
= m_visibleItems
.value(index
);
623 if (!widget
|| m_editingRole
) {
627 m_editingRole
= true;
628 widget
->setEditedRole(role
);
630 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
631 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
632 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
633 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
636 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
638 QGraphicsWidget::paint(painter
, option
, widget
);
640 if (m_rubberBand
->isActive()) {
641 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
642 m_rubberBand
->endPosition()).normalized();
644 const QPointF topLeft
= rubberBandRect
.topLeft();
645 if (scrollOrientation() == Qt::Vertical
) {
646 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
648 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
651 QStyleOptionRubberBand opt
;
652 opt
.initFrom(widget
);
653 opt
.shape
= QRubberBand::Rectangle
;
655 opt
.rect
= rubberBandRect
.toRect();
656 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
659 if (!m_dropIndicator
.isEmpty()) {
660 const QRectF r
= m_dropIndicator
.toRect();
662 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
663 painter
->setPen(color
);
665 // TODO: The following implementation works only for a vertical scroll-orientation
666 // and assumes a height of the m_draggingInsertIndicator of 1.
667 Q_ASSERT(r
.height() == 1);
668 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
671 painter
->setPen(color
);
672 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
676 void KItemListView::setItemSize(const QSizeF
& size
)
678 const QSizeF previousSize
= m_itemSize
;
679 if (size
== previousSize
) {
683 // Skip animations when the number of rows or columns
684 // are changed in the grid layout. Although the animation
685 // engine can handle this usecase, it looks obtrusive.
686 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
688 m_layouter
->itemMargin());
690 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
691 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
692 (!m_itemSize
.isEmpty() && size
.isEmpty()));
696 if (alternateBackgroundsChanged
) {
697 // For an empty item size alternate backgrounds are drawn if more than
698 // one role is shown. Assure that the backgrounds for visible items are
699 // updated when changing the size in this context.
700 updateAlternateBackgrounds();
703 if (size
.isEmpty()) {
704 if (m_headerWidget
->automaticColumnResizing()) {
705 updatePreferredColumnWidths();
707 // Only apply the changed height and respect the header widths
709 const qreal currentWidth
= m_layouter
->itemSize().width();
710 const QSizeF
newSize(currentWidth
, size
.height());
711 m_layouter
->setItemSize(newSize
);
714 m_layouter
->setItemSize(size
);
717 m_sizeHintResolver
->clearCache();
718 doLayout(animate
? Animation
: NoAnimation
);
719 onItemSizeChanged(size
, previousSize
);
722 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
724 const KItemListStyleOption previousOption
= m_styleOption
;
725 m_styleOption
= option
;
728 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
729 if (margin
!= m_layouter
->itemMargin()) {
730 // Skip animations when the number of rows or columns
731 // are changed in the grid layout. Although the animation
732 // engine can handle this usecase, it looks obtrusive.
733 animate
= !changesItemGridLayout(m_layouter
->size(),
734 m_layouter
->itemSize(),
736 m_layouter
->setItemMargin(margin
);
740 updateGroupHeaderHeight();
743 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
744 // Animating a change of the maximum text size just results in expensive
745 // temporary eliding and clipping operations and does not look good visually.
749 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
750 while (it
.hasNext()) {
752 it
.value()->setStyleOption(option
);
755 m_sizeHintResolver
->clearCache();
756 m_layouter
->markAsDirty();
757 doLayout(animate
? Animation
: NoAnimation
);
759 if (m_itemSize
.isEmpty()) {
760 updatePreferredColumnWidths();
763 onStyleOptionChanged(option
, previousOption
);
766 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
768 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
769 if (orientation
== previousOrientation
) {
773 m_layouter
->setScrollOrientation(orientation
);
774 m_animation
->setScrollOrientation(orientation
);
775 m_sizeHintResolver
->clearCache();
778 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
779 while (it
.hasNext()) {
781 it
.value()->setScrollOrientation(orientation
);
783 updateGroupHeaderHeight();
787 doLayout(NoAnimation
);
789 onScrollOrientationChanged(orientation
, previousOrientation
);
790 emit
scrollOrientationChanged(orientation
, previousOrientation
);
793 Qt::Orientation
KItemListView::scrollOrientation() const
795 return m_layouter
->scrollOrientation();
798 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
803 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
808 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
813 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
815 Q_UNUSED(changedRoles
);
819 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
825 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
831 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
837 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
843 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
849 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
855 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
861 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
863 Q_UNUSED(supportsExpanding
);
866 void KItemListView::onTransactionBegin()
870 void KItemListView::onTransactionEnd()
874 bool KItemListView::event(QEvent
* event
)
876 // Forward all events to the controller and handle them there
877 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
881 return QGraphicsWidget::event(event
);
884 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
886 m_mousePos
= transform().map(event
->pos());
890 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
892 QGraphicsWidget::mouseMoveEvent(event
);
894 m_mousePos
= transform().map(event
->pos());
895 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
896 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
900 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
902 event
->setAccepted(true);
906 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
908 QGraphicsWidget::dragMoveEvent(event
);
910 m_mousePos
= transform().map(event
->pos());
911 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
912 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
916 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
918 QGraphicsWidget::dragLeaveEvent(event
);
919 setAutoScroll(false);
922 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
924 QGraphicsWidget::dropEvent(event
);
925 setAutoScroll(false);
928 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
930 return m_visibleItems
.values();
933 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
935 if (m_itemSize
.isEmpty()) {
936 updatePreferredColumnWidths(itemRanges
);
939 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
940 if (hasMultipleRanges
) {
944 m_layouter
->markAsDirty();
946 int previouslyInsertedCount
= 0;
947 foreach (const KItemRange
& range
, itemRanges
) {
948 // range.index is related to the model before anything has been inserted.
949 // As in each loop the current item-range gets inserted the index must
950 // be increased by the already previously inserted items.
951 const int index
= range
.index
+ previouslyInsertedCount
;
952 const int count
= range
.count
;
953 if (index
< 0 || count
<= 0) {
954 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
957 previouslyInsertedCount
+= count
;
959 m_sizeHintResolver
->itemsInserted(index
, count
);
961 // Determine which visible items must be moved
962 QList
<int> itemsToMove
;
963 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
964 while (it
.hasNext()) {
966 const int visibleItemIndex
= it
.key();
967 if (visibleItemIndex
>= index
) {
968 itemsToMove
.append(visibleItemIndex
);
972 // Update the indexes of all KItemListWidget instances that are located
973 // after the inserted items. It is important to adjust the indexes in the order
974 // from the highest index to the lowest index to prevent overlaps when setting the new index.
976 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
977 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
979 const int newIndex
= widget
->index() + count
;
980 if (hasMultipleRanges
) {
981 setWidgetIndex(widget
, newIndex
);
983 // Try to animate the moving of the item
984 moveWidgetToIndex(widget
, newIndex
);
988 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
989 // Check whether a scrollbar is required to show the inserted items. In this case
990 // the size of the layouter will be decreased before calling doLayout(): This prevents
991 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
992 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
993 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
994 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
995 if (decreaseLayouterSize
) {
996 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
997 QSizeF layouterSize
= m_layouter
->size();
998 if (verticalScrollOrientation
) {
999 layouterSize
.rwidth() -= scrollBarExtent
;
1001 layouterSize
.rheight() -= scrollBarExtent
;
1003 m_layouter
->setSize(layouterSize
);
1007 if (!hasMultipleRanges
) {
1008 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1009 updateSiblingsInformation();
1014 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1017 if (hasMultipleRanges
) {
1019 // Important: Don't read any m_layouter-property inside the for-loop in case if
1020 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1021 // updated in each loop-cycle and has only a consistent state after the loop.
1022 Q_ASSERT(m_layouter
->isDirty());
1024 m_endTransactionAnimationHint
= NoAnimation
;
1027 updateSiblingsInformation();
1030 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1031 // In case if items of the same group have been inserted before an item that
1032 // currently represents the first item of the group, the group header of
1033 // this item must be removed.
1034 updateVisibleGroupHeaders();
1037 if (useAlternateBackgrounds()) {
1038 updateAlternateBackgrounds();
1042 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1044 if (m_itemSize
.isEmpty()) {
1045 // Don't pass the item-range: The preferred column-widths of
1046 // all items must be adjusted when removing items.
1047 updatePreferredColumnWidths();
1050 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1051 if (hasMultipleRanges
) {
1055 m_layouter
->markAsDirty();
1057 int removedItemsCount
= 0;
1058 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1059 removedItemsCount
+= itemRanges
[i
].count
;
1062 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1063 const KItemRange
& range
= itemRanges
[i
];
1064 const int index
= range
.index
;
1065 const int count
= range
.count
;
1066 if (index
< 0 || count
<= 0) {
1067 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1071 m_sizeHintResolver
->itemsRemoved(index
, count
);
1073 const int firstRemovedIndex
= index
;
1074 const int lastRemovedIndex
= index
+ count
- 1;
1075 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1076 removedItemsCount
-= count
;
1078 // Remove all KItemListWidget instances that got deleted
1079 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1080 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1085 m_animation
->stop(widget
);
1086 // Stopping the animation might lead to recycling the widget if
1087 // it is invisible (see slotAnimationFinished()).
1088 // Check again whether it is still visible:
1089 if (!m_visibleItems
.contains(i
)) {
1093 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1094 // Remove the widget without animation
1095 recycleWidget(widget
);
1097 // Animate the removing of the items. Special case: When removing an item there
1098 // is no valid model index available anymore. For the
1099 // remove-animation the item gets removed from m_visibleItems but the widget
1100 // will stay alive until the animation has been finished and will
1101 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1102 m_visibleItems
.remove(i
);
1103 widget
->setIndex(-1);
1104 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1108 // Update the indexes of all KItemListWidget instances that are located
1109 // after the deleted items
1110 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1111 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1113 const int newIndex
= i
- count
;
1114 if (hasMultipleRanges
) {
1115 setWidgetIndex(widget
, newIndex
);
1117 // Try to animate the moving of the item
1118 moveWidgetToIndex(widget
, newIndex
);
1123 if (!hasMultipleRanges
) {
1124 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1125 // assumes an updated geometry. If items are removed during an active transaction,
1126 // the transaction will be temporary deactivated so that doLayout() triggers a
1127 // geometry update if necessary.
1128 const int activeTransactions
= m_activeTransactions
;
1129 m_activeTransactions
= 0;
1130 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1131 m_activeTransactions
= activeTransactions
;
1132 updateSiblingsInformation();
1137 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1140 if (hasMultipleRanges
) {
1142 // Important: Don't read any m_layouter-property inside the for-loop in case if
1143 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1144 // updated in each loop-cycle and has only a consistent state after the loop.
1145 Q_ASSERT(m_layouter
->isDirty());
1147 m_endTransactionAnimationHint
= NoAnimation
;
1149 updateSiblingsInformation();
1152 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1153 // In case if the first item of a group has been removed, the group header
1154 // must be applied to the next visible item.
1155 updateVisibleGroupHeaders();
1158 if (useAlternateBackgrounds()) {
1159 updateAlternateBackgrounds();
1163 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1165 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1166 m_layouter
->markAsDirty();
1169 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1172 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1173 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1175 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1176 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1178 updateWidgetProperties(widget
, index
);
1179 initializeItemListWidget(widget
);
1183 doLayout(NoAnimation
);
1184 updateSiblingsInformation();
1187 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1188 const QSet
<QByteArray
>& roles
)
1190 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1191 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1192 updatePreferredColumnWidths(itemRanges
);
1195 foreach (const KItemRange
& itemRange
, itemRanges
) {
1196 const int index
= itemRange
.index
;
1197 const int count
= itemRange
.count
;
1199 if (updateSizeHints
) {
1200 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1201 m_layouter
->markAsDirty();
1203 if (!m_layoutTimer
->isActive()) {
1204 m_layoutTimer
->start();
1208 // Apply the changed roles to the visible item-widgets
1209 const int lastIndex
= index
+ count
- 1;
1210 for (int i
= index
; i
<= lastIndex
; ++i
) {
1211 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1213 widget
->setData(m_model
->data(i
), roles
);
1217 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1218 // The sort-role has been changed which might result
1219 // in modified group headers
1220 updateVisibleGroupHeaders();
1221 doLayout(NoAnimation
);
1224 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1227 void KItemListView::slotGroupedSortingChanged(bool current
)
1229 m_grouped
= current
;
1230 m_layouter
->markAsDirty();
1233 updateGroupHeaderHeight();
1235 // Clear all visible headers
1236 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1237 while (it
.hasNext()) {
1239 recycleGroupHeaderForWidget(it
.key());
1241 Q_ASSERT(m_visibleGroups
.isEmpty());
1244 if (useAlternateBackgrounds()) {
1245 // Changing the group mode requires to update the alternate backgrounds
1246 // as with the enabled group mode the altering is done on base of the first
1248 updateAlternateBackgrounds();
1250 updateSiblingsInformation();
1251 doLayout(NoAnimation
);
1254 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1259 updateVisibleGroupHeaders();
1260 doLayout(NoAnimation
);
1264 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1269 updateVisibleGroupHeaders();
1270 doLayout(NoAnimation
);
1274 void KItemListView::slotCurrentChanged(int current
, int previous
)
1278 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1279 if (previousWidget
) {
1280 previousWidget
->setCurrent(false);
1283 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1284 if (currentWidget
) {
1285 currentWidget
->setCurrent(true);
1287 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1290 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1294 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1295 while (it
.hasNext()) {
1297 const int index
= it
.key();
1298 KItemListWidget
* widget
= it
.value();
1299 widget
->setSelected(current
.contains(index
));
1303 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1304 KItemListViewAnimation::AnimationType type
)
1306 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1307 Q_ASSERT(itemListWidget
);
1310 case KItemListViewAnimation::DeleteAnimation
: {
1311 // As we recycle the widget in this case it is important to assure that no
1312 // other animation has been started. This is a convention in KItemListView and
1313 // not a requirement defined by KItemListViewAnimation.
1314 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1316 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1317 // by m_visibleWidgets and must be deleted manually after the animation has
1319 recycleGroupHeaderForWidget(itemListWidget
);
1320 widgetCreator()->recycle(itemListWidget
);
1324 case KItemListViewAnimation::CreateAnimation
:
1325 case KItemListViewAnimation::MovingAnimation
:
1326 case KItemListViewAnimation::ResizeAnimation
: {
1327 const int index
= itemListWidget
->index();
1328 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1329 (index
> m_layouter
->lastVisibleIndex());
1330 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1331 recycleWidget(itemListWidget
);
1340 void KItemListView::slotLayoutTimerFinished()
1342 m_layouter
->setSize(geometry().size());
1343 doLayout(Animation
);
1346 void KItemListView::slotRubberBandPosChanged()
1351 void KItemListView::slotRubberBandActivationChanged(bool active
)
1354 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1355 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1356 m_skipAutoScrollForRubberBand
= true;
1358 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1359 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1360 m_skipAutoScrollForRubberBand
= false;
1366 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1368 qreal previousWidth
)
1371 Q_UNUSED(currentWidth
);
1372 Q_UNUSED(previousWidth
);
1374 m_headerWidget
->setAutomaticColumnResizing(false);
1375 applyColumnWidthsFromHeader();
1376 doLayout(NoAnimation
);
1379 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1383 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1385 const QList
<QByteArray
> previous
= m_visibleRoles
;
1387 QList
<QByteArray
> current
= m_visibleRoles
;
1388 current
.removeAt(previousIndex
);
1389 current
.insert(currentIndex
, role
);
1391 setVisibleRoles(current
);
1393 emit
visibleRolesChanged(current
, previous
);
1396 void KItemListView::triggerAutoScrolling()
1398 if (!m_autoScrollTimer
) {
1403 int visibleSize
= 0;
1404 if (scrollOrientation() == Qt::Vertical
) {
1405 pos
= m_mousePos
.y();
1406 visibleSize
= size().height();
1408 pos
= m_mousePos
.x();
1409 visibleSize
= size().width();
1412 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1413 m_autoScrollIncrement
= 0;
1416 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1417 if (m_autoScrollIncrement
== 0) {
1418 // The mouse position is not above an autoscroll margin (the autoscroll timer
1419 // will be restarted in mouseMoveEvent())
1420 m_autoScrollTimer
->stop();
1424 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1425 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1426 // if the direction of the rubberband is similar to the autoscroll direction. This
1427 // prevents that starting to create a rubberband within the autoscroll margins starts
1428 // an autoscrolling.
1430 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1431 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1432 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1433 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1434 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1435 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1436 // been moved up although the autoscroll direction might be down)
1437 m_autoScrollTimer
->stop();
1442 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1443 // the autoscrolling may not get skipped anymore until a new rubberband is created
1444 m_skipAutoScrollForRubberBand
= false;
1446 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1447 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1448 setScrollOffset(newScrollOffset
);
1450 // Trigger the autoscroll timer which will periodically call
1451 // triggerAutoScrolling()
1452 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1455 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1457 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1459 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1460 Q_ASSERT(groupHeader
);
1461 updateGroupHeaderLayout(widget
);
1464 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1466 disconnectRoleEditingSignals(index
);
1468 emit
roleEditingCanceled(index
, role
, value
);
1469 m_editingRole
= false;
1472 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1474 disconnectRoleEditingSignals(index
);
1476 emit
roleEditingFinished(index
, role
, value
);
1477 m_editingRole
= false;
1480 void KItemListView::setController(KItemListController
* controller
)
1482 if (m_controller
!= controller
) {
1483 KItemListController
* previous
= m_controller
;
1485 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1486 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1487 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1490 m_controller
= controller
;
1493 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1494 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1495 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1498 onControllerChanged(controller
, previous
);
1502 void KItemListView::setModel(KItemModelBase
* model
)
1504 if (m_model
== model
) {
1508 KItemModelBase
* previous
= m_model
;
1511 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1512 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1513 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1514 this, SLOT(slotItemsInserted(KItemRangeList
)));
1515 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1516 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1517 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1518 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1519 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1520 this, SLOT(slotGroupedSortingChanged(bool)));
1521 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1522 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1523 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1524 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1527 m_sizeHintResolver
->clearCache();
1530 m_layouter
->setModel(model
);
1531 m_grouped
= model
->groupedSorting();
1534 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1535 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1536 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1537 this, SLOT(slotItemsInserted(KItemRangeList
)));
1538 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1539 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1540 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1541 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1542 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1543 this, SLOT(slotGroupedSortingChanged(bool)));
1544 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1545 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1546 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1547 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1549 const int itemCount
= m_model
->count();
1550 if (itemCount
> 0) {
1551 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1552 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1556 onModelChanged(model
, previous
);
1559 KItemListRubberBand
* KItemListView::rubberBand() const
1561 return m_rubberBand
;
1564 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1566 if (m_layoutTimer
->isActive()) {
1567 m_layoutTimer
->stop();
1570 if (m_activeTransactions
> 0) {
1571 if (hint
== NoAnimation
) {
1572 // As soon as at least one property change should be done without animation,
1573 // the whole transaction will be marked as not animated.
1574 m_endTransactionAnimationHint
= NoAnimation
;
1579 if (!m_model
|| m_model
->count() < 0) {
1583 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1584 if (firstVisibleIndex
< 0) {
1585 emitOffsetChanges();
1589 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1590 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1591 // is still shown if the maximum offset got decreased.
1592 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1593 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1594 if (scrollOffset() > maxOffsetToShowFullRange
) {
1595 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1596 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1599 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1601 int firstSibblingIndex
= -1;
1602 int lastSibblingIndex
= -1;
1603 const bool supportsExpanding
= supportsItemExpanding();
1605 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1607 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1608 // instances from invisible items are reused. If no reusable items are
1609 // found then new KItemListWidget instances get created.
1610 const bool animate
= (hint
== Animation
);
1611 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1612 bool applyNewPos
= true;
1613 bool wasHidden
= false;
1615 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1616 const QPointF newPos
= itemBounds
.topLeft();
1617 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1620 if (!reusableItems
.isEmpty()) {
1621 // Reuse a KItemListWidget instance from an invisible item
1622 const int oldIndex
= reusableItems
.takeLast();
1623 widget
= m_visibleItems
.value(oldIndex
);
1624 setWidgetIndex(widget
, i
);
1625 updateWidgetProperties(widget
, i
);
1626 initializeItemListWidget(widget
);
1628 // No reusable KItemListWidget instance is available, create a new one
1629 widget
= createWidget(i
);
1631 widget
->resize(itemBounds
.size());
1633 if (animate
&& changedCount
< 0) {
1634 // Items have been deleted, move the created item to the
1635 // imaginary old position. They will get animated to the new position
1637 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1638 if (itemRect
.isEmpty()) {
1639 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1640 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1641 widget
->setPos(invisibleOldPos
);
1643 widget
->setPos(itemRect
.topLeft());
1645 applyNewPos
= false;
1648 if (supportsExpanding
&& changedCount
== 0) {
1649 if (firstSibblingIndex
< 0) {
1650 firstSibblingIndex
= i
;
1652 lastSibblingIndex
= i
;
1657 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1658 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1659 applyNewPos
= false;
1662 const bool itemsRemoved
= (changedCount
< 0);
1663 const bool itemsInserted
= (changedCount
> 0);
1664 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1665 // The item is located after the removed items. Animate the moving of the position.
1666 applyNewPos
= !moveWidget(widget
, newPos
);
1667 } else if (itemsInserted
&& i
>= changedIndex
) {
1668 // The item is located after the first inserted item
1669 if (i
<= changedIndex
+ changedCount
- 1) {
1670 // The item is an inserted item. Animate the appearing of the item.
1671 // For performance reasons no animation is done when changedCount is equal
1672 // to all available items.
1673 if (changedCount
< m_model
->count()) {
1674 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1676 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1677 // The item was already there before, so animate the moving of the position.
1678 // No moving animation is done if the item is animated by a create animation: This
1679 // prevents a "move animation mess" when inserting several ranges in parallel.
1680 applyNewPos
= !moveWidget(widget
, newPos
);
1682 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1683 // The size of the view might have been changed. Animate the moving of the position.
1684 applyNewPos
= !moveWidget(widget
, newPos
);
1687 m_animation
->stop(widget
);
1691 widget
->setPos(newPos
);
1694 Q_ASSERT(widget
->index() == i
);
1695 widget
->setVisible(true);
1697 if (widget
->size() != itemBounds
.size()) {
1698 // Resize the widget for the item to the changed size.
1700 // If a dynamic item size is used then no animation is done in the direction
1701 // of the dynamic size.
1702 if (m_itemSize
.width() <= 0) {
1703 // The width is dynamic, apply the new width without animation.
1704 widget
->resize(itemBounds
.width(), widget
->size().height());
1705 } else if (m_itemSize
.height() <= 0) {
1706 // The height is dynamic, apply the new height without animation.
1707 widget
->resize(widget
->size().width(), itemBounds
.height());
1709 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1711 widget
->resize(itemBounds
.size());
1715 // Updating the cell-information must be done as last step: The decision whether the
1716 // moving-animation should be started at all is based on the previous cell-information.
1717 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1718 m_visibleCells
.insert(i
, cell
);
1721 // Delete invisible KItemListWidget instances that have not been reused
1722 foreach (int index
, reusableItems
) {
1723 recycleWidget(m_visibleItems
.value(index
));
1726 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1727 Q_ASSERT(lastSibblingIndex
>= 0);
1728 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1732 // Update the layout of all visible group headers
1733 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1734 while (it
.hasNext()) {
1736 updateGroupHeaderLayout(it
.key());
1740 emitOffsetChanges();
1743 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1744 int lastVisibleIndex
,
1745 LayoutAnimationHint hint
)
1747 // Determine all items that are completely invisible and might be
1748 // reused for items that just got (at least partly) visible. If the
1749 // animation hint is set to 'Animation' items that do e.g. an animated
1750 // moving of their position are not marked as invisible: This assures
1751 // that a scrolling inside the view can be done without breaking an animation.
1755 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1756 while (it
.hasNext()) {
1759 KItemListWidget
* widget
= it
.value();
1760 const int index
= widget
->index();
1761 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1764 if (m_animation
->isStarted(widget
)) {
1765 if (hint
== NoAnimation
) {
1766 // Stopping the animation will call KItemListView::slotAnimationFinished()
1767 // and the widget will be recycled if necessary there.
1768 m_animation
->stop(widget
);
1771 widget
->setVisible(false);
1772 items
.append(index
);
1775 recycleGroupHeaderForWidget(widget
);
1784 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1786 if (widget
->pos() == newPos
) {
1790 bool startMovingAnim
= false;
1792 if (m_itemSize
.isEmpty()) {
1793 // The items are not aligned in a grid but either as columns or rows.
1794 startMovingAnim
= true;
1796 // When having a grid the moving-animation should only be started, if it is done within
1797 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1798 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1799 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1800 const int index
= widget
->index();
1801 const Cell cell
= m_visibleCells
.value(index
);
1802 if (cell
.column
>= 0 && cell
.row
>= 0) {
1803 if (scrollOrientation() == Qt::Vertical
) {
1804 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1806 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1811 if (startMovingAnim
) {
1812 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1816 m_animation
->stop(widget
);
1817 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1821 void KItemListView::emitOffsetChanges()
1823 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1824 if (m_oldScrollOffset
!= newScrollOffset
) {
1825 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1826 m_oldScrollOffset
= newScrollOffset
;
1829 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1830 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1831 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1832 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1835 const qreal newItemOffset
= m_layouter
->itemOffset();
1836 if (m_oldItemOffset
!= newItemOffset
) {
1837 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1838 m_oldItemOffset
= newItemOffset
;
1841 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1842 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1843 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1844 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1848 KItemListWidget
* KItemListView::createWidget(int index
)
1850 KItemListWidget
* widget
= widgetCreator()->create(this);
1851 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1853 m_visibleItems
.insert(index
, widget
);
1854 m_visibleCells
.insert(index
, Cell());
1855 updateWidgetProperties(widget
, index
);
1856 initializeItemListWidget(widget
);
1860 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1863 recycleGroupHeaderForWidget(widget
);
1866 const int index
= widget
->index();
1867 m_visibleItems
.remove(index
);
1868 m_visibleCells
.remove(index
);
1870 widgetCreator()->recycle(widget
);
1873 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1875 const int oldIndex
= widget
->index();
1876 m_visibleItems
.remove(oldIndex
);
1877 m_visibleCells
.remove(oldIndex
);
1879 m_visibleItems
.insert(index
, widget
);
1880 m_visibleCells
.insert(index
, Cell());
1882 widget
->setIndex(index
);
1885 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1887 const int oldIndex
= widget
->index();
1888 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1890 setWidgetIndex(widget
, index
);
1892 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1893 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1894 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1895 (!vertical
&& oldCell
.column
== newCell
.column
);
1897 m_visibleCells
.insert(index
, newCell
);
1901 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1904 case LayouterSize
: m_layouter
->setSize(size
); break;
1905 case ItemSize
: m_layouter
->setItemSize(size
); break;
1910 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1912 widget
->setVisibleRoles(m_visibleRoles
);
1913 updateWidgetColumnWidths(widget
);
1914 widget
->setStyleOption(m_styleOption
);
1916 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1917 widget
->setCurrent(index
== selectionManager
->currentItem());
1918 widget
->setSelected(selectionManager
->isSelected(index
));
1919 widget
->setHovered(false);
1920 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1921 widget
->setIndex(index
);
1922 widget
->setData(m_model
->data(index
));
1923 widget
->setSiblingsInformation(QBitArray());
1924 updateAlternateBackgroundForWidget(widget
);
1927 updateGroupHeaderForWidget(widget
);
1931 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1933 Q_ASSERT(m_grouped
);
1935 const int index
= widget
->index();
1936 if (!m_layouter
->isFirstGroupItem(index
)) {
1937 // The widget does not represent the first item of a group
1938 // and hence requires no header
1939 recycleGroupHeaderForWidget(widget
);
1943 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1944 if (groups
.isEmpty() || !groupHeaderCreator()) {
1948 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1950 groupHeader
= groupHeaderCreator()->create(this);
1951 groupHeader
->setParentItem(widget
);
1952 m_visibleGroups
.insert(widget
, groupHeader
);
1953 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1955 Q_ASSERT(groupHeader
->parentItem() == widget
);
1957 const int groupIndex
= groupIndexForItem(index
);
1958 Q_ASSERT(groupIndex
>= 0);
1959 groupHeader
->setData(groups
.at(groupIndex
).second
);
1960 groupHeader
->setRole(model()->sortRole());
1961 groupHeader
->setStyleOption(m_styleOption
);
1962 groupHeader
->setScrollOrientation(scrollOrientation());
1963 groupHeader
->setItemIndex(index
);
1965 groupHeader
->show();
1968 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1970 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1971 Q_ASSERT(groupHeader
);
1973 const int index
= widget
->index();
1974 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1975 const QRectF itemRect
= m_layouter
->itemRect(index
);
1977 // The group-header is a child of the itemlist widget. Translate the
1978 // group header position to the relative position.
1979 if (scrollOrientation() == Qt::Vertical
) {
1980 // In the vertical scroll orientation the group header should always span
1981 // the whole width no matter which temporary position the parent widget
1982 // has. In this case the x-position and width will be adjusted manually.
1983 const qreal x
= -widget
->x() - itemOffset();
1984 const qreal width
= maximumItemOffset();
1985 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1986 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1988 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1989 groupHeader
->resize(groupHeaderRect
.size());
1993 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1995 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1997 header
->setParentItem(0);
1998 groupHeaderCreator()->recycle(header
);
1999 m_visibleGroups
.remove(widget
);
2000 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2004 void KItemListView::updateVisibleGroupHeaders()
2006 Q_ASSERT(m_grouped
);
2007 m_layouter
->markAsDirty();
2009 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2010 while (it
.hasNext()) {
2012 updateGroupHeaderForWidget(it
.value());
2016 int KItemListView::groupIndexForItem(int index
) const
2018 Q_ASSERT(m_grouped
);
2020 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2021 if (groups
.isEmpty()) {
2026 int max
= groups
.count() - 1;
2029 mid
= (min
+ max
) / 2;
2030 if (index
> groups
[mid
].first
) {
2035 } while (groups
[mid
].first
!= index
&& min
<= max
);
2038 while (groups
[mid
].first
> index
&& mid
> 0) {
2046 void KItemListView::updateAlternateBackgrounds()
2048 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2049 while (it
.hasNext()) {
2051 updateAlternateBackgroundForWidget(it
.value());
2055 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2057 bool enabled
= useAlternateBackgrounds();
2059 const int index
= widget
->index();
2060 enabled
= (index
& 0x1) > 0;
2062 const int groupIndex
= groupIndexForItem(index
);
2063 if (groupIndex
>= 0) {
2064 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2065 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2066 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2067 enabled
= (relativeIndex
& 0x1) > 0;
2071 widget
->setAlternateBackground(enabled
);
2074 bool KItemListView::useAlternateBackgrounds() const
2076 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2079 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2081 QElapsedTimer timer
;
2084 QHash
<QByteArray
, qreal
> widths
;
2086 // Calculate the minimum width for each column that is required
2087 // to show the headline unclipped.
2088 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2089 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2090 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2091 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2092 const QString headerText
= m_model
->roleDescription(visibleRole
);
2093 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2094 widths
.insert(visibleRole
, headerWidth
);
2097 // Calculate the preferred column withs for each item and ignore values
2098 // smaller than the width for showing the headline unclipped.
2099 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2100 int calculatedItemCount
= 0;
2101 bool maxTimeExceeded
= false;
2102 foreach (const KItemRange
& itemRange
, itemRanges
) {
2103 const int startIndex
= itemRange
.index
;
2104 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2106 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2107 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2108 qreal maxWidth
= widths
.value(visibleRole
, 0);
2109 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2110 maxWidth
= qMax(width
, maxWidth
);
2111 widths
.insert(visibleRole
, maxWidth
);
2114 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2115 // When having several thousands of items calculating the sizes can get
2116 // very expensive. We accept a possibly too small role-size in favour
2117 // of having no blocking user interface.
2118 maxTimeExceeded
= true;
2121 ++calculatedItemCount
;
2123 if (maxTimeExceeded
) {
2131 void KItemListView::applyColumnWidthsFromHeader()
2133 // Apply the new size to the layouter
2134 const qreal requiredWidth
= columnWidthsSum();
2135 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2136 m_itemSize
.height());
2137 m_layouter
->setItemSize(dynamicItemSize
);
2139 // Update the role sizes for all visible widgets
2140 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2141 while (it
.hasNext()) {
2143 updateWidgetColumnWidths(it
.value());
2147 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2149 foreach (const QByteArray
& role
, m_visibleRoles
) {
2150 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2154 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2156 Q_ASSERT(m_itemSize
.isEmpty());
2157 const int itemCount
= m_model
->count();
2158 int rangesItemCount
= 0;
2159 foreach (const KItemRange
& range
, itemRanges
) {
2160 rangesItemCount
+= range
.count
;
2163 if (itemCount
== rangesItemCount
) {
2164 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2165 foreach (const QByteArray
& role
, m_visibleRoles
) {
2166 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2169 // Only a sub range of the roles need to be determined.
2170 // The chances are good that the widths of the sub ranges
2171 // already fit into the available widths and hence no
2172 // expensive update might be required.
2173 bool changed
= false;
2175 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2176 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2177 while (it
.hasNext()) {
2179 const QByteArray
& role
= it
.key();
2180 const qreal updatedWidth
= it
.value();
2181 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2182 if (updatedWidth
> currentWidth
) {
2183 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2189 // All the updated sizes are smaller than the current sizes and no change
2190 // of the stretched roles-widths is required
2195 if (m_headerWidget
->automaticColumnResizing()) {
2196 applyAutomaticColumnWidths();
2200 void KItemListView::updatePreferredColumnWidths()
2203 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2207 void KItemListView::applyAutomaticColumnWidths()
2209 Q_ASSERT(m_itemSize
.isEmpty());
2210 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2211 if (m_visibleRoles
.isEmpty()) {
2215 // Calculate the maximum size of an item by considering the
2216 // visible role sizes and apply them to the layouter. If the
2217 // size does not use the available view-size the size of the
2218 // first role will get stretched.
2220 foreach (const QByteArray
& role
, m_visibleRoles
) {
2221 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2222 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2225 const QByteArray firstRole
= m_visibleRoles
.first();
2226 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2227 QSizeF dynamicItemSize
= m_itemSize
;
2229 qreal requiredWidth
= columnWidthsSum();
2230 const qreal availableWidth
= size().width();
2231 if (requiredWidth
< availableWidth
) {
2232 // Stretch the first column to use the whole remaining width
2233 firstColumnWidth
+= availableWidth
- requiredWidth
;
2234 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2235 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2236 // Shrink the first column to be able to show as much other
2237 // columns as possible
2238 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2240 // TODO: A proper calculation of the minimum width depends on the implementation
2241 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2243 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2244 if (shrinkedFirstColumnWidth
< minWidth
) {
2245 shrinkedFirstColumnWidth
= minWidth
;
2248 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2249 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2252 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2254 m_layouter
->setItemSize(dynamicItemSize
);
2256 // Update the role sizes for all visible widgets
2257 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2258 while (it
.hasNext()) {
2260 updateWidgetColumnWidths(it
.value());
2264 qreal
KItemListView::columnWidthsSum() const
2266 qreal widthsSum
= 0;
2267 foreach (const QByteArray
& role
, m_visibleRoles
) {
2268 widthsSum
+= m_headerWidget
->columnWidth(role
);
2273 QRectF
KItemListView::headerBoundaries() const
2275 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2278 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2279 const QSizeF
& newItemSize
,
2280 const QSizeF
& newItemMargin
) const
2282 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2286 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2287 const qreal itemWidth
= m_layouter
->itemSize().width();
2288 if (itemWidth
> 0) {
2289 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2290 newItemSize
.width(),
2291 newItemMargin
.width());
2292 if (m_model
->count() > newColumnCount
) {
2293 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2295 m_layouter
->itemMargin().width());
2296 return oldColumnCount
!= newColumnCount
;
2300 const qreal itemHeight
= m_layouter
->itemSize().height();
2301 if (itemHeight
> 0) {
2302 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2303 newItemSize
.height(),
2304 newItemMargin
.height());
2305 if (m_model
->count() > newRowCount
) {
2306 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2308 m_layouter
->itemMargin().height());
2309 return oldRowCount
!= newRowCount
;
2317 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2319 if (m_itemSize
.isEmpty()) {
2320 // We have only columns or only rows, but no grid: An animation is usually
2321 // welcome when inserting or removing items.
2322 return !supportsItemExpanding();
2325 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2329 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2330 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2331 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2332 // Only animate if up to 2/3 of a row or column are inserted or removed
2333 return changedItemCount
<= maximum
* 2 / 3;
2337 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2339 const QSizeF oldSize
= m_layouter
->size();
2341 m_layouter
->setSize(size
);
2342 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2343 m_layouter
->setSize(oldSize
);
2345 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2346 : maxOffset
> size
.width();
2349 int KItemListView::showDropIndicator(const QPointF
& pos
)
2351 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2352 while (it
.hasNext()) {
2354 const KItemListWidget
* widget
= it
.value();
2356 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2357 const QRectF rect
= itemRect(widget
->index());
2358 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2359 if (m_model
->supportsDropping(widget
->index())) {
2360 const int gap
= qMax(4, m_styleOption
.padding
);
2361 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2366 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2367 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2369 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2370 if (m_dropIndicator
!= draggingInsertIndicator
) {
2371 m_dropIndicator
= draggingInsertIndicator
;
2375 int index
= widget
->index();
2383 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2384 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2387 void KItemListView::hideDropIndicator()
2389 if (!m_dropIndicator
.isNull()) {
2390 m_dropIndicator
= QRectF();
2395 void KItemListView::updateGroupHeaderHeight()
2397 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2398 qreal groupHeaderMargin
= 0;
2400 if (scrollOrientation() == Qt::Horizontal
) {
2401 // The vertical margin above and below the header should be
2402 // equal to the horizontal margin, not the vertical margin
2403 // from m_styleOption.
2404 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2405 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2406 } else if (m_itemSize
.isEmpty()){
2407 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2408 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2410 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2411 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2413 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2414 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2416 updateVisibleGroupHeaders();
2419 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2421 if (!supportsItemExpanding() || !m_model
) {
2425 if (firstIndex
< 0 || lastIndex
< 0) {
2426 firstIndex
= m_layouter
->firstVisibleIndex();
2427 lastIndex
= m_layouter
->lastVisibleIndex();
2429 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2430 lastIndex
>= m_layouter
->firstVisibleIndex());
2431 if (!isRangeVisible
) {
2436 int previousParents
= 0;
2437 QBitArray previousSiblings
;
2439 // The rootIndex describes the first index where the siblings get
2440 // calculated from. For the calculation the upper most parent item
2441 // is required. For performance reasons it is checked first whether
2442 // the visible items before or after the current range already
2443 // contain a siblings information which can be used as base.
2444 int rootIndex
= firstIndex
;
2446 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2448 // There is no visible widget before the range, check whether there
2449 // is one after the range:
2450 widget
= m_visibleItems
.value(lastIndex
+ 1);
2452 // The sibling information of the widget may only be used if
2453 // all items of the range have the same number of parents.
2454 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2455 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2456 if (m_model
->expandedParentsCount(i
) != parents
) {
2465 // Performance optimization: Use the sibling information of the visible
2466 // widget beside the given range.
2467 previousSiblings
= widget
->siblingsInformation();
2468 if (previousSiblings
.isEmpty()) {
2471 previousParents
= previousSiblings
.count() - 1;
2472 previousSiblings
.truncate(previousParents
);
2474 // Potentially slow path: Go back to the upper most parent of firstIndex
2475 // to be able to calculate the initial value for the siblings.
2476 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2481 Q_ASSERT(previousParents
>= 0);
2482 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2483 // Update the parent-siblings in case if the current item represents
2484 // a child or an upper parent.
2485 const int currentParents
= m_model
->expandedParentsCount(i
);
2486 Q_ASSERT(currentParents
>= 0);
2487 if (previousParents
< currentParents
) {
2488 previousParents
= currentParents
;
2489 previousSiblings
.resize(currentParents
);
2490 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2491 } else if (previousParents
> currentParents
) {
2492 previousParents
= currentParents
;
2493 previousSiblings
.truncate(currentParents
);
2496 if (i
>= firstIndex
) {
2497 // The index represents a visible item. Apply the parent-siblings
2498 // and update the sibling of the current item.
2499 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2504 QBitArray siblings
= previousSiblings
;
2505 siblings
.resize(siblings
.count() + 1);
2506 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2508 widget
->setSiblingsInformation(siblings
);
2513 bool KItemListView::hasSiblingSuccessor(int index
) const
2515 bool hasSuccessor
= false;
2516 const int parentsCount
= m_model
->expandedParentsCount(index
);
2517 int successorIndex
= index
+ 1;
2519 // Search the next sibling
2520 const int itemCount
= m_model
->count();
2521 while (successorIndex
< itemCount
) {
2522 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2523 if (currentParentsCount
== parentsCount
) {
2524 hasSuccessor
= true;
2526 } else if (currentParentsCount
< parentsCount
) {
2532 if (m_grouped
&& hasSuccessor
) {
2533 // If the sibling is part of another group, don't mark it as
2534 // successor as the group header is between the sibling connections.
2535 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2536 if (m_layouter
->isFirstGroupItem(i
)) {
2537 hasSuccessor
= false;
2543 return hasSuccessor
;
2546 void KItemListView::disconnectRoleEditingSignals(int index
)
2548 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2553 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2554 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2557 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2561 const int minSpeed
= 4;
2562 const int maxSpeed
= 128;
2563 const int speedLimiter
= 96;
2564 const int autoScrollBorder
= 64;
2566 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2567 // This assures that the autoscrolling speed grows gradually.
2568 const int incLimiter
= 1;
2570 if (pos
< autoScrollBorder
) {
2571 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2572 inc
= qMax(inc
, -maxSpeed
);
2573 inc
= qMax(inc
, oldInc
- incLimiter
);
2574 } else if (pos
> range
- autoScrollBorder
) {
2575 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2576 inc
= qMin(inc
, maxSpeed
);
2577 inc
= qMin(inc
, oldInc
+ incLimiter
);
2583 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2585 const qreal availableSize
= size
- itemMargin
;
2586 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2592 KItemListCreatorBase::~KItemListCreatorBase()
2594 qDeleteAll(m_recycleableWidgets
);
2595 qDeleteAll(m_createdWidgets
);
2598 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2600 m_createdWidgets
.insert(widget
);
2603 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2605 Q_ASSERT(m_createdWidgets
.contains(widget
));
2606 m_createdWidgets
.remove(widget
);
2608 if (m_recycleableWidgets
.count() < 100) {
2609 m_recycleableWidgets
.append(widget
);
2610 widget
->setVisible(false);
2616 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2618 if (m_recycleableWidgets
.isEmpty()) {
2622 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2623 m_createdWidgets
.insert(widget
);
2627 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2631 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2633 widget
->setParentItem(0);
2634 widget
->setOpacity(1.0);
2635 pushRecycleableWidget(widget
);
2638 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2642 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2644 header
->setOpacity(1.0);
2645 pushRecycleableWidget(header
);
2648 #include "kitemlistview.moc"