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 int KItemListView::itemAt(const QPointF
& pos
) const
393 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
394 while (it
.hasNext()) {
397 const KItemListWidget
* widget
= it
.value();
398 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
399 if (widget
->contains(mappedPos
)) {
407 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
409 if (!m_enabledSelectionToggles
) {
413 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
415 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
416 if (!selectionToggleRect
.isEmpty()) {
417 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
418 return selectionToggleRect
.contains(mappedPos
);
424 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
426 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
428 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
429 if (!expansionToggleRect
.isEmpty()) {
430 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
431 return expansionToggleRect
.contains(mappedPos
);
437 int KItemListView::firstVisibleIndex() const
439 return m_layouter
->firstVisibleIndex();
442 int KItemListView::lastVisibleIndex() const
444 return m_layouter
->lastVisibleIndex();
447 QSizeF
KItemListView::itemSizeHint(int index
) const
449 return widgetCreator()->itemSizeHint(index
, this);
452 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
454 if (m_supportsItemExpanding
!= supportsExpanding
) {
455 m_supportsItemExpanding
= supportsExpanding
;
456 updateSiblingsInformation();
457 onSupportsItemExpandingChanged(supportsExpanding
);
461 bool KItemListView::supportsItemExpanding() const
463 return m_supportsItemExpanding
;
466 QRectF
KItemListView::itemRect(int index
) const
468 return m_layouter
->itemRect(index
);
471 QRectF
KItemListView::itemContextRect(int index
) const
475 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
477 contextRect
= widget
->iconRect() | widget
->textRect();
478 contextRect
.translate(itemRect(index
).topLeft());
484 void KItemListView::scrollToItem(int index
)
486 QRectF viewGeometry
= geometry();
487 if (m_headerWidget
->isVisible()) {
488 const qreal headerHeight
= m_headerWidget
->size().height();
489 viewGeometry
.adjust(0, headerHeight
, 0, 0);
491 const QRectF currentRect
= itemRect(index
);
493 if (!viewGeometry
.contains(currentRect
)) {
494 qreal newOffset
= scrollOffset();
495 if (scrollOrientation() == Qt::Vertical
) {
496 if (currentRect
.top() < viewGeometry
.top()) {
497 newOffset
+= currentRect
.top() - viewGeometry
.top();
498 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
499 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
502 if (currentRect
.left() < viewGeometry
.left()) {
503 newOffset
+= currentRect
.left() - viewGeometry
.left();
504 } else if (currentRect
.right() > viewGeometry
.right()) {
505 newOffset
+= currentRect
.right() - viewGeometry
.right();
509 if (newOffset
!= scrollOffset()) {
510 emit
scrollTo(newOffset
);
515 void KItemListView::beginTransaction()
517 ++m_activeTransactions
;
518 if (m_activeTransactions
== 1) {
519 onTransactionBegin();
523 void KItemListView::endTransaction()
525 --m_activeTransactions
;
526 if (m_activeTransactions
< 0) {
527 m_activeTransactions
= 0;
528 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
531 if (m_activeTransactions
== 0) {
533 doLayout(m_endTransactionAnimationHint
);
534 m_endTransactionAnimationHint
= Animation
;
538 bool KItemListView::isTransactionActive() const
540 return m_activeTransactions
> 0;
543 void KItemListView::setHeaderVisible(bool visible
)
545 if (visible
&& !m_headerWidget
->isVisible()) {
546 QStyleOptionHeader option
;
547 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
550 m_headerWidget
->setPos(0, 0);
551 m_headerWidget
->resize(size().width(), headerSize
.height());
552 m_headerWidget
->setModel(m_model
);
553 m_headerWidget
->setColumns(m_visibleRoles
);
554 m_headerWidget
->setZValue(1);
556 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
557 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
558 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
559 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
560 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
561 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
562 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
563 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
565 m_layouter
->setHeaderHeight(headerSize
.height());
566 m_headerWidget
->setVisible(true);
567 } else if (!visible
&& m_headerWidget
->isVisible()) {
568 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
569 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
570 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
571 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
572 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
573 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
574 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
575 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
577 m_layouter
->setHeaderHeight(0);
578 m_headerWidget
->setVisible(false);
582 bool KItemListView::isHeaderVisible() const
584 return m_headerWidget
->isVisible();
587 KItemListHeader
* KItemListView::header() const
592 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
596 if (indexes
.count() == 1) {
597 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
598 QGraphicsView
* graphicsView
= scene()->views()[0];
599 if (item
&& graphicsView
) {
600 pixmap
= item
->createDragPixmap(0, graphicsView
);
603 // TODO: Not implemented yet. Probably extend the interface
604 // from KItemListWidget::createDragPixmap() to return a pixmap
605 // that can be used for multiple indexes.
611 void KItemListView::editRole(int index
, const QByteArray
& role
)
613 KItemListWidget
* widget
= m_visibleItems
.value(index
);
614 if (!widget
|| m_editingRole
) {
618 m_editingRole
= true;
619 widget
->setEditedRole(role
);
621 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
622 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
623 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
624 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
627 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
629 QGraphicsWidget::paint(painter
, option
, widget
);
631 if (m_rubberBand
->isActive()) {
632 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
633 m_rubberBand
->endPosition()).normalized();
635 const QPointF topLeft
= rubberBandRect
.topLeft();
636 if (scrollOrientation() == Qt::Vertical
) {
637 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
639 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
642 QStyleOptionRubberBand opt
;
643 opt
.initFrom(widget
);
644 opt
.shape
= QRubberBand::Rectangle
;
646 opt
.rect
= rubberBandRect
.toRect();
647 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
650 if (!m_dropIndicator
.isEmpty()) {
651 const QRectF r
= m_dropIndicator
.toRect();
653 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
654 painter
->setPen(color
);
656 // TODO: The following implementation works only for a vertical scroll-orientation
657 // and assumes a height of the m_draggingInsertIndicator of 1.
658 Q_ASSERT(r
.height() == 1);
659 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
662 painter
->setPen(color
);
663 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
667 void KItemListView::setItemSize(const QSizeF
& size
)
669 const QSizeF previousSize
= m_itemSize
;
670 if (size
== previousSize
) {
674 // Skip animations when the number of rows or columns
675 // are changed in the grid layout. Although the animation
676 // engine can handle this usecase, it looks obtrusive.
677 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
679 m_layouter
->itemMargin());
681 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
682 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
683 (!m_itemSize
.isEmpty() && size
.isEmpty()));
687 if (alternateBackgroundsChanged
) {
688 // For an empty item size alternate backgrounds are drawn if more than
689 // one role is shown. Assure that the backgrounds for visible items are
690 // updated when changing the size in this context.
691 updateAlternateBackgrounds();
694 if (size
.isEmpty()) {
695 if (m_headerWidget
->automaticColumnResizing()) {
696 updatePreferredColumnWidths();
698 // Only apply the changed height and respect the header widths
700 const qreal currentWidth
= m_layouter
->itemSize().width();
701 const QSizeF
newSize(currentWidth
, size
.height());
702 m_layouter
->setItemSize(newSize
);
705 m_layouter
->setItemSize(size
);
708 m_sizeHintResolver
->clearCache();
709 doLayout(animate
? Animation
: NoAnimation
);
710 onItemSizeChanged(size
, previousSize
);
713 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
715 const KItemListStyleOption previousOption
= m_styleOption
;
716 m_styleOption
= option
;
719 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
720 if (margin
!= m_layouter
->itemMargin()) {
721 // Skip animations when the number of rows or columns
722 // are changed in the grid layout. Although the animation
723 // engine can handle this usecase, it looks obtrusive.
724 animate
= !changesItemGridLayout(m_layouter
->size(),
725 m_layouter
->itemSize(),
727 m_layouter
->setItemMargin(margin
);
731 updateGroupHeaderHeight();
734 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
735 // Animating a change of the maximum text size just results in expensive
736 // temporary eliding and clipping operations and does not look good visually.
740 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
741 while (it
.hasNext()) {
743 it
.value()->setStyleOption(option
);
746 m_sizeHintResolver
->clearCache();
747 m_layouter
->markAsDirty();
748 doLayout(animate
? Animation
: NoAnimation
);
750 if (m_itemSize
.isEmpty()) {
751 updatePreferredColumnWidths();
754 onStyleOptionChanged(option
, previousOption
);
757 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
759 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
760 if (orientation
== previousOrientation
) {
764 m_layouter
->setScrollOrientation(orientation
);
765 m_animation
->setScrollOrientation(orientation
);
766 m_sizeHintResolver
->clearCache();
769 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
770 while (it
.hasNext()) {
772 it
.value()->setScrollOrientation(orientation
);
774 updateGroupHeaderHeight();
778 doLayout(NoAnimation
);
780 onScrollOrientationChanged(orientation
, previousOrientation
);
781 emit
scrollOrientationChanged(orientation
, previousOrientation
);
784 Qt::Orientation
KItemListView::scrollOrientation() const
786 return m_layouter
->scrollOrientation();
789 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
794 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
799 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
804 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
806 Q_UNUSED(changedRoles
);
810 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
816 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
822 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
828 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
834 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
840 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
846 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
852 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
854 Q_UNUSED(supportsExpanding
);
857 void KItemListView::onTransactionBegin()
861 void KItemListView::onTransactionEnd()
865 bool KItemListView::event(QEvent
* event
)
867 // Forward all events to the controller and handle them there
868 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
872 return QGraphicsWidget::event(event
);
875 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
877 m_mousePos
= transform().map(event
->pos());
881 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
883 QGraphicsWidget::mouseMoveEvent(event
);
885 m_mousePos
= transform().map(event
->pos());
886 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
887 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
891 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
893 event
->setAccepted(true);
897 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
899 QGraphicsWidget::dragMoveEvent(event
);
901 m_mousePos
= transform().map(event
->pos());
902 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
903 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
907 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
909 QGraphicsWidget::dragLeaveEvent(event
);
910 setAutoScroll(false);
913 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
915 QGraphicsWidget::dropEvent(event
);
916 setAutoScroll(false);
919 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
921 return m_visibleItems
.values();
924 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
926 if (m_itemSize
.isEmpty()) {
927 updatePreferredColumnWidths(itemRanges
);
930 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
931 if (hasMultipleRanges
) {
935 m_layouter
->markAsDirty();
937 int previouslyInsertedCount
= 0;
938 foreach (const KItemRange
& range
, itemRanges
) {
939 // range.index is related to the model before anything has been inserted.
940 // As in each loop the current item-range gets inserted the index must
941 // be increased by the already previously inserted items.
942 const int index
= range
.index
+ previouslyInsertedCount
;
943 const int count
= range
.count
;
944 if (index
< 0 || count
<= 0) {
945 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
948 previouslyInsertedCount
+= count
;
950 m_sizeHintResolver
->itemsInserted(index
, count
);
952 // Determine which visible items must be moved
953 QList
<int> itemsToMove
;
954 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
955 while (it
.hasNext()) {
957 const int visibleItemIndex
= it
.key();
958 if (visibleItemIndex
>= index
) {
959 itemsToMove
.append(visibleItemIndex
);
963 // Update the indexes of all KItemListWidget instances that are located
964 // after the inserted items. It is important to adjust the indexes in the order
965 // from the highest index to the lowest index to prevent overlaps when setting the new index.
967 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
968 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
970 const int newIndex
= widget
->index() + count
;
971 if (hasMultipleRanges
) {
972 setWidgetIndex(widget
, newIndex
);
974 // Try to animate the moving of the item
975 moveWidgetToIndex(widget
, newIndex
);
979 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
980 // Check whether a scrollbar is required to show the inserted items. In this case
981 // the size of the layouter will be decreased before calling doLayout(): This prevents
982 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
983 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
984 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
985 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
986 if (decreaseLayouterSize
) {
987 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
988 QSizeF layouterSize
= m_layouter
->size();
989 if (verticalScrollOrientation
) {
990 layouterSize
.rwidth() -= scrollBarExtent
;
992 layouterSize
.rheight() -= scrollBarExtent
;
994 m_layouter
->setSize(layouterSize
);
998 if (!hasMultipleRanges
) {
999 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1000 updateSiblingsInformation();
1005 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1008 if (hasMultipleRanges
) {
1010 // Important: Don't read any m_layouter-property inside the for-loop in case if
1011 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1012 // updated in each loop-cycle and has only a consistent state after the loop.
1013 Q_ASSERT(m_layouter
->isDirty());
1015 m_endTransactionAnimationHint
= NoAnimation
;
1018 updateSiblingsInformation();
1021 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1022 // In case if items of the same group have been inserted before an item that
1023 // currently represents the first item of the group, the group header of
1024 // this item must be removed.
1025 updateVisibleGroupHeaders();
1028 if (useAlternateBackgrounds()) {
1029 updateAlternateBackgrounds();
1033 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1035 if (m_itemSize
.isEmpty()) {
1036 // Don't pass the item-range: The preferred column-widths of
1037 // all items must be adjusted when removing items.
1038 updatePreferredColumnWidths();
1041 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1042 if (hasMultipleRanges
) {
1046 m_layouter
->markAsDirty();
1048 int removedItemsCount
= 0;
1049 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1050 removedItemsCount
+= itemRanges
[i
].count
;
1053 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1054 const KItemRange
& range
= itemRanges
[i
];
1055 const int index
= range
.index
;
1056 const int count
= range
.count
;
1057 if (index
< 0 || count
<= 0) {
1058 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1062 m_sizeHintResolver
->itemsRemoved(index
, count
);
1064 const int firstRemovedIndex
= index
;
1065 const int lastRemovedIndex
= index
+ count
- 1;
1066 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1067 removedItemsCount
-= count
;
1069 // Remove all KItemListWidget instances that got deleted
1070 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1071 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1076 m_animation
->stop(widget
);
1077 // Stopping the animation might lead to recycling the widget if
1078 // it is invisible (see slotAnimationFinished()).
1079 // Check again whether it is still visible:
1080 if (!m_visibleItems
.contains(i
)) {
1084 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1085 // Remove the widget without animation
1086 recycleWidget(widget
);
1088 // Animate the removing of the items. Special case: When removing an item there
1089 // is no valid model index available anymore. For the
1090 // remove-animation the item gets removed from m_visibleItems but the widget
1091 // will stay alive until the animation has been finished and will
1092 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1093 m_visibleItems
.remove(i
);
1094 widget
->setIndex(-1);
1095 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1099 // Update the indexes of all KItemListWidget instances that are located
1100 // after the deleted items
1101 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1102 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1104 const int newIndex
= i
- count
;
1105 if (hasMultipleRanges
) {
1106 setWidgetIndex(widget
, newIndex
);
1108 // Try to animate the moving of the item
1109 moveWidgetToIndex(widget
, newIndex
);
1114 if (!hasMultipleRanges
) {
1115 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1116 // assumes an updated geometry. If items are removed during an active transaction,
1117 // the transaction will be temporary deactivated so that doLayout() triggers a
1118 // geometry update if necessary.
1119 const int activeTransactions
= m_activeTransactions
;
1120 m_activeTransactions
= 0;
1121 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1122 m_activeTransactions
= activeTransactions
;
1123 updateSiblingsInformation();
1128 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1131 if (hasMultipleRanges
) {
1133 // Important: Don't read any m_layouter-property inside the for-loop in case if
1134 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1135 // updated in each loop-cycle and has only a consistent state after the loop.
1136 Q_ASSERT(m_layouter
->isDirty());
1138 m_endTransactionAnimationHint
= NoAnimation
;
1140 updateSiblingsInformation();
1143 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1144 // In case if the first item of a group has been removed, the group header
1145 // must be applied to the next visible item.
1146 updateVisibleGroupHeaders();
1149 if (useAlternateBackgrounds()) {
1150 updateAlternateBackgrounds();
1154 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1156 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1157 m_layouter
->markAsDirty();
1160 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1163 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1164 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1166 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1167 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1169 updateWidgetProperties(widget
, index
);
1170 initializeItemListWidget(widget
);
1174 doLayout(NoAnimation
);
1175 updateSiblingsInformation();
1178 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1179 const QSet
<QByteArray
>& roles
)
1181 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1182 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1183 updatePreferredColumnWidths(itemRanges
);
1186 foreach (const KItemRange
& itemRange
, itemRanges
) {
1187 const int index
= itemRange
.index
;
1188 const int count
= itemRange
.count
;
1190 if (updateSizeHints
) {
1191 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1192 m_layouter
->markAsDirty();
1194 if (!m_layoutTimer
->isActive()) {
1195 m_layoutTimer
->start();
1199 // Apply the changed roles to the visible item-widgets
1200 const int lastIndex
= index
+ count
- 1;
1201 for (int i
= index
; i
<= lastIndex
; ++i
) {
1202 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1204 widget
->setData(m_model
->data(i
), roles
);
1208 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1209 // The sort-role has been changed which might result
1210 // in modified group headers
1211 updateVisibleGroupHeaders();
1212 doLayout(NoAnimation
);
1215 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1218 void KItemListView::slotGroupedSortingChanged(bool current
)
1220 m_grouped
= current
;
1221 m_layouter
->markAsDirty();
1224 updateGroupHeaderHeight();
1226 // Clear all visible headers
1227 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1228 while (it
.hasNext()) {
1230 recycleGroupHeaderForWidget(it
.key());
1232 Q_ASSERT(m_visibleGroups
.isEmpty());
1235 if (useAlternateBackgrounds()) {
1236 // Changing the group mode requires to update the alternate backgrounds
1237 // as with the enabled group mode the altering is done on base of the first
1239 updateAlternateBackgrounds();
1241 updateSiblingsInformation();
1242 doLayout(NoAnimation
);
1245 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1250 updateVisibleGroupHeaders();
1251 doLayout(NoAnimation
);
1255 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1260 updateVisibleGroupHeaders();
1261 doLayout(NoAnimation
);
1265 void KItemListView::slotCurrentChanged(int current
, int previous
)
1269 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1270 if (previousWidget
) {
1271 previousWidget
->setCurrent(false);
1274 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1275 if (currentWidget
) {
1276 currentWidget
->setCurrent(true);
1278 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1281 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1285 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1286 while (it
.hasNext()) {
1288 const int index
= it
.key();
1289 KItemListWidget
* widget
= it
.value();
1290 widget
->setSelected(current
.contains(index
));
1294 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1295 KItemListViewAnimation::AnimationType type
)
1297 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1298 Q_ASSERT(itemListWidget
);
1301 case KItemListViewAnimation::DeleteAnimation
: {
1302 // As we recycle the widget in this case it is important to assure that no
1303 // other animation has been started. This is a convention in KItemListView and
1304 // not a requirement defined by KItemListViewAnimation.
1305 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1307 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1308 // by m_visibleWidgets and must be deleted manually after the animation has
1310 recycleGroupHeaderForWidget(itemListWidget
);
1311 widgetCreator()->recycle(itemListWidget
);
1315 case KItemListViewAnimation::CreateAnimation
:
1316 case KItemListViewAnimation::MovingAnimation
:
1317 case KItemListViewAnimation::ResizeAnimation
: {
1318 const int index
= itemListWidget
->index();
1319 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1320 (index
> m_layouter
->lastVisibleIndex());
1321 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1322 recycleWidget(itemListWidget
);
1331 void KItemListView::slotLayoutTimerFinished()
1333 m_layouter
->setSize(geometry().size());
1334 doLayout(Animation
);
1337 void KItemListView::slotRubberBandPosChanged()
1342 void KItemListView::slotRubberBandActivationChanged(bool active
)
1345 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1346 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1347 m_skipAutoScrollForRubberBand
= true;
1349 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1350 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1351 m_skipAutoScrollForRubberBand
= false;
1357 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1359 qreal previousWidth
)
1362 Q_UNUSED(currentWidth
);
1363 Q_UNUSED(previousWidth
);
1365 m_headerWidget
->setAutomaticColumnResizing(false);
1366 applyColumnWidthsFromHeader();
1367 doLayout(NoAnimation
);
1370 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1374 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1376 const QList
<QByteArray
> previous
= m_visibleRoles
;
1378 QList
<QByteArray
> current
= m_visibleRoles
;
1379 current
.removeAt(previousIndex
);
1380 current
.insert(currentIndex
, role
);
1382 setVisibleRoles(current
);
1384 emit
visibleRolesChanged(current
, previous
);
1387 void KItemListView::triggerAutoScrolling()
1389 if (!m_autoScrollTimer
) {
1394 int visibleSize
= 0;
1395 if (scrollOrientation() == Qt::Vertical
) {
1396 pos
= m_mousePos
.y();
1397 visibleSize
= size().height();
1399 pos
= m_mousePos
.x();
1400 visibleSize
= size().width();
1403 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1404 m_autoScrollIncrement
= 0;
1407 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1408 if (m_autoScrollIncrement
== 0) {
1409 // The mouse position is not above an autoscroll margin (the autoscroll timer
1410 // will be restarted in mouseMoveEvent())
1411 m_autoScrollTimer
->stop();
1415 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1416 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1417 // if the direction of the rubberband is similar to the autoscroll direction. This
1418 // prevents that starting to create a rubberband within the autoscroll margins starts
1419 // an autoscrolling.
1421 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1422 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1423 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1424 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1425 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1426 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1427 // been moved up although the autoscroll direction might be down)
1428 m_autoScrollTimer
->stop();
1433 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1434 // the autoscrolling may not get skipped anymore until a new rubberband is created
1435 m_skipAutoScrollForRubberBand
= false;
1437 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1438 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1439 setScrollOffset(newScrollOffset
);
1441 // Trigger the autoscroll timer which will periodically call
1442 // triggerAutoScrolling()
1443 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1446 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1448 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1450 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1451 Q_ASSERT(groupHeader
);
1452 updateGroupHeaderLayout(widget
);
1455 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1457 disconnectRoleEditingSignals(index
);
1459 emit
roleEditingCanceled(index
, role
, value
);
1460 m_editingRole
= false;
1463 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1465 disconnectRoleEditingSignals(index
);
1467 emit
roleEditingFinished(index
, role
, value
);
1468 m_editingRole
= false;
1471 void KItemListView::setController(KItemListController
* controller
)
1473 if (m_controller
!= controller
) {
1474 KItemListController
* previous
= m_controller
;
1476 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1477 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1478 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1481 m_controller
= controller
;
1484 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1485 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1486 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1489 onControllerChanged(controller
, previous
);
1493 void KItemListView::setModel(KItemModelBase
* model
)
1495 if (m_model
== model
) {
1499 KItemModelBase
* previous
= m_model
;
1502 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1503 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1504 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1505 this, SLOT(slotItemsInserted(KItemRangeList
)));
1506 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1507 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1508 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1509 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1510 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1511 this, SLOT(slotGroupedSortingChanged(bool)));
1512 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1513 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1514 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1515 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1518 m_sizeHintResolver
->clearCache();
1521 m_layouter
->setModel(model
);
1522 m_grouped
= model
->groupedSorting();
1525 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1526 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1527 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1528 this, SLOT(slotItemsInserted(KItemRangeList
)));
1529 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1530 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1531 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1532 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1533 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1534 this, SLOT(slotGroupedSortingChanged(bool)));
1535 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1536 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1537 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1538 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1540 const int itemCount
= m_model
->count();
1541 if (itemCount
> 0) {
1542 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1543 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1547 onModelChanged(model
, previous
);
1550 KItemListRubberBand
* KItemListView::rubberBand() const
1552 return m_rubberBand
;
1555 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1557 if (m_layoutTimer
->isActive()) {
1558 m_layoutTimer
->stop();
1561 if (m_activeTransactions
> 0) {
1562 if (hint
== NoAnimation
) {
1563 // As soon as at least one property change should be done without animation,
1564 // the whole transaction will be marked as not animated.
1565 m_endTransactionAnimationHint
= NoAnimation
;
1570 if (!m_model
|| m_model
->count() < 0) {
1574 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1575 if (firstVisibleIndex
< 0) {
1576 emitOffsetChanges();
1580 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1581 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1582 // is still shown if the maximum offset got decreased.
1583 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1584 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1585 if (scrollOffset() > maxOffsetToShowFullRange
) {
1586 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1587 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1590 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1592 int firstSibblingIndex
= -1;
1593 int lastSibblingIndex
= -1;
1594 const bool supportsExpanding
= supportsItemExpanding();
1596 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1598 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1599 // instances from invisible items are reused. If no reusable items are
1600 // found then new KItemListWidget instances get created.
1601 const bool animate
= (hint
== Animation
);
1602 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1603 bool applyNewPos
= true;
1604 bool wasHidden
= false;
1606 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1607 const QPointF newPos
= itemBounds
.topLeft();
1608 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1611 if (!reusableItems
.isEmpty()) {
1612 // Reuse a KItemListWidget instance from an invisible item
1613 const int oldIndex
= reusableItems
.takeLast();
1614 widget
= m_visibleItems
.value(oldIndex
);
1615 setWidgetIndex(widget
, i
);
1616 updateWidgetProperties(widget
, i
);
1617 initializeItemListWidget(widget
);
1619 // No reusable KItemListWidget instance is available, create a new one
1620 widget
= createWidget(i
);
1622 widget
->resize(itemBounds
.size());
1624 if (animate
&& changedCount
< 0) {
1625 // Items have been deleted, move the created item to the
1626 // imaginary old position. They will get animated to the new position
1628 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1629 if (itemRect
.isEmpty()) {
1630 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1631 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1632 widget
->setPos(invisibleOldPos
);
1634 widget
->setPos(itemRect
.topLeft());
1636 applyNewPos
= false;
1639 if (supportsExpanding
&& changedCount
== 0) {
1640 if (firstSibblingIndex
< 0) {
1641 firstSibblingIndex
= i
;
1643 lastSibblingIndex
= i
;
1648 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1649 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1650 applyNewPos
= false;
1653 const bool itemsRemoved
= (changedCount
< 0);
1654 const bool itemsInserted
= (changedCount
> 0);
1655 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1656 // The item is located after the removed items. Animate the moving of the position.
1657 applyNewPos
= !moveWidget(widget
, newPos
);
1658 } else if (itemsInserted
&& i
>= changedIndex
) {
1659 // The item is located after the first inserted item
1660 if (i
<= changedIndex
+ changedCount
- 1) {
1661 // The item is an inserted item. Animate the appearing of the item.
1662 // For performance reasons no animation is done when changedCount is equal
1663 // to all available items.
1664 if (changedCount
< m_model
->count()) {
1665 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1667 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1668 // The item was already there before, so animate the moving of the position.
1669 // No moving animation is done if the item is animated by a create animation: This
1670 // prevents a "move animation mess" when inserting several ranges in parallel.
1671 applyNewPos
= !moveWidget(widget
, newPos
);
1673 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1674 // The size of the view might have been changed. Animate the moving of the position.
1675 applyNewPos
= !moveWidget(widget
, newPos
);
1678 m_animation
->stop(widget
);
1682 widget
->setPos(newPos
);
1685 Q_ASSERT(widget
->index() == i
);
1686 widget
->setVisible(true);
1688 if (widget
->size() != itemBounds
.size()) {
1689 // Resize the widget for the item to the changed size.
1691 // If a dynamic item size is used then no animation is done in the direction
1692 // of the dynamic size.
1693 if (m_itemSize
.width() <= 0) {
1694 // The width is dynamic, apply the new width without animation.
1695 widget
->resize(itemBounds
.width(), widget
->size().height());
1696 } else if (m_itemSize
.height() <= 0) {
1697 // The height is dynamic, apply the new height without animation.
1698 widget
->resize(widget
->size().width(), itemBounds
.height());
1700 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1702 widget
->resize(itemBounds
.size());
1706 // Updating the cell-information must be done as last step: The decision whether the
1707 // moving-animation should be started at all is based on the previous cell-information.
1708 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1709 m_visibleCells
.insert(i
, cell
);
1712 // Delete invisible KItemListWidget instances that have not been reused
1713 foreach (int index
, reusableItems
) {
1714 recycleWidget(m_visibleItems
.value(index
));
1717 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1718 Q_ASSERT(lastSibblingIndex
>= 0);
1719 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1723 // Update the layout of all visible group headers
1724 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1725 while (it
.hasNext()) {
1727 updateGroupHeaderLayout(it
.key());
1731 emitOffsetChanges();
1734 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1735 int lastVisibleIndex
,
1736 LayoutAnimationHint hint
)
1738 // Determine all items that are completely invisible and might be
1739 // reused for items that just got (at least partly) visible. If the
1740 // animation hint is set to 'Animation' items that do e.g. an animated
1741 // moving of their position are not marked as invisible: This assures
1742 // that a scrolling inside the view can be done without breaking an animation.
1746 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1747 while (it
.hasNext()) {
1750 KItemListWidget
* widget
= it
.value();
1751 const int index
= widget
->index();
1752 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1755 if (m_animation
->isStarted(widget
)) {
1756 if (hint
== NoAnimation
) {
1757 // Stopping the animation will call KItemListView::slotAnimationFinished()
1758 // and the widget will be recycled if necessary there.
1759 m_animation
->stop(widget
);
1762 widget
->setVisible(false);
1763 items
.append(index
);
1766 recycleGroupHeaderForWidget(widget
);
1775 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1777 if (widget
->pos() == newPos
) {
1781 bool startMovingAnim
= false;
1783 if (m_itemSize
.isEmpty()) {
1784 // The items are not aligned in a grid but either as columns or rows.
1785 startMovingAnim
= true;
1787 // When having a grid the moving-animation should only be started, if it is done within
1788 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1789 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1790 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1791 const int index
= widget
->index();
1792 const Cell cell
= m_visibleCells
.value(index
);
1793 if (cell
.column
>= 0 && cell
.row
>= 0) {
1794 if (scrollOrientation() == Qt::Vertical
) {
1795 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1797 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1802 if (startMovingAnim
) {
1803 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1807 m_animation
->stop(widget
);
1808 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1812 void KItemListView::emitOffsetChanges()
1814 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1815 if (m_oldScrollOffset
!= newScrollOffset
) {
1816 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1817 m_oldScrollOffset
= newScrollOffset
;
1820 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1821 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1822 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1823 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1826 const qreal newItemOffset
= m_layouter
->itemOffset();
1827 if (m_oldItemOffset
!= newItemOffset
) {
1828 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1829 m_oldItemOffset
= newItemOffset
;
1832 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1833 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1834 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1835 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1839 KItemListWidget
* KItemListView::createWidget(int index
)
1841 KItemListWidget
* widget
= widgetCreator()->create(this);
1842 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1844 m_visibleItems
.insert(index
, widget
);
1845 m_visibleCells
.insert(index
, Cell());
1846 updateWidgetProperties(widget
, index
);
1847 initializeItemListWidget(widget
);
1851 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1854 recycleGroupHeaderForWidget(widget
);
1857 const int index
= widget
->index();
1858 m_visibleItems
.remove(index
);
1859 m_visibleCells
.remove(index
);
1861 widgetCreator()->recycle(widget
);
1864 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1866 const int oldIndex
= widget
->index();
1867 m_visibleItems
.remove(oldIndex
);
1868 m_visibleCells
.remove(oldIndex
);
1870 m_visibleItems
.insert(index
, widget
);
1871 m_visibleCells
.insert(index
, Cell());
1873 widget
->setIndex(index
);
1876 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1878 const int oldIndex
= widget
->index();
1879 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1881 setWidgetIndex(widget
, index
);
1883 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1884 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1885 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1886 (!vertical
&& oldCell
.column
== newCell
.column
);
1888 m_visibleCells
.insert(index
, newCell
);
1892 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1895 case LayouterSize
: m_layouter
->setSize(size
); break;
1896 case ItemSize
: m_layouter
->setItemSize(size
); break;
1901 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1903 widget
->setVisibleRoles(m_visibleRoles
);
1904 updateWidgetColumnWidths(widget
);
1905 widget
->setStyleOption(m_styleOption
);
1907 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1908 widget
->setCurrent(index
== selectionManager
->currentItem());
1909 widget
->setSelected(selectionManager
->isSelected(index
));
1910 widget
->setHovered(false);
1911 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1912 widget
->setIndex(index
);
1913 widget
->setData(m_model
->data(index
));
1914 widget
->setSiblingsInformation(QBitArray());
1915 updateAlternateBackgroundForWidget(widget
);
1918 updateGroupHeaderForWidget(widget
);
1922 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1924 Q_ASSERT(m_grouped
);
1926 const int index
= widget
->index();
1927 if (!m_layouter
->isFirstGroupItem(index
)) {
1928 // The widget does not represent the first item of a group
1929 // and hence requires no header
1930 recycleGroupHeaderForWidget(widget
);
1934 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1935 if (groups
.isEmpty() || !groupHeaderCreator()) {
1939 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1941 groupHeader
= groupHeaderCreator()->create(this);
1942 groupHeader
->setParentItem(widget
);
1943 m_visibleGroups
.insert(widget
, groupHeader
);
1944 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1946 Q_ASSERT(groupHeader
->parentItem() == widget
);
1948 const int groupIndex
= groupIndexForItem(index
);
1949 Q_ASSERT(groupIndex
>= 0);
1950 groupHeader
->setData(groups
.at(groupIndex
).second
);
1951 groupHeader
->setRole(model()->sortRole());
1952 groupHeader
->setStyleOption(m_styleOption
);
1953 groupHeader
->setScrollOrientation(scrollOrientation());
1954 groupHeader
->setItemIndex(index
);
1956 groupHeader
->show();
1959 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1961 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1962 Q_ASSERT(groupHeader
);
1964 const int index
= widget
->index();
1965 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1966 const QRectF itemRect
= m_layouter
->itemRect(index
);
1968 // The group-header is a child of the itemlist widget. Translate the
1969 // group header position to the relative position.
1970 if (scrollOrientation() == Qt::Vertical
) {
1971 // In the vertical scroll orientation the group header should always span
1972 // the whole width no matter which temporary position the parent widget
1973 // has. In this case the x-position and width will be adjusted manually.
1974 const qreal x
= -widget
->x() - itemOffset();
1975 const qreal width
= maximumItemOffset();
1976 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1977 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1979 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1980 groupHeader
->resize(groupHeaderRect
.size());
1984 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1986 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1988 header
->setParentItem(0);
1989 groupHeaderCreator()->recycle(header
);
1990 m_visibleGroups
.remove(widget
);
1991 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1995 void KItemListView::updateVisibleGroupHeaders()
1997 Q_ASSERT(m_grouped
);
1998 m_layouter
->markAsDirty();
2000 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2001 while (it
.hasNext()) {
2003 updateGroupHeaderForWidget(it
.value());
2007 int KItemListView::groupIndexForItem(int index
) const
2009 Q_ASSERT(m_grouped
);
2011 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2012 if (groups
.isEmpty()) {
2017 int max
= groups
.count() - 1;
2020 mid
= (min
+ max
) / 2;
2021 if (index
> groups
[mid
].first
) {
2026 } while (groups
[mid
].first
!= index
&& min
<= max
);
2029 while (groups
[mid
].first
> index
&& mid
> 0) {
2037 void KItemListView::updateAlternateBackgrounds()
2039 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2040 while (it
.hasNext()) {
2042 updateAlternateBackgroundForWidget(it
.value());
2046 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2048 bool enabled
= useAlternateBackgrounds();
2050 const int index
= widget
->index();
2051 enabled
= (index
& 0x1) > 0;
2053 const int groupIndex
= groupIndexForItem(index
);
2054 if (groupIndex
>= 0) {
2055 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2056 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2057 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2058 enabled
= (relativeIndex
& 0x1) > 0;
2062 widget
->setAlternateBackground(enabled
);
2065 bool KItemListView::useAlternateBackgrounds() const
2067 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2070 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2072 QElapsedTimer timer
;
2075 QHash
<QByteArray
, qreal
> widths
;
2077 // Calculate the minimum width for each column that is required
2078 // to show the headline unclipped.
2079 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2080 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2081 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2082 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2083 const QString headerText
= m_model
->roleDescription(visibleRole
);
2084 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2085 widths
.insert(visibleRole
, headerWidth
);
2088 // Calculate the preferred column withs for each item and ignore values
2089 // smaller than the width for showing the headline unclipped.
2090 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2091 int calculatedItemCount
= 0;
2092 bool maxTimeExceeded
= false;
2093 foreach (const KItemRange
& itemRange
, itemRanges
) {
2094 const int startIndex
= itemRange
.index
;
2095 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2097 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2098 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2099 qreal maxWidth
= widths
.value(visibleRole
, 0);
2100 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2101 maxWidth
= qMax(width
, maxWidth
);
2102 widths
.insert(visibleRole
, maxWidth
);
2105 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2106 // When having several thousands of items calculating the sizes can get
2107 // very expensive. We accept a possibly too small role-size in favour
2108 // of having no blocking user interface.
2109 maxTimeExceeded
= true;
2112 ++calculatedItemCount
;
2114 if (maxTimeExceeded
) {
2122 void KItemListView::applyColumnWidthsFromHeader()
2124 // Apply the new size to the layouter
2125 const qreal requiredWidth
= columnWidthsSum();
2126 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2127 m_itemSize
.height());
2128 m_layouter
->setItemSize(dynamicItemSize
);
2130 // Update the role sizes for all visible widgets
2131 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2132 while (it
.hasNext()) {
2134 updateWidgetColumnWidths(it
.value());
2138 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2140 foreach (const QByteArray
& role
, m_visibleRoles
) {
2141 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2145 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2147 Q_ASSERT(m_itemSize
.isEmpty());
2148 const int itemCount
= m_model
->count();
2149 int rangesItemCount
= 0;
2150 foreach (const KItemRange
& range
, itemRanges
) {
2151 rangesItemCount
+= range
.count
;
2154 if (itemCount
== rangesItemCount
) {
2155 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2156 foreach (const QByteArray
& role
, m_visibleRoles
) {
2157 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2160 // Only a sub range of the roles need to be determined.
2161 // The chances are good that the widths of the sub ranges
2162 // already fit into the available widths and hence no
2163 // expensive update might be required.
2164 bool changed
= false;
2166 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2167 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2168 while (it
.hasNext()) {
2170 const QByteArray
& role
= it
.key();
2171 const qreal updatedWidth
= it
.value();
2172 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2173 if (updatedWidth
> currentWidth
) {
2174 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2180 // All the updated sizes are smaller than the current sizes and no change
2181 // of the stretched roles-widths is required
2186 if (m_headerWidget
->automaticColumnResizing()) {
2187 applyAutomaticColumnWidths();
2191 void KItemListView::updatePreferredColumnWidths()
2194 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2198 void KItemListView::applyAutomaticColumnWidths()
2200 Q_ASSERT(m_itemSize
.isEmpty());
2201 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2202 if (m_visibleRoles
.isEmpty()) {
2206 // Calculate the maximum size of an item by considering the
2207 // visible role sizes and apply them to the layouter. If the
2208 // size does not use the available view-size the size of the
2209 // first role will get stretched.
2211 foreach (const QByteArray
& role
, m_visibleRoles
) {
2212 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2213 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2216 const QByteArray firstRole
= m_visibleRoles
.first();
2217 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2218 QSizeF dynamicItemSize
= m_itemSize
;
2220 qreal requiredWidth
= columnWidthsSum();
2221 const qreal availableWidth
= size().width();
2222 if (requiredWidth
< availableWidth
) {
2223 // Stretch the first column to use the whole remaining width
2224 firstColumnWidth
+= availableWidth
- requiredWidth
;
2225 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2226 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2227 // Shrink the first column to be able to show as much other
2228 // columns as possible
2229 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2231 // TODO: A proper calculation of the minimum width depends on the implementation
2232 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2234 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2235 if (shrinkedFirstColumnWidth
< minWidth
) {
2236 shrinkedFirstColumnWidth
= minWidth
;
2239 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2240 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2243 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2245 m_layouter
->setItemSize(dynamicItemSize
);
2247 // Update the role sizes for all visible widgets
2248 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2249 while (it
.hasNext()) {
2251 updateWidgetColumnWidths(it
.value());
2255 qreal
KItemListView::columnWidthsSum() const
2257 qreal widthsSum
= 0;
2258 foreach (const QByteArray
& role
, m_visibleRoles
) {
2259 widthsSum
+= m_headerWidget
->columnWidth(role
);
2264 QRectF
KItemListView::headerBoundaries() const
2266 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2269 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2270 const QSizeF
& newItemSize
,
2271 const QSizeF
& newItemMargin
) const
2273 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2277 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2278 const qreal itemWidth
= m_layouter
->itemSize().width();
2279 if (itemWidth
> 0) {
2280 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2281 newItemSize
.width(),
2282 newItemMargin
.width());
2283 if (m_model
->count() > newColumnCount
) {
2284 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2286 m_layouter
->itemMargin().width());
2287 return oldColumnCount
!= newColumnCount
;
2291 const qreal itemHeight
= m_layouter
->itemSize().height();
2292 if (itemHeight
> 0) {
2293 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2294 newItemSize
.height(),
2295 newItemMargin
.height());
2296 if (m_model
->count() > newRowCount
) {
2297 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2299 m_layouter
->itemMargin().height());
2300 return oldRowCount
!= newRowCount
;
2308 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2310 if (m_itemSize
.isEmpty()) {
2311 // We have only columns or only rows, but no grid: An animation is usually
2312 // welcome when inserting or removing items.
2313 return !supportsItemExpanding();
2316 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2320 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2321 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2322 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2323 // Only animate if up to 2/3 of a row or column are inserted or removed
2324 return changedItemCount
<= maximum
* 2 / 3;
2328 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2330 const QSizeF oldSize
= m_layouter
->size();
2332 m_layouter
->setSize(size
);
2333 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2334 m_layouter
->setSize(oldSize
);
2336 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2337 : maxOffset
> size
.width();
2340 int KItemListView::showDropIndicator(const QPointF
& pos
)
2342 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2343 while (it
.hasNext()) {
2345 const KItemListWidget
* widget
= it
.value();
2347 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2348 const QRectF rect
= itemRect(widget
->index());
2349 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2350 if (m_model
->supportsDropping(widget
->index())) {
2351 const int gap
= qMax(4, m_styleOption
.padding
);
2352 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2357 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2358 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2360 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2361 if (m_dropIndicator
!= draggingInsertIndicator
) {
2362 m_dropIndicator
= draggingInsertIndicator
;
2366 int index
= widget
->index();
2374 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2375 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2378 void KItemListView::hideDropIndicator()
2380 if (!m_dropIndicator
.isNull()) {
2381 m_dropIndicator
= QRectF();
2386 void KItemListView::updateGroupHeaderHeight()
2388 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2389 qreal groupHeaderMargin
= 0;
2391 if (scrollOrientation() == Qt::Horizontal
) {
2392 // The vertical margin above and below the header should be
2393 // equal to the horizontal margin, not the vertical margin
2394 // from m_styleOption.
2395 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2396 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2397 } else if (m_itemSize
.isEmpty()){
2398 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2399 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2401 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2402 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2404 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2405 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2407 updateVisibleGroupHeaders();
2410 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2412 if (!supportsItemExpanding() || !m_model
) {
2416 if (firstIndex
< 0 || lastIndex
< 0) {
2417 firstIndex
= m_layouter
->firstVisibleIndex();
2418 lastIndex
= m_layouter
->lastVisibleIndex();
2420 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2421 lastIndex
>= m_layouter
->firstVisibleIndex());
2422 if (!isRangeVisible
) {
2427 int previousParents
= 0;
2428 QBitArray previousSiblings
;
2430 // The rootIndex describes the first index where the siblings get
2431 // calculated from. For the calculation the upper most parent item
2432 // is required. For performance reasons it is checked first whether
2433 // the visible items before or after the current range already
2434 // contain a siblings information which can be used as base.
2435 int rootIndex
= firstIndex
;
2437 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2439 // There is no visible widget before the range, check whether there
2440 // is one after the range:
2441 widget
= m_visibleItems
.value(lastIndex
+ 1);
2443 // The sibling information of the widget may only be used if
2444 // all items of the range have the same number of parents.
2445 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2446 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2447 if (m_model
->expandedParentsCount(i
) != parents
) {
2456 // Performance optimization: Use the sibling information of the visible
2457 // widget beside the given range.
2458 previousSiblings
= widget
->siblingsInformation();
2459 if (previousSiblings
.isEmpty()) {
2462 previousParents
= previousSiblings
.count() - 1;
2463 previousSiblings
.truncate(previousParents
);
2465 // Potentially slow path: Go back to the upper most parent of firstIndex
2466 // to be able to calculate the initial value for the siblings.
2467 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2472 Q_ASSERT(previousParents
>= 0);
2473 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2474 // Update the parent-siblings in case if the current item represents
2475 // a child or an upper parent.
2476 const int currentParents
= m_model
->expandedParentsCount(i
);
2477 Q_ASSERT(currentParents
>= 0);
2478 if (previousParents
< currentParents
) {
2479 previousParents
= currentParents
;
2480 previousSiblings
.resize(currentParents
);
2481 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2482 } else if (previousParents
> currentParents
) {
2483 previousParents
= currentParents
;
2484 previousSiblings
.truncate(currentParents
);
2487 if (i
>= firstIndex
) {
2488 // The index represents a visible item. Apply the parent-siblings
2489 // and update the sibling of the current item.
2490 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2495 QBitArray siblings
= previousSiblings
;
2496 siblings
.resize(siblings
.count() + 1);
2497 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2499 widget
->setSiblingsInformation(siblings
);
2504 bool KItemListView::hasSiblingSuccessor(int index
) const
2506 bool hasSuccessor
= false;
2507 const int parentsCount
= m_model
->expandedParentsCount(index
);
2508 int successorIndex
= index
+ 1;
2510 // Search the next sibling
2511 const int itemCount
= m_model
->count();
2512 while (successorIndex
< itemCount
) {
2513 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2514 if (currentParentsCount
== parentsCount
) {
2515 hasSuccessor
= true;
2517 } else if (currentParentsCount
< parentsCount
) {
2523 if (m_grouped
&& hasSuccessor
) {
2524 // If the sibling is part of another group, don't mark it as
2525 // successor as the group header is between the sibling connections.
2526 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2527 if (m_layouter
->isFirstGroupItem(i
)) {
2528 hasSuccessor
= false;
2534 return hasSuccessor
;
2537 void KItemListView::disconnectRoleEditingSignals(int index
)
2539 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2544 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2545 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2548 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2552 const int minSpeed
= 4;
2553 const int maxSpeed
= 128;
2554 const int speedLimiter
= 96;
2555 const int autoScrollBorder
= 64;
2557 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2558 // This assures that the autoscrolling speed grows gradually.
2559 const int incLimiter
= 1;
2561 if (pos
< autoScrollBorder
) {
2562 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2563 inc
= qMax(inc
, -maxSpeed
);
2564 inc
= qMax(inc
, oldInc
- incLimiter
);
2565 } else if (pos
> range
- autoScrollBorder
) {
2566 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2567 inc
= qMin(inc
, maxSpeed
);
2568 inc
= qMin(inc
, oldInc
+ incLimiter
);
2574 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2576 const qreal availableSize
= size
- itemMargin
;
2577 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2583 KItemListCreatorBase::~KItemListCreatorBase()
2585 qDeleteAll(m_recycleableWidgets
);
2586 qDeleteAll(m_createdWidgets
);
2589 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2591 m_createdWidgets
.insert(widget
);
2594 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2596 Q_ASSERT(m_createdWidgets
.contains(widget
));
2597 m_createdWidgets
.remove(widget
);
2599 if (m_recycleableWidgets
.count() < 100) {
2600 m_recycleableWidgets
.append(widget
);
2601 widget
->setVisible(false);
2607 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2609 if (m_recycleableWidgets
.isEmpty()) {
2613 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2614 m_createdWidgets
.insert(widget
);
2618 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2622 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2624 widget
->setParentItem(0);
2625 widget
->setOpacity(1.0);
2626 pushRecycleableWidget(widget
);
2629 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2633 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2635 header
->setOpacity(1.0);
2636 pushRecycleableWidget(header
);
2639 #include "kitemlistview.moc"