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 int KItemListView::maximumVisibleItems() const
213 return m_layouter
->maximumVisibleItems();
216 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
218 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
219 m_visibleRoles
= roles
;
220 onVisibleRolesChanged(roles
, previousRoles
);
222 m_sizeHintResolver
->clearCache();
223 m_layouter
->markAsDirty();
225 if (m_itemSize
.isEmpty()) {
226 m_headerWidget
->setColumns(roles
);
227 updatePreferredColumnWidths();
228 if (!m_headerWidget
->automaticColumnResizing()) {
229 // The column-width of new roles are still 0. Apply the preferred
230 // column-width as default with.
231 foreach (const QByteArray
& role
, m_visibleRoles
) {
232 if (m_headerWidget
->columnWidth(role
) == 0) {
233 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
234 m_headerWidget
->setColumnWidth(role
, width
);
238 applyColumnWidthsFromHeader();
242 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
243 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
244 (roles
.count() <= 1 && previousRoles
.count() > 1));
246 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
247 while (it
.hasNext()) {
249 KItemListWidget
* widget
= it
.value();
250 widget
->setVisibleRoles(roles
);
251 if (alternateBackgroundsChanged
) {
252 updateAlternateBackgroundForWidget(widget
);
256 doLayout(NoAnimation
);
259 QList
<QByteArray
> KItemListView::visibleRoles() const
261 return m_visibleRoles
;
264 void KItemListView::setAutoScroll(bool enabled
)
266 if (enabled
&& !m_autoScrollTimer
) {
267 m_autoScrollTimer
= new QTimer(this);
268 m_autoScrollTimer
->setSingleShot(true);
269 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
270 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
271 } else if (!enabled
&& m_autoScrollTimer
) {
272 delete m_autoScrollTimer
;
273 m_autoScrollTimer
= 0;
277 bool KItemListView::autoScroll() const
279 return m_autoScrollTimer
!= 0;
282 void KItemListView::setEnabledSelectionToggles(bool enabled
)
284 if (m_enabledSelectionToggles
!= enabled
) {
285 m_enabledSelectionToggles
= enabled
;
287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
288 while (it
.hasNext()) {
290 it
.value()->setEnabledSelectionToggle(enabled
);
295 bool KItemListView::enabledSelectionToggles() const
297 return m_enabledSelectionToggles
;
300 KItemListController
* KItemListView::controller() const
305 KItemModelBase
* KItemListView::model() const
310 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
312 if (m_widgetCreator
) {
313 delete m_widgetCreator
;
315 m_widgetCreator
= widgetCreator
;
318 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
320 if (!m_widgetCreator
) {
321 m_widgetCreator
= defaultWidgetCreator();
323 return m_widgetCreator
;
326 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
328 if (m_groupHeaderCreator
) {
329 delete m_groupHeaderCreator
;
331 m_groupHeaderCreator
= groupHeaderCreator
;
334 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
336 if (!m_groupHeaderCreator
) {
337 m_groupHeaderCreator
= defaultGroupHeaderCreator();
339 return m_groupHeaderCreator
;
342 QSizeF
KItemListView::itemSize() const
347 const KItemListStyleOption
& KItemListView::styleOption() const
349 return m_styleOption
;
352 void KItemListView::setGeometry(const QRectF
& rect
)
354 QGraphicsWidget::setGeometry(rect
);
360 const QSizeF newSize
= rect
.size();
361 if (m_itemSize
.isEmpty()) {
362 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
363 if (m_headerWidget
->automaticColumnResizing()) {
364 applyAutomaticColumnWidths();
366 const qreal requiredWidth
= columnWidthsSum();
367 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
368 m_itemSize
.height());
369 m_layouter
->setItemSize(dynamicItemSize
);
372 // Triggering a synchronous layout is fine from a performance point of view,
373 // as with dynamic item sizes no moving animation must be done.
374 m_layouter
->setSize(newSize
);
375 doLayout(NoAnimation
);
377 const bool animate
= !changesItemGridLayout(newSize
,
378 m_layouter
->itemSize(),
379 m_layouter
->itemMargin());
380 m_layouter
->setSize(newSize
);
383 // Trigger an asynchronous relayout with m_layoutTimer to prevent
384 // performance bottlenecks. If the timer is exceeded, an animated layout
385 // will be triggered.
386 if (!m_layoutTimer
->isActive()) {
387 m_layoutTimer
->start();
390 m_layoutTimer
->stop();
391 doLayout(NoAnimation
);
396 qreal
KItemListView::verticalPageStep() const
398 qreal headerHeight
= 0;
399 if (m_headerWidget
->isVisible()) {
400 headerHeight
= m_headerWidget
->size().height();
402 return size().height() - headerHeight
;
405 int KItemListView::itemAt(const QPointF
& pos
) const
407 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
408 while (it
.hasNext()) {
411 const KItemListWidget
* widget
= it
.value();
412 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
413 if (widget
->contains(mappedPos
)) {
421 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
423 if (!m_enabledSelectionToggles
) {
427 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
429 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
430 if (!selectionToggleRect
.isEmpty()) {
431 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
432 return selectionToggleRect
.contains(mappedPos
);
438 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
440 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
442 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
443 if (!expansionToggleRect
.isEmpty()) {
444 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
445 return expansionToggleRect
.contains(mappedPos
);
451 int KItemListView::firstVisibleIndex() const
453 return m_layouter
->firstVisibleIndex();
456 int KItemListView::lastVisibleIndex() const
458 return m_layouter
->lastVisibleIndex();
461 QSizeF
KItemListView::itemSizeHint(int index
) const
463 return widgetCreator()->itemSizeHint(index
, this);
466 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
468 if (m_supportsItemExpanding
!= supportsExpanding
) {
469 m_supportsItemExpanding
= supportsExpanding
;
470 updateSiblingsInformation();
471 onSupportsItemExpandingChanged(supportsExpanding
);
475 bool KItemListView::supportsItemExpanding() const
477 return m_supportsItemExpanding
;
480 QRectF
KItemListView::itemRect(int index
) const
482 return m_layouter
->itemRect(index
);
485 QRectF
KItemListView::itemContextRect(int index
) const
489 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
491 contextRect
= widget
->iconRect() | widget
->textRect();
492 contextRect
.translate(itemRect(index
).topLeft());
498 void KItemListView::scrollToItem(int index
)
500 QRectF viewGeometry
= geometry();
501 if (m_headerWidget
->isVisible()) {
502 const qreal headerHeight
= m_headerWidget
->size().height();
503 viewGeometry
.adjust(0, headerHeight
, 0, 0);
505 const QRectF currentRect
= itemRect(index
);
507 if (!viewGeometry
.contains(currentRect
)) {
508 qreal newOffset
= scrollOffset();
509 if (scrollOrientation() == Qt::Vertical
) {
510 if (currentRect
.top() < viewGeometry
.top()) {
511 newOffset
+= currentRect
.top() - viewGeometry
.top();
512 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
513 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
516 if (currentRect
.left() < viewGeometry
.left()) {
517 newOffset
+= currentRect
.left() - viewGeometry
.left();
518 } else if (currentRect
.right() > viewGeometry
.right()) {
519 newOffset
+= currentRect
.right() - viewGeometry
.right();
523 if (newOffset
!= scrollOffset()) {
524 emit
scrollTo(newOffset
);
529 void KItemListView::beginTransaction()
531 ++m_activeTransactions
;
532 if (m_activeTransactions
== 1) {
533 onTransactionBegin();
537 void KItemListView::endTransaction()
539 --m_activeTransactions
;
540 if (m_activeTransactions
< 0) {
541 m_activeTransactions
= 0;
542 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
545 if (m_activeTransactions
== 0) {
547 doLayout(m_endTransactionAnimationHint
);
548 m_endTransactionAnimationHint
= Animation
;
552 bool KItemListView::isTransactionActive() const
554 return m_activeTransactions
> 0;
557 void KItemListView::setHeaderVisible(bool visible
)
559 if (visible
&& !m_headerWidget
->isVisible()) {
560 QStyleOptionHeader option
;
561 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
564 m_headerWidget
->setPos(0, 0);
565 m_headerWidget
->resize(size().width(), headerSize
.height());
566 m_headerWidget
->setModel(m_model
);
567 m_headerWidget
->setColumns(m_visibleRoles
);
568 m_headerWidget
->setZValue(1);
570 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
571 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
572 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
573 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
574 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
575 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
576 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
577 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
579 m_layouter
->setHeaderHeight(headerSize
.height());
580 m_headerWidget
->setVisible(true);
581 } else if (!visible
&& m_headerWidget
->isVisible()) {
582 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
583 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
584 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
585 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
586 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
587 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
588 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
589 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
591 m_layouter
->setHeaderHeight(0);
592 m_headerWidget
->setVisible(false);
596 bool KItemListView::isHeaderVisible() const
598 return m_headerWidget
->isVisible();
601 KItemListHeader
* KItemListView::header() const
606 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
610 if (indexes
.count() == 1) {
611 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
612 QGraphicsView
* graphicsView
= scene()->views()[0];
613 if (item
&& graphicsView
) {
614 pixmap
= item
->createDragPixmap(0, graphicsView
);
617 // TODO: Not implemented yet. Probably extend the interface
618 // from KItemListWidget::createDragPixmap() to return a pixmap
619 // that can be used for multiple indexes.
625 void KItemListView::editRole(int index
, const QByteArray
& role
)
627 KItemListWidget
* widget
= m_visibleItems
.value(index
);
628 if (!widget
|| m_editingRole
) {
632 m_editingRole
= true;
633 widget
->setEditedRole(role
);
635 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
636 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
637 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
638 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
641 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
643 QGraphicsWidget::paint(painter
, option
, widget
);
645 if (m_rubberBand
->isActive()) {
646 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
647 m_rubberBand
->endPosition()).normalized();
649 const QPointF topLeft
= rubberBandRect
.topLeft();
650 if (scrollOrientation() == Qt::Vertical
) {
651 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
653 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
656 QStyleOptionRubberBand opt
;
657 opt
.initFrom(widget
);
658 opt
.shape
= QRubberBand::Rectangle
;
660 opt
.rect
= rubberBandRect
.toRect();
661 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
664 if (!m_dropIndicator
.isEmpty()) {
665 const QRectF r
= m_dropIndicator
.toRect();
667 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
668 painter
->setPen(color
);
670 // TODO: The following implementation works only for a vertical scroll-orientation
671 // and assumes a height of the m_draggingInsertIndicator of 1.
672 Q_ASSERT(r
.height() == 1);
673 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
676 painter
->setPen(color
);
677 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
681 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
683 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
684 if (!scene()->views().isEmpty()) {
685 m_styleOption
.palette
= scene()->views().at(0)->palette();
688 return QGraphicsItem::itemChange(change
, value
);
691 void KItemListView::setItemSize(const QSizeF
& size
)
693 const QSizeF previousSize
= m_itemSize
;
694 if (size
== previousSize
) {
698 // Skip animations when the number of rows or columns
699 // are changed in the grid layout. Although the animation
700 // engine can handle this usecase, it looks obtrusive.
701 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
703 m_layouter
->itemMargin());
705 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
706 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
707 (!m_itemSize
.isEmpty() && size
.isEmpty()));
711 if (alternateBackgroundsChanged
) {
712 // For an empty item size alternate backgrounds are drawn if more than
713 // one role is shown. Assure that the backgrounds for visible items are
714 // updated when changing the size in this context.
715 updateAlternateBackgrounds();
718 if (size
.isEmpty()) {
719 if (m_headerWidget
->automaticColumnResizing()) {
720 updatePreferredColumnWidths();
722 // Only apply the changed height and respect the header widths
724 const qreal currentWidth
= m_layouter
->itemSize().width();
725 const QSizeF
newSize(currentWidth
, size
.height());
726 m_layouter
->setItemSize(newSize
);
729 m_layouter
->setItemSize(size
);
732 m_sizeHintResolver
->clearCache();
733 doLayout(animate
? Animation
: NoAnimation
);
734 onItemSizeChanged(size
, previousSize
);
737 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
739 const KItemListStyleOption previousOption
= m_styleOption
;
740 m_styleOption
= option
;
743 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
744 if (margin
!= m_layouter
->itemMargin()) {
745 // Skip animations when the number of rows or columns
746 // are changed in the grid layout. Although the animation
747 // engine can handle this usecase, it looks obtrusive.
748 animate
= !changesItemGridLayout(m_layouter
->size(),
749 m_layouter
->itemSize(),
751 m_layouter
->setItemMargin(margin
);
755 updateGroupHeaderHeight();
758 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
759 // Animating a change of the maximum text size just results in expensive
760 // temporary eliding and clipping operations and does not look good visually.
764 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
765 while (it
.hasNext()) {
767 it
.value()->setStyleOption(option
);
770 m_sizeHintResolver
->clearCache();
771 m_layouter
->markAsDirty();
772 doLayout(animate
? Animation
: NoAnimation
);
774 if (m_itemSize
.isEmpty()) {
775 updatePreferredColumnWidths();
778 onStyleOptionChanged(option
, previousOption
);
781 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
783 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
784 if (orientation
== previousOrientation
) {
788 m_layouter
->setScrollOrientation(orientation
);
789 m_animation
->setScrollOrientation(orientation
);
790 m_sizeHintResolver
->clearCache();
793 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
794 while (it
.hasNext()) {
796 it
.value()->setScrollOrientation(orientation
);
798 updateGroupHeaderHeight();
802 doLayout(NoAnimation
);
804 onScrollOrientationChanged(orientation
, previousOrientation
);
805 emit
scrollOrientationChanged(orientation
, previousOrientation
);
808 Qt::Orientation
KItemListView::scrollOrientation() const
810 return m_layouter
->scrollOrientation();
813 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
818 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
823 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
828 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
830 Q_UNUSED(changedRoles
);
834 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
840 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
846 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
852 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
858 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
864 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
870 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
876 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
878 Q_UNUSED(supportsExpanding
);
881 void KItemListView::onTransactionBegin()
885 void KItemListView::onTransactionEnd()
889 bool KItemListView::event(QEvent
* event
)
891 // Forward all events to the controller and handle them there
892 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
896 return QGraphicsWidget::event(event
);
899 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
901 m_mousePos
= transform().map(event
->pos());
905 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
907 QGraphicsWidget::mouseMoveEvent(event
);
909 m_mousePos
= transform().map(event
->pos());
910 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
911 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
915 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
917 event
->setAccepted(true);
921 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
923 QGraphicsWidget::dragMoveEvent(event
);
925 m_mousePos
= transform().map(event
->pos());
926 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
927 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
931 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
933 QGraphicsWidget::dragLeaveEvent(event
);
934 setAutoScroll(false);
937 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
939 QGraphicsWidget::dropEvent(event
);
940 setAutoScroll(false);
943 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
945 return m_visibleItems
.values();
948 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
950 if (m_itemSize
.isEmpty()) {
951 updatePreferredColumnWidths(itemRanges
);
954 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
955 if (hasMultipleRanges
) {
959 m_layouter
->markAsDirty();
961 int previouslyInsertedCount
= 0;
962 foreach (const KItemRange
& range
, itemRanges
) {
963 // range.index is related to the model before anything has been inserted.
964 // As in each loop the current item-range gets inserted the index must
965 // be increased by the already previously inserted items.
966 const int index
= range
.index
+ previouslyInsertedCount
;
967 const int count
= range
.count
;
968 if (index
< 0 || count
<= 0) {
969 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
972 previouslyInsertedCount
+= count
;
974 m_sizeHintResolver
->itemsInserted(index
, count
);
976 // Determine which visible items must be moved
977 QList
<int> itemsToMove
;
978 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
979 while (it
.hasNext()) {
981 const int visibleItemIndex
= it
.key();
982 if (visibleItemIndex
>= index
) {
983 itemsToMove
.append(visibleItemIndex
);
987 // Update the indexes of all KItemListWidget instances that are located
988 // after the inserted items. It is important to adjust the indexes in the order
989 // from the highest index to the lowest index to prevent overlaps when setting the new index.
991 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
992 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
994 const int newIndex
= widget
->index() + count
;
995 if (hasMultipleRanges
) {
996 setWidgetIndex(widget
, newIndex
);
998 // Try to animate the moving of the item
999 moveWidgetToIndex(widget
, newIndex
);
1003 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1004 // Check whether a scrollbar is required to show the inserted items. In this case
1005 // the size of the layouter will be decreased before calling doLayout(): This prevents
1006 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1007 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1008 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1009 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1010 if (decreaseLayouterSize
) {
1011 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1012 QSizeF layouterSize
= m_layouter
->size();
1013 if (verticalScrollOrientation
) {
1014 layouterSize
.rwidth() -= scrollBarExtent
;
1016 layouterSize
.rheight() -= scrollBarExtent
;
1018 m_layouter
->setSize(layouterSize
);
1022 if (!hasMultipleRanges
) {
1023 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1024 updateSiblingsInformation();
1029 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1032 if (hasMultipleRanges
) {
1034 // Important: Don't read any m_layouter-property inside the for-loop in case if
1035 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1036 // updated in each loop-cycle and has only a consistent state after the loop.
1037 Q_ASSERT(m_layouter
->isDirty());
1039 m_endTransactionAnimationHint
= NoAnimation
;
1042 updateSiblingsInformation();
1045 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1046 // In case if items of the same group have been inserted before an item that
1047 // currently represents the first item of the group, the group header of
1048 // this item must be removed.
1049 updateVisibleGroupHeaders();
1052 if (useAlternateBackgrounds()) {
1053 updateAlternateBackgrounds();
1057 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1059 if (m_itemSize
.isEmpty()) {
1060 // Don't pass the item-range: The preferred column-widths of
1061 // all items must be adjusted when removing items.
1062 updatePreferredColumnWidths();
1065 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1066 if (hasMultipleRanges
) {
1070 m_layouter
->markAsDirty();
1072 int removedItemsCount
= 0;
1073 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1074 removedItemsCount
+= itemRanges
[i
].count
;
1077 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1078 const KItemRange
& range
= itemRanges
[i
];
1079 const int index
= range
.index
;
1080 const int count
= range
.count
;
1081 if (index
< 0 || count
<= 0) {
1082 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1086 m_sizeHintResolver
->itemsRemoved(index
, count
);
1088 const int firstRemovedIndex
= index
;
1089 const int lastRemovedIndex
= index
+ count
- 1;
1090 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1091 removedItemsCount
-= count
;
1093 // Remove all KItemListWidget instances that got deleted
1094 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1095 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1100 m_animation
->stop(widget
);
1101 // Stopping the animation might lead to recycling the widget if
1102 // it is invisible (see slotAnimationFinished()).
1103 // Check again whether it is still visible:
1104 if (!m_visibleItems
.contains(i
)) {
1108 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1109 // Remove the widget without animation
1110 recycleWidget(widget
);
1112 // Animate the removing of the items. Special case: When removing an item there
1113 // is no valid model index available anymore. For the
1114 // remove-animation the item gets removed from m_visibleItems but the widget
1115 // will stay alive until the animation has been finished and will
1116 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1117 m_visibleItems
.remove(i
);
1118 widget
->setIndex(-1);
1119 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1123 // Update the indexes of all KItemListWidget instances that are located
1124 // after the deleted items
1125 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1126 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1128 const int newIndex
= i
- count
;
1129 if (hasMultipleRanges
) {
1130 setWidgetIndex(widget
, newIndex
);
1132 // Try to animate the moving of the item
1133 moveWidgetToIndex(widget
, newIndex
);
1138 if (!hasMultipleRanges
) {
1139 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1140 // assumes an updated geometry. If items are removed during an active transaction,
1141 // the transaction will be temporary deactivated so that doLayout() triggers a
1142 // geometry update if necessary.
1143 const int activeTransactions
= m_activeTransactions
;
1144 m_activeTransactions
= 0;
1145 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1146 m_activeTransactions
= activeTransactions
;
1147 updateSiblingsInformation();
1152 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1155 if (hasMultipleRanges
) {
1157 // Important: Don't read any m_layouter-property inside the for-loop in case if
1158 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1159 // updated in each loop-cycle and has only a consistent state after the loop.
1160 // TODO: This assert can be hit when filtering in Icons and Compact view,
1161 // see https://bugs.kde.org/show_bug.cgi?id=317827 comments 2 and 3.
1162 // We should try to figure out if the assert is wrong or if there is a bug in the code.
1163 //Q_ASSERT(m_layouter->isDirty());
1165 m_endTransactionAnimationHint
= NoAnimation
;
1167 updateSiblingsInformation();
1170 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1171 // In case if the first item of a group has been removed, the group header
1172 // must be applied to the next visible item.
1173 updateVisibleGroupHeaders();
1176 if (useAlternateBackgrounds()) {
1177 updateAlternateBackgrounds();
1181 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1183 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1184 m_layouter
->markAsDirty();
1187 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1190 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1191 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1193 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1194 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1196 updateWidgetProperties(widget
, index
);
1197 initializeItemListWidget(widget
);
1201 doLayout(NoAnimation
);
1202 updateSiblingsInformation();
1205 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1206 const QSet
<QByteArray
>& roles
)
1208 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1209 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1210 updatePreferredColumnWidths(itemRanges
);
1213 foreach (const KItemRange
& itemRange
, itemRanges
) {
1214 const int index
= itemRange
.index
;
1215 const int count
= itemRange
.count
;
1217 if (updateSizeHints
) {
1218 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1219 m_layouter
->markAsDirty();
1221 if (!m_layoutTimer
->isActive()) {
1222 m_layoutTimer
->start();
1226 // Apply the changed roles to the visible item-widgets
1227 const int lastIndex
= index
+ count
- 1;
1228 for (int i
= index
; i
<= lastIndex
; ++i
) {
1229 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1231 widget
->setData(m_model
->data(i
), roles
);
1235 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1236 // The sort-role has been changed which might result
1237 // in modified group headers
1238 updateVisibleGroupHeaders();
1239 doLayout(NoAnimation
);
1242 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1245 void KItemListView::slotGroupedSortingChanged(bool current
)
1247 m_grouped
= current
;
1248 m_layouter
->markAsDirty();
1251 updateGroupHeaderHeight();
1253 // Clear all visible headers
1254 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1255 while (it
.hasNext()) {
1257 recycleGroupHeaderForWidget(it
.key());
1259 Q_ASSERT(m_visibleGroups
.isEmpty());
1262 if (useAlternateBackgrounds()) {
1263 // Changing the group mode requires to update the alternate backgrounds
1264 // as with the enabled group mode the altering is done on base of the first
1266 updateAlternateBackgrounds();
1268 updateSiblingsInformation();
1269 doLayout(NoAnimation
);
1272 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1277 updateVisibleGroupHeaders();
1278 doLayout(NoAnimation
);
1282 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1287 updateVisibleGroupHeaders();
1288 doLayout(NoAnimation
);
1292 void KItemListView::slotCurrentChanged(int current
, int previous
)
1296 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1297 if (previousWidget
) {
1298 previousWidget
->setCurrent(false);
1301 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1302 if (currentWidget
) {
1303 currentWidget
->setCurrent(true);
1305 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1308 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1312 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1313 while (it
.hasNext()) {
1315 const int index
= it
.key();
1316 KItemListWidget
* widget
= it
.value();
1317 widget
->setSelected(current
.contains(index
));
1321 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1322 KItemListViewAnimation::AnimationType type
)
1324 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1325 Q_ASSERT(itemListWidget
);
1328 case KItemListViewAnimation::DeleteAnimation
: {
1329 // As we recycle the widget in this case it is important to assure that no
1330 // other animation has been started. This is a convention in KItemListView and
1331 // not a requirement defined by KItemListViewAnimation.
1332 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1334 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1335 // by m_visibleWidgets and must be deleted manually after the animation has
1337 recycleGroupHeaderForWidget(itemListWidget
);
1338 widgetCreator()->recycle(itemListWidget
);
1342 case KItemListViewAnimation::CreateAnimation
:
1343 case KItemListViewAnimation::MovingAnimation
:
1344 case KItemListViewAnimation::ResizeAnimation
: {
1345 const int index
= itemListWidget
->index();
1346 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1347 (index
> m_layouter
->lastVisibleIndex());
1348 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1349 recycleWidget(itemListWidget
);
1358 void KItemListView::slotLayoutTimerFinished()
1360 m_layouter
->setSize(geometry().size());
1361 doLayout(Animation
);
1364 void KItemListView::slotRubberBandPosChanged()
1369 void KItemListView::slotRubberBandActivationChanged(bool active
)
1372 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1373 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1374 m_skipAutoScrollForRubberBand
= true;
1376 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1377 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1378 m_skipAutoScrollForRubberBand
= false;
1384 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1386 qreal previousWidth
)
1389 Q_UNUSED(currentWidth
);
1390 Q_UNUSED(previousWidth
);
1392 m_headerWidget
->setAutomaticColumnResizing(false);
1393 applyColumnWidthsFromHeader();
1394 doLayout(NoAnimation
);
1397 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1401 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1403 const QList
<QByteArray
> previous
= m_visibleRoles
;
1405 QList
<QByteArray
> current
= m_visibleRoles
;
1406 current
.removeAt(previousIndex
);
1407 current
.insert(currentIndex
, role
);
1409 setVisibleRoles(current
);
1411 emit
visibleRolesChanged(current
, previous
);
1414 void KItemListView::triggerAutoScrolling()
1416 if (!m_autoScrollTimer
) {
1421 int visibleSize
= 0;
1422 if (scrollOrientation() == Qt::Vertical
) {
1423 pos
= m_mousePos
.y();
1424 visibleSize
= size().height();
1426 pos
= m_mousePos
.x();
1427 visibleSize
= size().width();
1430 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1431 m_autoScrollIncrement
= 0;
1434 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1435 if (m_autoScrollIncrement
== 0) {
1436 // The mouse position is not above an autoscroll margin (the autoscroll timer
1437 // will be restarted in mouseMoveEvent())
1438 m_autoScrollTimer
->stop();
1442 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1443 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1444 // if the direction of the rubberband is similar to the autoscroll direction. This
1445 // prevents that starting to create a rubberband within the autoscroll margins starts
1446 // an autoscrolling.
1448 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1449 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1450 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1451 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1452 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1453 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1454 // been moved up although the autoscroll direction might be down)
1455 m_autoScrollTimer
->stop();
1460 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1461 // the autoscrolling may not get skipped anymore until a new rubberband is created
1462 m_skipAutoScrollForRubberBand
= false;
1464 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1465 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1466 setScrollOffset(newScrollOffset
);
1468 // Trigger the autoscroll timer which will periodically call
1469 // triggerAutoScrolling()
1470 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1473 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1475 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1477 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1478 Q_ASSERT(groupHeader
);
1479 updateGroupHeaderLayout(widget
);
1482 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1484 disconnectRoleEditingSignals(index
);
1486 emit
roleEditingCanceled(index
, role
, value
);
1487 m_editingRole
= false;
1490 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1492 disconnectRoleEditingSignals(index
);
1494 emit
roleEditingFinished(index
, role
, value
);
1495 m_editingRole
= false;
1498 void KItemListView::setController(KItemListController
* controller
)
1500 if (m_controller
!= controller
) {
1501 KItemListController
* previous
= m_controller
;
1503 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1504 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1505 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1508 m_controller
= controller
;
1511 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1512 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1513 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1516 onControllerChanged(controller
, previous
);
1520 void KItemListView::setModel(KItemModelBase
* model
)
1522 if (m_model
== model
) {
1526 KItemModelBase
* previous
= m_model
;
1529 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1530 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1531 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1532 this, SLOT(slotItemsInserted(KItemRangeList
)));
1533 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1534 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1535 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1536 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1537 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1538 this, SLOT(slotGroupedSortingChanged(bool)));
1539 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1540 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1541 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1542 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1545 m_sizeHintResolver
->clearCache();
1548 m_layouter
->setModel(model
);
1549 m_grouped
= model
->groupedSorting();
1552 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1553 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1554 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1555 this, SLOT(slotItemsInserted(KItemRangeList
)));
1556 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1557 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1558 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1559 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1560 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1561 this, SLOT(slotGroupedSortingChanged(bool)));
1562 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1563 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1564 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1565 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1567 const int itemCount
= m_model
->count();
1568 if (itemCount
> 0) {
1569 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1570 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1574 onModelChanged(model
, previous
);
1577 KItemListRubberBand
* KItemListView::rubberBand() const
1579 return m_rubberBand
;
1582 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1584 if (m_layoutTimer
->isActive()) {
1585 m_layoutTimer
->stop();
1588 if (m_activeTransactions
> 0) {
1589 if (hint
== NoAnimation
) {
1590 // As soon as at least one property change should be done without animation,
1591 // the whole transaction will be marked as not animated.
1592 m_endTransactionAnimationHint
= NoAnimation
;
1597 if (!m_model
|| m_model
->count() < 0) {
1601 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1602 if (firstVisibleIndex
< 0) {
1603 emitOffsetChanges();
1607 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1608 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1609 // is still shown if the maximum offset got decreased.
1610 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1611 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1612 if (scrollOffset() > maxOffsetToShowFullRange
) {
1613 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1614 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1617 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1619 int firstSibblingIndex
= -1;
1620 int lastSibblingIndex
= -1;
1621 const bool supportsExpanding
= supportsItemExpanding();
1623 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1625 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1626 // instances from invisible items are reused. If no reusable items are
1627 // found then new KItemListWidget instances get created.
1628 const bool animate
= (hint
== Animation
);
1629 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1630 bool applyNewPos
= true;
1631 bool wasHidden
= false;
1633 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1634 const QPointF newPos
= itemBounds
.topLeft();
1635 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1638 if (!reusableItems
.isEmpty()) {
1639 // Reuse a KItemListWidget instance from an invisible item
1640 const int oldIndex
= reusableItems
.takeLast();
1641 widget
= m_visibleItems
.value(oldIndex
);
1642 setWidgetIndex(widget
, i
);
1643 updateWidgetProperties(widget
, i
);
1644 initializeItemListWidget(widget
);
1646 // No reusable KItemListWidget instance is available, create a new one
1647 widget
= createWidget(i
);
1649 widget
->resize(itemBounds
.size());
1651 if (animate
&& changedCount
< 0) {
1652 // Items have been deleted, move the created item to the
1653 // imaginary old position. They will get animated to the new position
1655 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1656 if (itemRect
.isEmpty()) {
1657 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1658 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1659 widget
->setPos(invisibleOldPos
);
1661 widget
->setPos(itemRect
.topLeft());
1663 applyNewPos
= false;
1666 if (supportsExpanding
&& changedCount
== 0) {
1667 if (firstSibblingIndex
< 0) {
1668 firstSibblingIndex
= i
;
1670 lastSibblingIndex
= i
;
1675 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1676 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1677 applyNewPos
= false;
1680 const bool itemsRemoved
= (changedCount
< 0);
1681 const bool itemsInserted
= (changedCount
> 0);
1682 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1683 // The item is located after the removed items. Animate the moving of the position.
1684 applyNewPos
= !moveWidget(widget
, newPos
);
1685 } else if (itemsInserted
&& i
>= changedIndex
) {
1686 // The item is located after the first inserted item
1687 if (i
<= changedIndex
+ changedCount
- 1) {
1688 // The item is an inserted item. Animate the appearing of the item.
1689 // For performance reasons no animation is done when changedCount is equal
1690 // to all available items.
1691 if (changedCount
< m_model
->count()) {
1692 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1694 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1695 // The item was already there before, so animate the moving of the position.
1696 // No moving animation is done if the item is animated by a create animation: This
1697 // prevents a "move animation mess" when inserting several ranges in parallel.
1698 applyNewPos
= !moveWidget(widget
, newPos
);
1700 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1701 // The size of the view might have been changed. Animate the moving of the position.
1702 applyNewPos
= !moveWidget(widget
, newPos
);
1705 m_animation
->stop(widget
);
1709 widget
->setPos(newPos
);
1712 Q_ASSERT(widget
->index() == i
);
1713 widget
->setVisible(true);
1715 if (widget
->size() != itemBounds
.size()) {
1716 // Resize the widget for the item to the changed size.
1718 // If a dynamic item size is used then no animation is done in the direction
1719 // of the dynamic size.
1720 if (m_itemSize
.width() <= 0) {
1721 // The width is dynamic, apply the new width without animation.
1722 widget
->resize(itemBounds
.width(), widget
->size().height());
1723 } else if (m_itemSize
.height() <= 0) {
1724 // The height is dynamic, apply the new height without animation.
1725 widget
->resize(widget
->size().width(), itemBounds
.height());
1727 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1729 widget
->resize(itemBounds
.size());
1733 // Updating the cell-information must be done as last step: The decision whether the
1734 // moving-animation should be started at all is based on the previous cell-information.
1735 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1736 m_visibleCells
.insert(i
, cell
);
1739 // Delete invisible KItemListWidget instances that have not been reused
1740 foreach (int index
, reusableItems
) {
1741 recycleWidget(m_visibleItems
.value(index
));
1744 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1745 Q_ASSERT(lastSibblingIndex
>= 0);
1746 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1750 // Update the layout of all visible group headers
1751 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1752 while (it
.hasNext()) {
1754 updateGroupHeaderLayout(it
.key());
1758 emitOffsetChanges();
1761 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1762 int lastVisibleIndex
,
1763 LayoutAnimationHint hint
)
1765 // Determine all items that are completely invisible and might be
1766 // reused for items that just got (at least partly) visible. If the
1767 // animation hint is set to 'Animation' items that do e.g. an animated
1768 // moving of their position are not marked as invisible: This assures
1769 // that a scrolling inside the view can be done without breaking an animation.
1773 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1774 while (it
.hasNext()) {
1777 KItemListWidget
* widget
= it
.value();
1778 const int index
= widget
->index();
1779 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1782 if (m_animation
->isStarted(widget
)) {
1783 if (hint
== NoAnimation
) {
1784 // Stopping the animation will call KItemListView::slotAnimationFinished()
1785 // and the widget will be recycled if necessary there.
1786 m_animation
->stop(widget
);
1789 widget
->setVisible(false);
1790 items
.append(index
);
1793 recycleGroupHeaderForWidget(widget
);
1802 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1804 if (widget
->pos() == newPos
) {
1808 bool startMovingAnim
= false;
1810 if (m_itemSize
.isEmpty()) {
1811 // The items are not aligned in a grid but either as columns or rows.
1812 startMovingAnim
= true;
1814 // When having a grid the moving-animation should only be started, if it is done within
1815 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1816 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1817 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1818 const int index
= widget
->index();
1819 const Cell cell
= m_visibleCells
.value(index
);
1820 if (cell
.column
>= 0 && cell
.row
>= 0) {
1821 if (scrollOrientation() == Qt::Vertical
) {
1822 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1824 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1829 if (startMovingAnim
) {
1830 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1834 m_animation
->stop(widget
);
1835 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1839 void KItemListView::emitOffsetChanges()
1841 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1842 if (m_oldScrollOffset
!= newScrollOffset
) {
1843 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1844 m_oldScrollOffset
= newScrollOffset
;
1847 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1848 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1849 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1850 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1853 const qreal newItemOffset
= m_layouter
->itemOffset();
1854 if (m_oldItemOffset
!= newItemOffset
) {
1855 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1856 m_oldItemOffset
= newItemOffset
;
1859 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1860 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1861 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1862 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1866 KItemListWidget
* KItemListView::createWidget(int index
)
1868 KItemListWidget
* widget
= widgetCreator()->create(this);
1869 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1871 m_visibleItems
.insert(index
, widget
);
1872 m_visibleCells
.insert(index
, Cell());
1873 updateWidgetProperties(widget
, index
);
1874 initializeItemListWidget(widget
);
1878 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1881 recycleGroupHeaderForWidget(widget
);
1884 const int index
= widget
->index();
1885 m_visibleItems
.remove(index
);
1886 m_visibleCells
.remove(index
);
1888 widgetCreator()->recycle(widget
);
1891 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1893 const int oldIndex
= widget
->index();
1894 m_visibleItems
.remove(oldIndex
);
1895 m_visibleCells
.remove(oldIndex
);
1897 m_visibleItems
.insert(index
, widget
);
1898 m_visibleCells
.insert(index
, Cell());
1900 widget
->setIndex(index
);
1903 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1905 const int oldIndex
= widget
->index();
1906 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1908 setWidgetIndex(widget
, index
);
1910 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1911 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1912 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1913 (!vertical
&& oldCell
.column
== newCell
.column
);
1915 m_visibleCells
.insert(index
, newCell
);
1919 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1922 case LayouterSize
: m_layouter
->setSize(size
); break;
1923 case ItemSize
: m_layouter
->setItemSize(size
); break;
1928 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1930 widget
->setVisibleRoles(m_visibleRoles
);
1931 updateWidgetColumnWidths(widget
);
1932 widget
->setStyleOption(m_styleOption
);
1934 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1935 widget
->setCurrent(index
== selectionManager
->currentItem());
1936 widget
->setSelected(selectionManager
->isSelected(index
));
1937 widget
->setHovered(false);
1938 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1939 widget
->setIndex(index
);
1940 widget
->setData(m_model
->data(index
));
1941 widget
->setSiblingsInformation(QBitArray());
1942 updateAlternateBackgroundForWidget(widget
);
1945 updateGroupHeaderForWidget(widget
);
1949 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1951 Q_ASSERT(m_grouped
);
1953 const int index
= widget
->index();
1954 if (!m_layouter
->isFirstGroupItem(index
)) {
1955 // The widget does not represent the first item of a group
1956 // and hence requires no header
1957 recycleGroupHeaderForWidget(widget
);
1961 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1962 if (groups
.isEmpty() || !groupHeaderCreator()) {
1966 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1968 groupHeader
= groupHeaderCreator()->create(this);
1969 groupHeader
->setParentItem(widget
);
1970 m_visibleGroups
.insert(widget
, groupHeader
);
1971 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1973 Q_ASSERT(groupHeader
->parentItem() == widget
);
1975 const int groupIndex
= groupIndexForItem(index
);
1976 Q_ASSERT(groupIndex
>= 0);
1977 groupHeader
->setData(groups
.at(groupIndex
).second
);
1978 groupHeader
->setRole(model()->sortRole());
1979 groupHeader
->setStyleOption(m_styleOption
);
1980 groupHeader
->setScrollOrientation(scrollOrientation());
1981 groupHeader
->setItemIndex(index
);
1983 groupHeader
->show();
1986 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1988 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1989 Q_ASSERT(groupHeader
);
1991 const int index
= widget
->index();
1992 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1993 const QRectF itemRect
= m_layouter
->itemRect(index
);
1995 // The group-header is a child of the itemlist widget. Translate the
1996 // group header position to the relative position.
1997 if (scrollOrientation() == Qt::Vertical
) {
1998 // In the vertical scroll orientation the group header should always span
1999 // the whole width no matter which temporary position the parent widget
2000 // has. In this case the x-position and width will be adjusted manually.
2001 const qreal x
= -widget
->x() - itemOffset();
2002 const qreal width
= maximumItemOffset();
2003 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2004 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2006 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2007 groupHeader
->resize(groupHeaderRect
.size());
2011 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2013 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2015 header
->setParentItem(0);
2016 groupHeaderCreator()->recycle(header
);
2017 m_visibleGroups
.remove(widget
);
2018 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2022 void KItemListView::updateVisibleGroupHeaders()
2024 Q_ASSERT(m_grouped
);
2025 m_layouter
->markAsDirty();
2027 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2028 while (it
.hasNext()) {
2030 updateGroupHeaderForWidget(it
.value());
2034 int KItemListView::groupIndexForItem(int index
) const
2036 Q_ASSERT(m_grouped
);
2038 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2039 if (groups
.isEmpty()) {
2044 int max
= groups
.count() - 1;
2047 mid
= (min
+ max
) / 2;
2048 if (index
> groups
[mid
].first
) {
2053 } while (groups
[mid
].first
!= index
&& min
<= max
);
2056 while (groups
[mid
].first
> index
&& mid
> 0) {
2064 void KItemListView::updateAlternateBackgrounds()
2066 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2067 while (it
.hasNext()) {
2069 updateAlternateBackgroundForWidget(it
.value());
2073 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2075 bool enabled
= useAlternateBackgrounds();
2077 const int index
= widget
->index();
2078 enabled
= (index
& 0x1) > 0;
2080 const int groupIndex
= groupIndexForItem(index
);
2081 if (groupIndex
>= 0) {
2082 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2083 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2084 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2085 enabled
= (relativeIndex
& 0x1) > 0;
2089 widget
->setAlternateBackground(enabled
);
2092 bool KItemListView::useAlternateBackgrounds() const
2094 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2097 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2099 QElapsedTimer timer
;
2102 QHash
<QByteArray
, qreal
> widths
;
2104 // Calculate the minimum width for each column that is required
2105 // to show the headline unclipped.
2106 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2107 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2108 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2109 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2110 const QString headerText
= m_model
->roleDescription(visibleRole
);
2111 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2112 widths
.insert(visibleRole
, headerWidth
);
2115 // Calculate the preferred column withs for each item and ignore values
2116 // smaller than the width for showing the headline unclipped.
2117 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2118 int calculatedItemCount
= 0;
2119 bool maxTimeExceeded
= false;
2120 foreach (const KItemRange
& itemRange
, itemRanges
) {
2121 const int startIndex
= itemRange
.index
;
2122 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2124 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2125 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2126 qreal maxWidth
= widths
.value(visibleRole
, 0);
2127 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2128 maxWidth
= qMax(width
, maxWidth
);
2129 widths
.insert(visibleRole
, maxWidth
);
2132 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2133 // When having several thousands of items calculating the sizes can get
2134 // very expensive. We accept a possibly too small role-size in favour
2135 // of having no blocking user interface.
2136 maxTimeExceeded
= true;
2139 ++calculatedItemCount
;
2141 if (maxTimeExceeded
) {
2149 void KItemListView::applyColumnWidthsFromHeader()
2151 // Apply the new size to the layouter
2152 const qreal requiredWidth
= columnWidthsSum();
2153 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2154 m_itemSize
.height());
2155 m_layouter
->setItemSize(dynamicItemSize
);
2157 // Update the role sizes for all visible widgets
2158 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2159 while (it
.hasNext()) {
2161 updateWidgetColumnWidths(it
.value());
2165 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2167 foreach (const QByteArray
& role
, m_visibleRoles
) {
2168 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2172 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2174 Q_ASSERT(m_itemSize
.isEmpty());
2175 const int itemCount
= m_model
->count();
2176 int rangesItemCount
= 0;
2177 foreach (const KItemRange
& range
, itemRanges
) {
2178 rangesItemCount
+= range
.count
;
2181 if (itemCount
== rangesItemCount
) {
2182 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2183 foreach (const QByteArray
& role
, m_visibleRoles
) {
2184 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2187 // Only a sub range of the roles need to be determined.
2188 // The chances are good that the widths of the sub ranges
2189 // already fit into the available widths and hence no
2190 // expensive update might be required.
2191 bool changed
= false;
2193 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2194 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2195 while (it
.hasNext()) {
2197 const QByteArray
& role
= it
.key();
2198 const qreal updatedWidth
= it
.value();
2199 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2200 if (updatedWidth
> currentWidth
) {
2201 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2207 // All the updated sizes are smaller than the current sizes and no change
2208 // of the stretched roles-widths is required
2213 if (m_headerWidget
->automaticColumnResizing()) {
2214 applyAutomaticColumnWidths();
2218 void KItemListView::updatePreferredColumnWidths()
2221 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2225 void KItemListView::applyAutomaticColumnWidths()
2227 Q_ASSERT(m_itemSize
.isEmpty());
2228 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2229 if (m_visibleRoles
.isEmpty()) {
2233 // Calculate the maximum size of an item by considering the
2234 // visible role sizes and apply them to the layouter. If the
2235 // size does not use the available view-size the size of the
2236 // first role will get stretched.
2238 foreach (const QByteArray
& role
, m_visibleRoles
) {
2239 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2240 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2243 const QByteArray firstRole
= m_visibleRoles
.first();
2244 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2245 QSizeF dynamicItemSize
= m_itemSize
;
2247 qreal requiredWidth
= columnWidthsSum();
2248 const qreal availableWidth
= size().width();
2249 if (requiredWidth
< availableWidth
) {
2250 // Stretch the first column to use the whole remaining width
2251 firstColumnWidth
+= availableWidth
- requiredWidth
;
2252 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2253 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2254 // Shrink the first column to be able to show as much other
2255 // columns as possible
2256 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2258 // TODO: A proper calculation of the minimum width depends on the implementation
2259 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2261 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2262 if (shrinkedFirstColumnWidth
< minWidth
) {
2263 shrinkedFirstColumnWidth
= minWidth
;
2266 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2267 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2270 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2272 m_layouter
->setItemSize(dynamicItemSize
);
2274 // Update the role sizes for all visible widgets
2275 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2276 while (it
.hasNext()) {
2278 updateWidgetColumnWidths(it
.value());
2282 qreal
KItemListView::columnWidthsSum() const
2284 qreal widthsSum
= 0;
2285 foreach (const QByteArray
& role
, m_visibleRoles
) {
2286 widthsSum
+= m_headerWidget
->columnWidth(role
);
2291 QRectF
KItemListView::headerBoundaries() const
2293 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2296 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2297 const QSizeF
& newItemSize
,
2298 const QSizeF
& newItemMargin
) const
2300 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2304 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2305 const qreal itemWidth
= m_layouter
->itemSize().width();
2306 if (itemWidth
> 0) {
2307 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2308 newItemSize
.width(),
2309 newItemMargin
.width());
2310 if (m_model
->count() > newColumnCount
) {
2311 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2313 m_layouter
->itemMargin().width());
2314 return oldColumnCount
!= newColumnCount
;
2318 const qreal itemHeight
= m_layouter
->itemSize().height();
2319 if (itemHeight
> 0) {
2320 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2321 newItemSize
.height(),
2322 newItemMargin
.height());
2323 if (m_model
->count() > newRowCount
) {
2324 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2326 m_layouter
->itemMargin().height());
2327 return oldRowCount
!= newRowCount
;
2335 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2337 if (m_itemSize
.isEmpty()) {
2338 // We have only columns or only rows, but no grid: An animation is usually
2339 // welcome when inserting or removing items.
2340 return !supportsItemExpanding();
2343 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2347 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2348 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2349 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2350 // Only animate if up to 2/3 of a row or column are inserted or removed
2351 return changedItemCount
<= maximum
* 2 / 3;
2355 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2357 const QSizeF oldSize
= m_layouter
->size();
2359 m_layouter
->setSize(size
);
2360 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2361 m_layouter
->setSize(oldSize
);
2363 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2364 : maxOffset
> size
.width();
2367 int KItemListView::showDropIndicator(const QPointF
& pos
)
2369 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2370 while (it
.hasNext()) {
2372 const KItemListWidget
* widget
= it
.value();
2374 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2375 const QRectF rect
= itemRect(widget
->index());
2376 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2377 if (m_model
->supportsDropping(widget
->index())) {
2378 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2379 const int gap
= qMax(4.0, 0.3 * rect
.height());
2380 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2385 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2386 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2388 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2389 if (m_dropIndicator
!= draggingInsertIndicator
) {
2390 m_dropIndicator
= draggingInsertIndicator
;
2394 int index
= widget
->index();
2402 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2403 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2406 void KItemListView::hideDropIndicator()
2408 if (!m_dropIndicator
.isNull()) {
2409 m_dropIndicator
= QRectF();
2414 void KItemListView::updateGroupHeaderHeight()
2416 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2417 qreal groupHeaderMargin
= 0;
2419 if (scrollOrientation() == Qt::Horizontal
) {
2420 // The vertical margin above and below the header should be
2421 // equal to the horizontal margin, not the vertical margin
2422 // from m_styleOption.
2423 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2424 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2425 } else if (m_itemSize
.isEmpty()){
2426 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2427 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2429 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2430 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2432 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2433 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2435 updateVisibleGroupHeaders();
2438 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2440 if (!supportsItemExpanding() || !m_model
) {
2444 if (firstIndex
< 0 || lastIndex
< 0) {
2445 firstIndex
= m_layouter
->firstVisibleIndex();
2446 lastIndex
= m_layouter
->lastVisibleIndex();
2448 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2449 lastIndex
>= m_layouter
->firstVisibleIndex());
2450 if (!isRangeVisible
) {
2455 int previousParents
= 0;
2456 QBitArray previousSiblings
;
2458 // The rootIndex describes the first index where the siblings get
2459 // calculated from. For the calculation the upper most parent item
2460 // is required. For performance reasons it is checked first whether
2461 // the visible items before or after the current range already
2462 // contain a siblings information which can be used as base.
2463 int rootIndex
= firstIndex
;
2465 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2467 // There is no visible widget before the range, check whether there
2468 // is one after the range:
2469 widget
= m_visibleItems
.value(lastIndex
+ 1);
2471 // The sibling information of the widget may only be used if
2472 // all items of the range have the same number of parents.
2473 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2474 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2475 if (m_model
->expandedParentsCount(i
) != parents
) {
2484 // Performance optimization: Use the sibling information of the visible
2485 // widget beside the given range.
2486 previousSiblings
= widget
->siblingsInformation();
2487 if (previousSiblings
.isEmpty()) {
2490 previousParents
= previousSiblings
.count() - 1;
2491 previousSiblings
.truncate(previousParents
);
2493 // Potentially slow path: Go back to the upper most parent of firstIndex
2494 // to be able to calculate the initial value for the siblings.
2495 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2500 Q_ASSERT(previousParents
>= 0);
2501 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2502 // Update the parent-siblings in case if the current item represents
2503 // a child or an upper parent.
2504 const int currentParents
= m_model
->expandedParentsCount(i
);
2505 Q_ASSERT(currentParents
>= 0);
2506 if (previousParents
< currentParents
) {
2507 previousParents
= currentParents
;
2508 previousSiblings
.resize(currentParents
);
2509 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2510 } else if (previousParents
> currentParents
) {
2511 previousParents
= currentParents
;
2512 previousSiblings
.truncate(currentParents
);
2515 if (i
>= firstIndex
) {
2516 // The index represents a visible item. Apply the parent-siblings
2517 // and update the sibling of the current item.
2518 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2523 QBitArray siblings
= previousSiblings
;
2524 siblings
.resize(siblings
.count() + 1);
2525 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2527 widget
->setSiblingsInformation(siblings
);
2532 bool KItemListView::hasSiblingSuccessor(int index
) const
2534 bool hasSuccessor
= false;
2535 const int parentsCount
= m_model
->expandedParentsCount(index
);
2536 int successorIndex
= index
+ 1;
2538 // Search the next sibling
2539 const int itemCount
= m_model
->count();
2540 while (successorIndex
< itemCount
) {
2541 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2542 if (currentParentsCount
== parentsCount
) {
2543 hasSuccessor
= true;
2545 } else if (currentParentsCount
< parentsCount
) {
2551 if (m_grouped
&& hasSuccessor
) {
2552 // If the sibling is part of another group, don't mark it as
2553 // successor as the group header is between the sibling connections.
2554 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2555 if (m_layouter
->isFirstGroupItem(i
)) {
2556 hasSuccessor
= false;
2562 return hasSuccessor
;
2565 void KItemListView::disconnectRoleEditingSignals(int index
)
2567 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2572 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2573 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2576 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2580 const int minSpeed
= 4;
2581 const int maxSpeed
= 128;
2582 const int speedLimiter
= 96;
2583 const int autoScrollBorder
= 64;
2585 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2586 // This assures that the autoscrolling speed grows gradually.
2587 const int incLimiter
= 1;
2589 if (pos
< autoScrollBorder
) {
2590 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2591 inc
= qMax(inc
, -maxSpeed
);
2592 inc
= qMax(inc
, oldInc
- incLimiter
);
2593 } else if (pos
> range
- autoScrollBorder
) {
2594 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2595 inc
= qMin(inc
, maxSpeed
);
2596 inc
= qMin(inc
, oldInc
+ incLimiter
);
2602 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2604 const qreal availableSize
= size
- itemMargin
;
2605 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2611 KItemListCreatorBase::~KItemListCreatorBase()
2613 qDeleteAll(m_recycleableWidgets
);
2614 qDeleteAll(m_createdWidgets
);
2617 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2619 m_createdWidgets
.insert(widget
);
2622 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2624 Q_ASSERT(m_createdWidgets
.contains(widget
));
2625 m_createdWidgets
.remove(widget
);
2627 if (m_recycleableWidgets
.count() < 100) {
2628 m_recycleableWidgets
.append(widget
);
2629 widget
->setVisible(false);
2635 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2637 if (m_recycleableWidgets
.isEmpty()) {
2641 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2642 m_createdWidgets
.insert(widget
);
2646 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2650 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2652 widget
->setParentItem(0);
2653 widget
->setOpacity(1.0);
2654 pushRecycleableWidget(widget
);
2657 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2661 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2663 header
->setOpacity(1.0);
2664 pushRecycleableWidget(header
);
2667 #include "kitemlistview.moc"