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>
50 #include "kitemlistviewaccessible.h"
52 #define QT_NO_ACCESSIBILITY 1
53 #pragma message("TODO: port accessibility to Qt5")
57 // Time in ms until reaching the autoscroll margin triggers
58 // an initial autoscrolling
59 const int InitialAutoScrollDelay
= 700;
61 // Delay in ms for triggering the next autoscroll
62 const int RepeatingAutoScrollDelay
= 1000 / 60;
65 #ifndef QT_NO_ACCESSIBILITY
66 QAccessibleInterface
* accessibleInterfaceFactory(const QString
&key
, QObject
*object
)
70 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
71 return new KItemListContainerAccessible(container
);
72 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
73 return new KItemListViewAccessible(view
);
80 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
81 QGraphicsWidget(parent
),
82 m_enabledSelectionToggles(false),
84 m_supportsItemExpanding(false),
86 m_activeTransactions(0),
87 m_endTransactionAnimationHint(Animation
),
93 m_groupHeaderCreator(0),
98 m_sizeHintResolver(0),
102 m_oldScrollOffset(0),
103 m_oldMaximumScrollOffset(0),
105 m_oldMaximumItemOffset(0),
106 m_skipAutoScrollForRubberBand(false),
109 m_autoScrollIncrement(0),
110 m_autoScrollTimer(0),
115 setAcceptHoverEvents(true);
117 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
119 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
121 m_animation
= new KItemListViewAnimation(this);
122 connect(m_animation
, &KItemListViewAnimation::finished
,
123 this, &KItemListView::slotAnimationFinished
);
125 m_layoutTimer
= new QTimer(this);
126 m_layoutTimer
->setInterval(300);
127 m_layoutTimer
->setSingleShot(true);
128 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
130 m_rubberBand
= new KItemListRubberBand(this);
131 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
133 m_headerWidget
= new KItemListHeaderWidget(this);
134 m_headerWidget
->setVisible(false);
136 m_header
= new KItemListHeader(this);
138 #ifndef QT_NO_ACCESSIBILITY
139 QAccessible::installFactory(accessibleInterfaceFactory
);
144 KItemListView::~KItemListView()
146 // The group headers are children of the widgets created by
147 // widgetCreator(). So it is mandatory to delete the group headers
149 delete m_groupHeaderCreator
;
150 m_groupHeaderCreator
= 0;
152 delete m_widgetCreator
;
155 delete m_sizeHintResolver
;
156 m_sizeHintResolver
= 0;
159 void KItemListView::setScrollOffset(qreal offset
)
165 const qreal previousOffset
= m_layouter
->scrollOffset();
166 if (offset
== previousOffset
) {
170 m_layouter
->setScrollOffset(offset
);
171 m_animation
->setScrollOffset(offset
);
173 // Don't check whether the m_layoutTimer is active: Changing the
174 // scroll offset must always trigger a synchronous layout, otherwise
175 // the smooth-scrolling might get jerky.
176 doLayout(NoAnimation
);
177 onScrollOffsetChanged(offset
, previousOffset
);
180 qreal
KItemListView::scrollOffset() const
182 return m_layouter
->scrollOffset();
185 qreal
KItemListView::maximumScrollOffset() const
187 return m_layouter
->maximumScrollOffset();
190 void KItemListView::setItemOffset(qreal offset
)
192 if (m_layouter
->itemOffset() == offset
) {
196 m_layouter
->setItemOffset(offset
);
197 if (m_headerWidget
->isVisible()) {
198 m_headerWidget
->setOffset(offset
);
201 // Don't check whether the m_layoutTimer is active: Changing the
202 // item offset must always trigger a synchronous layout, otherwise
203 // the smooth-scrolling might get jerky.
204 doLayout(NoAnimation
);
207 qreal
KItemListView::itemOffset() const
209 return m_layouter
->itemOffset();
212 qreal
KItemListView::maximumItemOffset() const
214 return m_layouter
->maximumItemOffset();
217 int KItemListView::maximumVisibleItems() const
219 return m_layouter
->maximumVisibleItems();
222 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
224 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
225 m_visibleRoles
= roles
;
226 onVisibleRolesChanged(roles
, previousRoles
);
228 m_sizeHintResolver
->clearCache();
229 m_layouter
->markAsDirty();
231 if (m_itemSize
.isEmpty()) {
232 m_headerWidget
->setColumns(roles
);
233 updatePreferredColumnWidths();
234 if (!m_headerWidget
->automaticColumnResizing()) {
235 // The column-width of new roles are still 0. Apply the preferred
236 // column-width as default with.
237 foreach (const QByteArray
& role
, m_visibleRoles
) {
238 if (m_headerWidget
->columnWidth(role
) == 0) {
239 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
240 m_headerWidget
->setColumnWidth(role
, width
);
244 applyColumnWidthsFromHeader();
248 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
249 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
250 (roles
.count() <= 1 && previousRoles
.count() > 1));
252 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
253 while (it
.hasNext()) {
255 KItemListWidget
* widget
= it
.value();
256 widget
->setVisibleRoles(roles
);
257 if (alternateBackgroundsChanged
) {
258 updateAlternateBackgroundForWidget(widget
);
262 doLayout(NoAnimation
);
265 QList
<QByteArray
> KItemListView::visibleRoles() const
267 return m_visibleRoles
;
270 void KItemListView::setAutoScroll(bool enabled
)
272 if (enabled
&& !m_autoScrollTimer
) {
273 m_autoScrollTimer
= new QTimer(this);
274 m_autoScrollTimer
->setSingleShot(true);
275 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
276 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
277 } else if (!enabled
&& m_autoScrollTimer
) {
278 delete m_autoScrollTimer
;
279 m_autoScrollTimer
= 0;
283 bool KItemListView::autoScroll() const
285 return m_autoScrollTimer
!= 0;
288 void KItemListView::setEnabledSelectionToggles(bool enabled
)
290 if (m_enabledSelectionToggles
!= enabled
) {
291 m_enabledSelectionToggles
= enabled
;
293 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
294 while (it
.hasNext()) {
296 it
.value()->setEnabledSelectionToggle(enabled
);
301 bool KItemListView::enabledSelectionToggles() const
303 return m_enabledSelectionToggles
;
306 KItemListController
* KItemListView::controller() const
311 KItemModelBase
* KItemListView::model() const
316 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
318 if (m_widgetCreator
) {
319 delete m_widgetCreator
;
321 m_widgetCreator
= widgetCreator
;
324 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
326 if (!m_widgetCreator
) {
327 m_widgetCreator
= defaultWidgetCreator();
329 return m_widgetCreator
;
332 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
334 if (m_groupHeaderCreator
) {
335 delete m_groupHeaderCreator
;
337 m_groupHeaderCreator
= groupHeaderCreator
;
340 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
342 if (!m_groupHeaderCreator
) {
343 m_groupHeaderCreator
= defaultGroupHeaderCreator();
345 return m_groupHeaderCreator
;
348 QSizeF
KItemListView::itemSize() const
353 const KItemListStyleOption
& KItemListView::styleOption() const
355 return m_styleOption
;
358 void KItemListView::setGeometry(const QRectF
& rect
)
360 QGraphicsWidget::setGeometry(rect
);
366 const QSizeF newSize
= rect
.size();
367 if (m_itemSize
.isEmpty()) {
368 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
369 if (m_headerWidget
->automaticColumnResizing()) {
370 applyAutomaticColumnWidths();
372 const qreal requiredWidth
= columnWidthsSum();
373 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
374 m_itemSize
.height());
375 m_layouter
->setItemSize(dynamicItemSize
);
378 // Triggering a synchronous layout is fine from a performance point of view,
379 // as with dynamic item sizes no moving animation must be done.
380 m_layouter
->setSize(newSize
);
381 doLayout(NoAnimation
);
383 const bool animate
= !changesItemGridLayout(newSize
,
384 m_layouter
->itemSize(),
385 m_layouter
->itemMargin());
386 m_layouter
->setSize(newSize
);
389 // Trigger an asynchronous relayout with m_layoutTimer to prevent
390 // performance bottlenecks. If the timer is exceeded, an animated layout
391 // will be triggered.
392 if (!m_layoutTimer
->isActive()) {
393 m_layoutTimer
->start();
396 m_layoutTimer
->stop();
397 doLayout(NoAnimation
);
402 qreal
KItemListView::verticalPageStep() const
404 qreal headerHeight
= 0;
405 if (m_headerWidget
->isVisible()) {
406 headerHeight
= m_headerWidget
->size().height();
408 return size().height() - headerHeight
;
411 int KItemListView::itemAt(const QPointF
& pos
) const
413 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
414 while (it
.hasNext()) {
417 const KItemListWidget
* widget
= it
.value();
418 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
419 if (widget
->contains(mappedPos
)) {
427 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
429 if (!m_enabledSelectionToggles
) {
433 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
435 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
436 if (!selectionToggleRect
.isEmpty()) {
437 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
438 return selectionToggleRect
.contains(mappedPos
);
444 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
446 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
448 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
449 if (!expansionToggleRect
.isEmpty()) {
450 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
451 return expansionToggleRect
.contains(mappedPos
);
457 int KItemListView::firstVisibleIndex() const
459 return m_layouter
->firstVisibleIndex();
462 int KItemListView::lastVisibleIndex() const
464 return m_layouter
->lastVisibleIndex();
467 void KItemListView::calculateItemSizeHints(QVector
<QSizeF
>& sizeHints
) const
469 widgetCreator()->calculateItemSizeHints(sizeHints
, this);
472 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
474 if (m_supportsItemExpanding
!= supportsExpanding
) {
475 m_supportsItemExpanding
= supportsExpanding
;
476 updateSiblingsInformation();
477 onSupportsItemExpandingChanged(supportsExpanding
);
481 bool KItemListView::supportsItemExpanding() const
483 return m_supportsItemExpanding
;
486 QRectF
KItemListView::itemRect(int index
) const
488 return m_layouter
->itemRect(index
);
491 QRectF
KItemListView::itemContextRect(int index
) const
495 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
497 contextRect
= widget
->iconRect() | widget
->textRect();
498 contextRect
.translate(itemRect(index
).topLeft());
504 void KItemListView::scrollToItem(int index
)
506 QRectF viewGeometry
= geometry();
507 if (m_headerWidget
->isVisible()) {
508 const qreal headerHeight
= m_headerWidget
->size().height();
509 viewGeometry
.adjust(0, headerHeight
, 0, 0);
511 QRectF currentRect
= itemRect(index
);
513 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
514 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
515 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
517 if (!viewGeometry
.contains(currentRect
)) {
518 qreal newOffset
= scrollOffset();
519 if (scrollOrientation() == Qt::Vertical
) {
520 if (currentRect
.top() < viewGeometry
.top()) {
521 newOffset
+= currentRect
.top() - viewGeometry
.top();
522 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
523 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
526 if (currentRect
.left() < viewGeometry
.left()) {
527 newOffset
+= currentRect
.left() - viewGeometry
.left();
528 } else if (currentRect
.right() > viewGeometry
.right()) {
529 newOffset
+= currentRect
.right() - viewGeometry
.right();
533 if (newOffset
!= scrollOffset()) {
534 emit
scrollTo(newOffset
);
539 void KItemListView::beginTransaction()
541 ++m_activeTransactions
;
542 if (m_activeTransactions
== 1) {
543 onTransactionBegin();
547 void KItemListView::endTransaction()
549 --m_activeTransactions
;
550 if (m_activeTransactions
< 0) {
551 m_activeTransactions
= 0;
552 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
555 if (m_activeTransactions
== 0) {
557 doLayout(m_endTransactionAnimationHint
);
558 m_endTransactionAnimationHint
= Animation
;
562 bool KItemListView::isTransactionActive() const
564 return m_activeTransactions
> 0;
567 void KItemListView::setHeaderVisible(bool visible
)
569 if (visible
&& !m_headerWidget
->isVisible()) {
570 QStyleOptionHeader option
;
571 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
574 m_headerWidget
->setPos(0, 0);
575 m_headerWidget
->resize(size().width(), headerSize
.height());
576 m_headerWidget
->setModel(m_model
);
577 m_headerWidget
->setColumns(m_visibleRoles
);
578 m_headerWidget
->setZValue(1);
580 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
581 this, &KItemListView::slotHeaderColumnWidthChanged
);
582 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
583 this, &KItemListView::slotHeaderColumnMoved
);
584 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
585 this, &KItemListView::sortOrderChanged
);
586 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
587 this, &KItemListView::sortRoleChanged
);
589 m_layouter
->setHeaderHeight(headerSize
.height());
590 m_headerWidget
->setVisible(true);
591 } else if (!visible
&& m_headerWidget
->isVisible()) {
592 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
593 this, &KItemListView::slotHeaderColumnWidthChanged
);
594 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
595 this, &KItemListView::slotHeaderColumnMoved
);
596 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
597 this, &KItemListView::sortOrderChanged
);
598 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
599 this, &KItemListView::sortRoleChanged
);
601 m_layouter
->setHeaderHeight(0);
602 m_headerWidget
->setVisible(false);
606 bool KItemListView::isHeaderVisible() const
608 return m_headerWidget
->isVisible();
611 KItemListHeader
* KItemListView::header() const
616 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
620 if (indexes
.count() == 1) {
621 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
622 QGraphicsView
* graphicsView
= scene()->views()[0];
623 if (item
&& graphicsView
) {
624 pixmap
= item
->createDragPixmap(0, graphicsView
);
627 // TODO: Not implemented yet. Probably extend the interface
628 // from KItemListWidget::createDragPixmap() to return a pixmap
629 // that can be used for multiple indexes.
635 void KItemListView::editRole(int index
, const QByteArray
& role
)
637 KItemListWidget
* widget
= m_visibleItems
.value(index
);
638 if (!widget
|| m_editingRole
) {
642 m_editingRole
= true;
643 widget
->setEditedRole(role
);
645 connect(widget
, &KItemListWidget::roleEditingCanceled
,
646 this, &KItemListView::slotRoleEditingCanceled
);
647 connect(widget
, &KItemListWidget::roleEditingFinished
,
648 this, &KItemListView::slotRoleEditingFinished
);
651 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
653 QGraphicsWidget::paint(painter
, option
, widget
);
655 if (m_rubberBand
->isActive()) {
656 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
657 m_rubberBand
->endPosition()).normalized();
659 const QPointF topLeft
= rubberBandRect
.topLeft();
660 if (scrollOrientation() == Qt::Vertical
) {
661 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
663 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
666 QStyleOptionRubberBand opt
;
667 opt
.initFrom(widget
);
668 opt
.shape
= QRubberBand::Rectangle
;
670 opt
.rect
= rubberBandRect
.toRect();
671 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
674 if (!m_dropIndicator
.isEmpty()) {
675 const QRectF r
= m_dropIndicator
.toRect();
677 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
678 painter
->setPen(color
);
680 // TODO: The following implementation works only for a vertical scroll-orientation
681 // and assumes a height of the m_draggingInsertIndicator of 1.
682 Q_ASSERT(r
.height() == 1);
683 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
686 painter
->setPen(color
);
687 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
691 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
693 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
694 if (!scene()->views().isEmpty()) {
695 m_styleOption
.palette
= scene()->views().at(0)->palette();
698 return QGraphicsItem::itemChange(change
, value
);
701 void KItemListView::setItemSize(const QSizeF
& size
)
703 const QSizeF previousSize
= m_itemSize
;
704 if (size
== previousSize
) {
708 // Skip animations when the number of rows or columns
709 // are changed in the grid layout. Although the animation
710 // engine can handle this usecase, it looks obtrusive.
711 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
713 m_layouter
->itemMargin());
715 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
716 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
717 (!m_itemSize
.isEmpty() && size
.isEmpty()));
721 if (alternateBackgroundsChanged
) {
722 // For an empty item size alternate backgrounds are drawn if more than
723 // one role is shown. Assure that the backgrounds for visible items are
724 // updated when changing the size in this context.
725 updateAlternateBackgrounds();
728 if (size
.isEmpty()) {
729 if (m_headerWidget
->automaticColumnResizing()) {
730 updatePreferredColumnWidths();
732 // Only apply the changed height and respect the header widths
734 const qreal currentWidth
= m_layouter
->itemSize().width();
735 const QSizeF
newSize(currentWidth
, size
.height());
736 m_layouter
->setItemSize(newSize
);
739 m_layouter
->setItemSize(size
);
742 m_sizeHintResolver
->clearCache();
743 doLayout(animate
? Animation
: NoAnimation
);
744 onItemSizeChanged(size
, previousSize
);
747 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
749 const KItemListStyleOption previousOption
= m_styleOption
;
750 m_styleOption
= option
;
753 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
754 if (margin
!= m_layouter
->itemMargin()) {
755 // Skip animations when the number of rows or columns
756 // are changed in the grid layout. Although the animation
757 // engine can handle this usecase, it looks obtrusive.
758 animate
= !changesItemGridLayout(m_layouter
->size(),
759 m_layouter
->itemSize(),
761 m_layouter
->setItemMargin(margin
);
765 updateGroupHeaderHeight();
769 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
770 // Animating a change of the maximum text size just results in expensive
771 // temporary eliding and clipping operations and does not look good visually.
775 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
776 while (it
.hasNext()) {
778 it
.value()->setStyleOption(option
);
781 m_sizeHintResolver
->clearCache();
782 m_layouter
->markAsDirty();
783 doLayout(animate
? Animation
: NoAnimation
);
785 if (m_itemSize
.isEmpty()) {
786 updatePreferredColumnWidths();
789 onStyleOptionChanged(option
, previousOption
);
792 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
794 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
795 if (orientation
== previousOrientation
) {
799 m_layouter
->setScrollOrientation(orientation
);
800 m_animation
->setScrollOrientation(orientation
);
801 m_sizeHintResolver
->clearCache();
804 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
805 while (it
.hasNext()) {
807 it
.value()->setScrollOrientation(orientation
);
809 updateGroupHeaderHeight();
813 doLayout(NoAnimation
);
815 onScrollOrientationChanged(orientation
, previousOrientation
);
816 emit
scrollOrientationChanged(orientation
, previousOrientation
);
819 Qt::Orientation
KItemListView::scrollOrientation() const
821 return m_layouter
->scrollOrientation();
824 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
829 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
834 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
839 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
841 Q_UNUSED(changedRoles
);
845 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
851 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
857 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
863 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
869 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
875 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
881 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
887 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
889 Q_UNUSED(supportsExpanding
);
892 void KItemListView::onTransactionBegin()
896 void KItemListView::onTransactionEnd()
900 bool KItemListView::event(QEvent
* event
)
902 switch (event
->type()) {
903 case QEvent::PaletteChange
:
907 case QEvent::FontChange
:
912 // Forward all other events to the controller and handle them there
913 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
919 return QGraphicsWidget::event(event
);
922 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
924 m_mousePos
= transform().map(event
->pos());
928 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
930 QGraphicsWidget::mouseMoveEvent(event
);
932 m_mousePos
= transform().map(event
->pos());
933 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
934 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
938 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
940 event
->setAccepted(true);
944 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
946 QGraphicsWidget::dragMoveEvent(event
);
948 m_mousePos
= transform().map(event
->pos());
949 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
950 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
954 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
956 QGraphicsWidget::dragLeaveEvent(event
);
957 setAutoScroll(false);
960 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
962 QGraphicsWidget::dropEvent(event
);
963 setAutoScroll(false);
966 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
968 return m_visibleItems
.values();
971 void KItemListView::updateFont()
973 if (scene() && !scene()->views().isEmpty()) {
974 KItemListStyleOption option
= styleOption();
975 option
.font
= scene()->views().first()->font();
976 option
.fontMetrics
= QFontMetrics(option
.font
);
978 setStyleOption(option
);
982 void KItemListView::updatePalette()
984 if (scene() && !scene()->views().isEmpty()) {
985 KItemListStyleOption option
= styleOption();
986 option
.palette
= scene()->views().first()->palette();
988 setStyleOption(option
);
992 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
994 if (m_itemSize
.isEmpty()) {
995 updatePreferredColumnWidths(itemRanges
);
998 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
999 if (hasMultipleRanges
) {
1003 m_layouter
->markAsDirty();
1005 m_sizeHintResolver
->itemsInserted(itemRanges
);
1007 int previouslyInsertedCount
= 0;
1008 foreach (const KItemRange
& range
, itemRanges
) {
1009 // range.index is related to the model before anything has been inserted.
1010 // As in each loop the current item-range gets inserted the index must
1011 // be increased by the already previously inserted items.
1012 const int index
= range
.index
+ previouslyInsertedCount
;
1013 const int count
= range
.count
;
1014 if (index
< 0 || count
<= 0) {
1015 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1018 previouslyInsertedCount
+= count
;
1020 // Determine which visible items must be moved
1021 QList
<int> itemsToMove
;
1022 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1023 while (it
.hasNext()) {
1025 const int visibleItemIndex
= it
.key();
1026 if (visibleItemIndex
>= index
) {
1027 itemsToMove
.append(visibleItemIndex
);
1031 // Update the indexes of all KItemListWidget instances that are located
1032 // after the inserted items. It is important to adjust the indexes in the order
1033 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1035 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1036 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1038 const int newIndex
= widget
->index() + count
;
1039 if (hasMultipleRanges
) {
1040 setWidgetIndex(widget
, newIndex
);
1042 // Try to animate the moving of the item
1043 moveWidgetToIndex(widget
, newIndex
);
1047 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1048 // Check whether a scrollbar is required to show the inserted items. In this case
1049 // the size of the layouter will be decreased before calling doLayout(): This prevents
1050 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1051 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1052 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1053 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1054 if (decreaseLayouterSize
) {
1055 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1057 int scrollbarSpacing
= 0;
1058 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1059 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1062 QSizeF layouterSize
= m_layouter
->size();
1063 if (verticalScrollOrientation
) {
1064 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1066 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1068 m_layouter
->setSize(layouterSize
);
1072 if (!hasMultipleRanges
) {
1073 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1074 updateSiblingsInformation();
1079 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1082 if (hasMultipleRanges
) {
1083 m_endTransactionAnimationHint
= NoAnimation
;
1086 updateSiblingsInformation();
1089 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1090 // In case if items of the same group have been inserted before an item that
1091 // currently represents the first item of the group, the group header of
1092 // this item must be removed.
1093 updateVisibleGroupHeaders();
1096 if (useAlternateBackgrounds()) {
1097 updateAlternateBackgrounds();
1101 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1103 if (m_itemSize
.isEmpty()) {
1104 // Don't pass the item-range: The preferred column-widths of
1105 // all items must be adjusted when removing items.
1106 updatePreferredColumnWidths();
1109 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1110 if (hasMultipleRanges
) {
1114 m_layouter
->markAsDirty();
1116 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1118 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1119 const KItemRange
& range
= itemRanges
[i
];
1120 const int index
= range
.index
;
1121 const int count
= range
.count
;
1122 if (index
< 0 || count
<= 0) {
1123 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1127 const int firstRemovedIndex
= index
;
1128 const int lastRemovedIndex
= index
+ count
- 1;
1130 // Remeber which items have to be moved because they are behind the removed range.
1131 QVector
<int> itemsToMove
;
1133 // Remove all KItemListWidget instances that got deleted
1134 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1135 const int i
= widget
->index();
1136 if (i
< firstRemovedIndex
) {
1138 } else if (i
> lastRemovedIndex
) {
1139 itemsToMove
.append(i
);
1143 m_animation
->stop(widget
);
1144 // Stopping the animation might lead to recycling the widget if
1145 // it is invisible (see slotAnimationFinished()).
1146 // Check again whether it is still visible:
1147 if (!m_visibleItems
.contains(i
)) {
1151 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1152 // Remove the widget without animation
1153 recycleWidget(widget
);
1155 // Animate the removing of the items. Special case: When removing an item there
1156 // is no valid model index available anymore. For the
1157 // remove-animation the item gets removed from m_visibleItems but the widget
1158 // will stay alive until the animation has been finished and will
1159 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1160 m_visibleItems
.remove(i
);
1161 widget
->setIndex(-1);
1162 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1166 // Update the indexes of all KItemListWidget instances that are located
1167 // after the deleted items. It is important to update them in ascending
1168 // order to prevent overlaps when setting the new index.
1169 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1170 foreach (int i
, itemsToMove
) {
1171 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1173 const int newIndex
= i
- count
;
1174 if (hasMultipleRanges
) {
1175 setWidgetIndex(widget
, newIndex
);
1177 // Try to animate the moving of the item
1178 moveWidgetToIndex(widget
, newIndex
);
1182 if (!hasMultipleRanges
) {
1183 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1184 // assumes an updated geometry. If items are removed during an active transaction,
1185 // the transaction will be temporary deactivated so that doLayout() triggers a
1186 // geometry update if necessary.
1187 const int activeTransactions
= m_activeTransactions
;
1188 m_activeTransactions
= 0;
1189 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1190 m_activeTransactions
= activeTransactions
;
1191 updateSiblingsInformation();
1196 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1199 if (hasMultipleRanges
) {
1200 m_endTransactionAnimationHint
= NoAnimation
;
1202 updateSiblingsInformation();
1205 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1206 // In case if the first item of a group has been removed, the group header
1207 // must be applied to the next visible item.
1208 updateVisibleGroupHeaders();
1211 if (useAlternateBackgrounds()) {
1212 updateAlternateBackgrounds();
1216 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1218 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1219 m_layouter
->markAsDirty();
1222 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1225 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1226 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1228 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1229 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1231 updateWidgetProperties(widget
, index
);
1232 initializeItemListWidget(widget
);
1236 doLayout(NoAnimation
);
1237 updateSiblingsInformation();
1240 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1241 const QSet
<QByteArray
>& roles
)
1243 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1244 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1245 updatePreferredColumnWidths(itemRanges
);
1248 foreach (const KItemRange
& itemRange
, itemRanges
) {
1249 const int index
= itemRange
.index
;
1250 const int count
= itemRange
.count
;
1252 if (updateSizeHints
) {
1253 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1254 m_layouter
->markAsDirty();
1256 if (!m_layoutTimer
->isActive()) {
1257 m_layoutTimer
->start();
1261 // Apply the changed roles to the visible item-widgets
1262 const int lastIndex
= index
+ count
- 1;
1263 for (int i
= index
; i
<= lastIndex
; ++i
) {
1264 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1266 widget
->setData(m_model
->data(i
), roles
);
1270 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1271 // The sort-role has been changed which might result
1272 // in modified group headers
1273 updateVisibleGroupHeaders();
1274 doLayout(NoAnimation
);
1277 #pragma message("TODO: port accessibility otherwise the following line asserts")
1278 //QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged);
1281 void KItemListView::slotGroupsChanged()
1283 updateVisibleGroupHeaders();
1284 doLayout(NoAnimation
);
1285 updateSiblingsInformation();
1288 void KItemListView::slotGroupedSortingChanged(bool current
)
1290 m_grouped
= current
;
1291 m_layouter
->markAsDirty();
1294 updateGroupHeaderHeight();
1296 // Clear all visible headers. Note that the QHashIterator takes a copy of
1297 // m_visibleGroups. Therefore, it remains valid even if items are removed
1298 // from m_visibleGroups in recycleGroupHeaderForWidget().
1299 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1300 while (it
.hasNext()) {
1302 recycleGroupHeaderForWidget(it
.key());
1304 Q_ASSERT(m_visibleGroups
.isEmpty());
1307 if (useAlternateBackgrounds()) {
1308 // Changing the group mode requires to update the alternate backgrounds
1309 // as with the enabled group mode the altering is done on base of the first
1311 updateAlternateBackgrounds();
1313 updateSiblingsInformation();
1314 doLayout(NoAnimation
);
1317 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1322 updateVisibleGroupHeaders();
1323 doLayout(NoAnimation
);
1327 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1332 updateVisibleGroupHeaders();
1333 doLayout(NoAnimation
);
1337 void KItemListView::slotCurrentChanged(int current
, int previous
)
1341 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1342 if (previousWidget
) {
1343 previousWidget
->setCurrent(false);
1346 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1347 if (currentWidget
) {
1348 currentWidget
->setCurrent(true);
1350 #pragma message("TODO: port accessibility otherwise the following line asserts")
1351 //QAccessible::updateAccessibility(this, current+1, QAccessible::Focus);
1354 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1358 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1359 while (it
.hasNext()) {
1361 const int index
= it
.key();
1362 KItemListWidget
* widget
= it
.value();
1363 widget
->setSelected(current
.contains(index
));
1367 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1368 KItemListViewAnimation::AnimationType type
)
1370 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1371 Q_ASSERT(itemListWidget
);
1374 case KItemListViewAnimation::DeleteAnimation
: {
1375 // As we recycle the widget in this case it is important to assure that no
1376 // other animation has been started. This is a convention in KItemListView and
1377 // not a requirement defined by KItemListViewAnimation.
1378 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1380 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1381 // by m_visibleWidgets and must be deleted manually after the animation has
1383 recycleGroupHeaderForWidget(itemListWidget
);
1384 widgetCreator()->recycle(itemListWidget
);
1388 case KItemListViewAnimation::CreateAnimation
:
1389 case KItemListViewAnimation::MovingAnimation
:
1390 case KItemListViewAnimation::ResizeAnimation
: {
1391 const int index
= itemListWidget
->index();
1392 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1393 (index
> m_layouter
->lastVisibleIndex());
1394 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1395 recycleWidget(itemListWidget
);
1404 void KItemListView::slotLayoutTimerFinished()
1406 m_layouter
->setSize(geometry().size());
1407 doLayout(Animation
);
1410 void KItemListView::slotRubberBandPosChanged()
1415 void KItemListView::slotRubberBandActivationChanged(bool active
)
1418 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1419 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1420 m_skipAutoScrollForRubberBand
= true;
1422 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1423 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1424 m_skipAutoScrollForRubberBand
= false;
1430 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1432 qreal previousWidth
)
1435 Q_UNUSED(currentWidth
);
1436 Q_UNUSED(previousWidth
);
1438 m_headerWidget
->setAutomaticColumnResizing(false);
1439 applyColumnWidthsFromHeader();
1440 doLayout(NoAnimation
);
1443 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1447 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1449 const QList
<QByteArray
> previous
= m_visibleRoles
;
1451 QList
<QByteArray
> current
= m_visibleRoles
;
1452 current
.removeAt(previousIndex
);
1453 current
.insert(currentIndex
, role
);
1455 setVisibleRoles(current
);
1457 emit
visibleRolesChanged(current
, previous
);
1460 void KItemListView::triggerAutoScrolling()
1462 if (!m_autoScrollTimer
) {
1467 int visibleSize
= 0;
1468 if (scrollOrientation() == Qt::Vertical
) {
1469 pos
= m_mousePos
.y();
1470 visibleSize
= size().height();
1472 pos
= m_mousePos
.x();
1473 visibleSize
= size().width();
1476 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1477 m_autoScrollIncrement
= 0;
1480 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1481 if (m_autoScrollIncrement
== 0) {
1482 // The mouse position is not above an autoscroll margin (the autoscroll timer
1483 // will be restarted in mouseMoveEvent())
1484 m_autoScrollTimer
->stop();
1488 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1489 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1490 // if the direction of the rubberband is similar to the autoscroll direction. This
1491 // prevents that starting to create a rubberband within the autoscroll margins starts
1492 // an autoscrolling.
1494 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1495 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1496 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1497 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1498 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1499 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1500 // been moved up although the autoscroll direction might be down)
1501 m_autoScrollTimer
->stop();
1506 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1507 // the autoscrolling may not get skipped anymore until a new rubberband is created
1508 m_skipAutoScrollForRubberBand
= false;
1510 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1511 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1512 setScrollOffset(newScrollOffset
);
1514 // Trigger the autoscroll timer which will periodically call
1515 // triggerAutoScrolling()
1516 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1519 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1521 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1523 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1524 Q_ASSERT(groupHeader
);
1525 updateGroupHeaderLayout(widget
);
1528 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1530 disconnectRoleEditingSignals(index
);
1532 emit
roleEditingCanceled(index
, role
, value
);
1533 m_editingRole
= false;
1536 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1538 disconnectRoleEditingSignals(index
);
1540 emit
roleEditingFinished(index
, role
, value
);
1541 m_editingRole
= false;
1544 void KItemListView::setController(KItemListController
* controller
)
1546 if (m_controller
!= controller
) {
1547 KItemListController
* previous
= m_controller
;
1549 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1550 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1551 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1554 m_controller
= controller
;
1557 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1558 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1559 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1562 onControllerChanged(controller
, previous
);
1566 void KItemListView::setModel(KItemModelBase
* model
)
1568 if (m_model
== model
) {
1572 KItemModelBase
* previous
= m_model
;
1575 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1576 this, &KItemListView::slotItemsChanged
);
1577 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1578 this, &KItemListView::slotItemsInserted
);
1579 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1580 this, &KItemListView::slotItemsRemoved
);
1581 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1582 this, &KItemListView::slotItemsMoved
);
1583 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1584 this, &KItemListView::slotGroupsChanged
);
1585 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1586 this, &KItemListView::slotGroupedSortingChanged
);
1587 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1588 this, &KItemListView::slotSortOrderChanged
);
1589 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1590 this, &KItemListView::slotSortRoleChanged
);
1592 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1596 m_layouter
->setModel(model
);
1597 m_grouped
= model
->groupedSorting();
1600 connect(m_model
, &KItemModelBase::itemsChanged
,
1601 this, &KItemListView::slotItemsChanged
);
1602 connect(m_model
, &KItemModelBase::itemsInserted
,
1603 this, &KItemListView::slotItemsInserted
);
1604 connect(m_model
, &KItemModelBase::itemsRemoved
,
1605 this, &KItemListView::slotItemsRemoved
);
1606 connect(m_model
, &KItemModelBase::itemsMoved
,
1607 this, &KItemListView::slotItemsMoved
);
1608 connect(m_model
, &KItemModelBase::groupsChanged
,
1609 this, &KItemListView::slotGroupsChanged
);
1610 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1611 this, &KItemListView::slotGroupedSortingChanged
);
1612 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1613 this, &KItemListView::slotSortOrderChanged
);
1614 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1615 this, &KItemListView::slotSortRoleChanged
);
1617 const int itemCount
= m_model
->count();
1618 if (itemCount
> 0) {
1619 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1623 onModelChanged(model
, previous
);
1626 KItemListRubberBand
* KItemListView::rubberBand() const
1628 return m_rubberBand
;
1631 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1633 if (m_layoutTimer
->isActive()) {
1634 m_layoutTimer
->stop();
1637 if (m_activeTransactions
> 0) {
1638 if (hint
== NoAnimation
) {
1639 // As soon as at least one property change should be done without animation,
1640 // the whole transaction will be marked as not animated.
1641 m_endTransactionAnimationHint
= NoAnimation
;
1646 if (!m_model
|| m_model
->count() < 0) {
1650 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1651 if (firstVisibleIndex
< 0) {
1652 emitOffsetChanges();
1656 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1657 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1658 // is still shown if the maximum offset got decreased.
1659 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1660 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1661 if (scrollOffset() > maxOffsetToShowFullRange
) {
1662 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1663 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1666 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1668 int firstSibblingIndex
= -1;
1669 int lastSibblingIndex
= -1;
1670 const bool supportsExpanding
= supportsItemExpanding();
1672 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1674 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1675 // instances from invisible items are reused. If no reusable items are
1676 // found then new KItemListWidget instances get created.
1677 const bool animate
= (hint
== Animation
);
1678 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1679 bool applyNewPos
= true;
1680 bool wasHidden
= false;
1682 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1683 const QPointF newPos
= itemBounds
.topLeft();
1684 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1687 if (!reusableItems
.isEmpty()) {
1688 // Reuse a KItemListWidget instance from an invisible item
1689 const int oldIndex
= reusableItems
.takeLast();
1690 widget
= m_visibleItems
.value(oldIndex
);
1691 setWidgetIndex(widget
, i
);
1692 updateWidgetProperties(widget
, i
);
1693 initializeItemListWidget(widget
);
1695 // No reusable KItemListWidget instance is available, create a new one
1696 widget
= createWidget(i
);
1698 widget
->resize(itemBounds
.size());
1700 if (animate
&& changedCount
< 0) {
1701 // Items have been deleted.
1702 if (i
>= changedIndex
) {
1703 // The item is located behind the removed range. Move the
1704 // created item to the imaginary old position outside the
1705 // view. It will get animated to the new position later.
1706 const int previousIndex
= i
- changedCount
;
1707 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1708 if (itemRect
.isEmpty()) {
1709 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1710 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1711 widget
->setPos(invisibleOldPos
);
1713 widget
->setPos(itemRect
.topLeft());
1715 applyNewPos
= false;
1719 if (supportsExpanding
&& changedCount
== 0) {
1720 if (firstSibblingIndex
< 0) {
1721 firstSibblingIndex
= i
;
1723 lastSibblingIndex
= i
;
1728 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1729 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1730 applyNewPos
= false;
1733 const bool itemsRemoved
= (changedCount
< 0);
1734 const bool itemsInserted
= (changedCount
> 0);
1735 if (itemsRemoved
&& (i
>= changedIndex
)) {
1736 // The item is located after the removed items. Animate the moving of the position.
1737 applyNewPos
= !moveWidget(widget
, newPos
);
1738 } else if (itemsInserted
&& i
>= changedIndex
) {
1739 // The item is located after the first inserted item
1740 if (i
<= changedIndex
+ changedCount
- 1) {
1741 // The item is an inserted item. Animate the appearing of the item.
1742 // For performance reasons no animation is done when changedCount is equal
1743 // to all available items.
1744 if (changedCount
< m_model
->count()) {
1745 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1747 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1748 // The item was already there before, so animate the moving of the position.
1749 // No moving animation is done if the item is animated by a create animation: This
1750 // prevents a "move animation mess" when inserting several ranges in parallel.
1751 applyNewPos
= !moveWidget(widget
, newPos
);
1753 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1754 // The size of the view might have been changed. Animate the moving of the position.
1755 applyNewPos
= !moveWidget(widget
, newPos
);
1758 m_animation
->stop(widget
);
1762 widget
->setPos(newPos
);
1765 Q_ASSERT(widget
->index() == i
);
1766 widget
->setVisible(true);
1768 if (widget
->size() != itemBounds
.size()) {
1769 // Resize the widget for the item to the changed size.
1771 // If a dynamic item size is used then no animation is done in the direction
1772 // of the dynamic size.
1773 if (m_itemSize
.width() <= 0) {
1774 // The width is dynamic, apply the new width without animation.
1775 widget
->resize(itemBounds
.width(), widget
->size().height());
1776 } else if (m_itemSize
.height() <= 0) {
1777 // The height is dynamic, apply the new height without animation.
1778 widget
->resize(widget
->size().width(), itemBounds
.height());
1780 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1782 widget
->resize(itemBounds
.size());
1786 // Updating the cell-information must be done as last step: The decision whether the
1787 // moving-animation should be started at all is based on the previous cell-information.
1788 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1789 m_visibleCells
.insert(i
, cell
);
1792 // Delete invisible KItemListWidget instances that have not been reused
1793 foreach (int index
, reusableItems
) {
1794 recycleWidget(m_visibleItems
.value(index
));
1797 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1798 Q_ASSERT(lastSibblingIndex
>= 0);
1799 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1803 // Update the layout of all visible group headers
1804 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1805 while (it
.hasNext()) {
1807 updateGroupHeaderLayout(it
.key());
1811 emitOffsetChanges();
1814 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1815 int lastVisibleIndex
,
1816 LayoutAnimationHint hint
)
1818 // Determine all items that are completely invisible and might be
1819 // reused for items that just got (at least partly) visible. If the
1820 // animation hint is set to 'Animation' items that do e.g. an animated
1821 // moving of their position are not marked as invisible: This assures
1822 // that a scrolling inside the view can be done without breaking an animation.
1826 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1827 while (it
.hasNext()) {
1830 KItemListWidget
* widget
= it
.value();
1831 const int index
= widget
->index();
1832 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1835 if (m_animation
->isStarted(widget
)) {
1836 if (hint
== NoAnimation
) {
1837 // Stopping the animation will call KItemListView::slotAnimationFinished()
1838 // and the widget will be recycled if necessary there.
1839 m_animation
->stop(widget
);
1842 widget
->setVisible(false);
1843 items
.append(index
);
1846 recycleGroupHeaderForWidget(widget
);
1855 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1857 if (widget
->pos() == newPos
) {
1861 bool startMovingAnim
= false;
1863 if (m_itemSize
.isEmpty()) {
1864 // The items are not aligned in a grid but either as columns or rows.
1865 startMovingAnim
= true;
1867 // When having a grid the moving-animation should only be started, if it is done within
1868 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1869 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1870 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1871 const int index
= widget
->index();
1872 const Cell cell
= m_visibleCells
.value(index
);
1873 if (cell
.column
>= 0 && cell
.row
>= 0) {
1874 if (scrollOrientation() == Qt::Vertical
) {
1875 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1877 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1882 if (startMovingAnim
) {
1883 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1887 m_animation
->stop(widget
);
1888 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1892 void KItemListView::emitOffsetChanges()
1894 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1895 if (m_oldScrollOffset
!= newScrollOffset
) {
1896 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1897 m_oldScrollOffset
= newScrollOffset
;
1900 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1901 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1902 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1903 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1906 const qreal newItemOffset
= m_layouter
->itemOffset();
1907 if (m_oldItemOffset
!= newItemOffset
) {
1908 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1909 m_oldItemOffset
= newItemOffset
;
1912 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1913 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1914 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1915 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1919 KItemListWidget
* KItemListView::createWidget(int index
)
1921 KItemListWidget
* widget
= widgetCreator()->create(this);
1922 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1924 m_visibleItems
.insert(index
, widget
);
1925 m_visibleCells
.insert(index
, Cell());
1926 updateWidgetProperties(widget
, index
);
1927 initializeItemListWidget(widget
);
1931 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1934 recycleGroupHeaderForWidget(widget
);
1937 const int index
= widget
->index();
1938 m_visibleItems
.remove(index
);
1939 m_visibleCells
.remove(index
);
1941 widgetCreator()->recycle(widget
);
1944 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1946 const int oldIndex
= widget
->index();
1947 m_visibleItems
.remove(oldIndex
);
1948 m_visibleCells
.remove(oldIndex
);
1950 m_visibleItems
.insert(index
, widget
);
1951 m_visibleCells
.insert(index
, Cell());
1953 widget
->setIndex(index
);
1956 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1958 const int oldIndex
= widget
->index();
1959 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1961 setWidgetIndex(widget
, index
);
1963 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1964 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1965 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1966 (!vertical
&& oldCell
.column
== newCell
.column
);
1968 m_visibleCells
.insert(index
, newCell
);
1972 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1975 case LayouterSize
: m_layouter
->setSize(size
); break;
1976 case ItemSize
: m_layouter
->setItemSize(size
); break;
1981 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1983 widget
->setVisibleRoles(m_visibleRoles
);
1984 updateWidgetColumnWidths(widget
);
1985 widget
->setStyleOption(m_styleOption
);
1987 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1988 widget
->setCurrent(index
== selectionManager
->currentItem());
1989 widget
->setSelected(selectionManager
->isSelected(index
));
1990 widget
->setHovered(false);
1991 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1992 widget
->setIndex(index
);
1993 widget
->setData(m_model
->data(index
));
1994 widget
->setSiblingsInformation(QBitArray());
1995 updateAlternateBackgroundForWidget(widget
);
1998 updateGroupHeaderForWidget(widget
);
2002 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2004 Q_ASSERT(m_grouped
);
2006 const int index
= widget
->index();
2007 if (!m_layouter
->isFirstGroupItem(index
)) {
2008 // The widget does not represent the first item of a group
2009 // and hence requires no header
2010 recycleGroupHeaderForWidget(widget
);
2014 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2015 if (groups
.isEmpty() || !groupHeaderCreator()) {
2019 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2021 groupHeader
= groupHeaderCreator()->create(this);
2022 groupHeader
->setParentItem(widget
);
2023 m_visibleGroups
.insert(widget
, groupHeader
);
2024 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2026 Q_ASSERT(groupHeader
->parentItem() == widget
);
2028 const int groupIndex
= groupIndexForItem(index
);
2029 Q_ASSERT(groupIndex
>= 0);
2030 groupHeader
->setData(groups
.at(groupIndex
).second
);
2031 groupHeader
->setRole(model()->sortRole());
2032 groupHeader
->setStyleOption(m_styleOption
);
2033 groupHeader
->setScrollOrientation(scrollOrientation());
2034 groupHeader
->setItemIndex(index
);
2036 groupHeader
->show();
2039 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2041 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2042 Q_ASSERT(groupHeader
);
2044 const int index
= widget
->index();
2045 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2046 const QRectF itemRect
= m_layouter
->itemRect(index
);
2048 // The group-header is a child of the itemlist widget. Translate the
2049 // group header position to the relative position.
2050 if (scrollOrientation() == Qt::Vertical
) {
2051 // In the vertical scroll orientation the group header should always span
2052 // the whole width no matter which temporary position the parent widget
2053 // has. In this case the x-position and width will be adjusted manually.
2054 const qreal x
= -widget
->x() - itemOffset();
2055 const qreal width
= maximumItemOffset();
2056 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2057 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2059 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2060 groupHeader
->resize(groupHeaderRect
.size());
2064 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2066 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2068 header
->setParentItem(0);
2069 groupHeaderCreator()->recycle(header
);
2070 m_visibleGroups
.remove(widget
);
2071 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2075 void KItemListView::updateVisibleGroupHeaders()
2077 Q_ASSERT(m_grouped
);
2078 m_layouter
->markAsDirty();
2080 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2081 while (it
.hasNext()) {
2083 updateGroupHeaderForWidget(it
.value());
2087 int KItemListView::groupIndexForItem(int index
) const
2089 Q_ASSERT(m_grouped
);
2091 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2092 if (groups
.isEmpty()) {
2097 int max
= groups
.count() - 1;
2100 mid
= (min
+ max
) / 2;
2101 if (index
> groups
[mid
].first
) {
2106 } while (groups
[mid
].first
!= index
&& min
<= max
);
2109 while (groups
[mid
].first
> index
&& mid
> 0) {
2117 void KItemListView::updateAlternateBackgrounds()
2119 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2120 while (it
.hasNext()) {
2122 updateAlternateBackgroundForWidget(it
.value());
2126 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2128 bool enabled
= useAlternateBackgrounds();
2130 const int index
= widget
->index();
2131 enabled
= (index
& 0x1) > 0;
2133 const int groupIndex
= groupIndexForItem(index
);
2134 if (groupIndex
>= 0) {
2135 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2136 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2137 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2138 enabled
= (relativeIndex
& 0x1) > 0;
2142 widget
->setAlternateBackground(enabled
);
2145 bool KItemListView::useAlternateBackgrounds() const
2147 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2150 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2152 QElapsedTimer timer
;
2155 QHash
<QByteArray
, qreal
> widths
;
2157 // Calculate the minimum width for each column that is required
2158 // to show the headline unclipped.
2159 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2160 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2161 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2162 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2163 const QString headerText
= m_model
->roleDescription(visibleRole
);
2164 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2165 widths
.insert(visibleRole
, headerWidth
);
2168 // Calculate the preferred column withs for each item and ignore values
2169 // smaller than the width for showing the headline unclipped.
2170 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2171 int calculatedItemCount
= 0;
2172 bool maxTimeExceeded
= false;
2173 foreach (const KItemRange
& itemRange
, itemRanges
) {
2174 const int startIndex
= itemRange
.index
;
2175 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2177 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2178 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2179 qreal maxWidth
= widths
.value(visibleRole
, 0);
2180 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2181 maxWidth
= qMax(width
, maxWidth
);
2182 widths
.insert(visibleRole
, maxWidth
);
2185 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2186 // When having several thousands of items calculating the sizes can get
2187 // very expensive. We accept a possibly too small role-size in favour
2188 // of having no blocking user interface.
2189 maxTimeExceeded
= true;
2192 ++calculatedItemCount
;
2194 if (maxTimeExceeded
) {
2202 void KItemListView::applyColumnWidthsFromHeader()
2204 // Apply the new size to the layouter
2205 const qreal requiredWidth
= columnWidthsSum();
2206 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2207 m_itemSize
.height());
2208 m_layouter
->setItemSize(dynamicItemSize
);
2210 // Update the role sizes for all visible widgets
2211 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2212 while (it
.hasNext()) {
2214 updateWidgetColumnWidths(it
.value());
2218 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2220 foreach (const QByteArray
& role
, m_visibleRoles
) {
2221 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2225 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2227 Q_ASSERT(m_itemSize
.isEmpty());
2228 const int itemCount
= m_model
->count();
2229 int rangesItemCount
= 0;
2230 foreach (const KItemRange
& range
, itemRanges
) {
2231 rangesItemCount
+= range
.count
;
2234 if (itemCount
== rangesItemCount
) {
2235 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2236 foreach (const QByteArray
& role
, m_visibleRoles
) {
2237 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2240 // Only a sub range of the roles need to be determined.
2241 // The chances are good that the widths of the sub ranges
2242 // already fit into the available widths and hence no
2243 // expensive update might be required.
2244 bool changed
= false;
2246 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2247 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2248 while (it
.hasNext()) {
2250 const QByteArray
& role
= it
.key();
2251 const qreal updatedWidth
= it
.value();
2252 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2253 if (updatedWidth
> currentWidth
) {
2254 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2260 // All the updated sizes are smaller than the current sizes and no change
2261 // of the stretched roles-widths is required
2266 if (m_headerWidget
->automaticColumnResizing()) {
2267 applyAutomaticColumnWidths();
2271 void KItemListView::updatePreferredColumnWidths()
2274 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2278 void KItemListView::applyAutomaticColumnWidths()
2280 Q_ASSERT(m_itemSize
.isEmpty());
2281 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2282 if (m_visibleRoles
.isEmpty()) {
2286 // Calculate the maximum size of an item by considering the
2287 // visible role sizes and apply them to the layouter. If the
2288 // size does not use the available view-size the size of the
2289 // first role will get stretched.
2291 foreach (const QByteArray
& role
, m_visibleRoles
) {
2292 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2293 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2296 const QByteArray firstRole
= m_visibleRoles
.first();
2297 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2298 QSizeF dynamicItemSize
= m_itemSize
;
2300 qreal requiredWidth
= columnWidthsSum();
2301 const qreal availableWidth
= size().width();
2302 if (requiredWidth
< availableWidth
) {
2303 // Stretch the first column to use the whole remaining width
2304 firstColumnWidth
+= availableWidth
- requiredWidth
;
2305 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2306 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2307 // Shrink the first column to be able to show as much other
2308 // columns as possible
2309 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2311 // TODO: A proper calculation of the minimum width depends on the implementation
2312 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2314 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2315 if (shrinkedFirstColumnWidth
< minWidth
) {
2316 shrinkedFirstColumnWidth
= minWidth
;
2319 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2320 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2323 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2325 m_layouter
->setItemSize(dynamicItemSize
);
2327 // Update the role sizes for all visible widgets
2328 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2329 while (it
.hasNext()) {
2331 updateWidgetColumnWidths(it
.value());
2335 qreal
KItemListView::columnWidthsSum() const
2337 qreal widthsSum
= 0;
2338 foreach (const QByteArray
& role
, m_visibleRoles
) {
2339 widthsSum
+= m_headerWidget
->columnWidth(role
);
2344 QRectF
KItemListView::headerBoundaries() const
2346 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2349 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2350 const QSizeF
& newItemSize
,
2351 const QSizeF
& newItemMargin
) const
2353 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2357 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2358 const qreal itemWidth
= m_layouter
->itemSize().width();
2359 if (itemWidth
> 0) {
2360 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2361 newItemSize
.width(),
2362 newItemMargin
.width());
2363 if (m_model
->count() > newColumnCount
) {
2364 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2366 m_layouter
->itemMargin().width());
2367 return oldColumnCount
!= newColumnCount
;
2371 const qreal itemHeight
= m_layouter
->itemSize().height();
2372 if (itemHeight
> 0) {
2373 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2374 newItemSize
.height(),
2375 newItemMargin
.height());
2376 if (m_model
->count() > newRowCount
) {
2377 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2379 m_layouter
->itemMargin().height());
2380 return oldRowCount
!= newRowCount
;
2388 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2390 if (m_itemSize
.isEmpty()) {
2391 // We have only columns or only rows, but no grid: An animation is usually
2392 // welcome when inserting or removing items.
2393 return !supportsItemExpanding();
2396 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2400 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2401 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2402 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2403 // Only animate if up to 2/3 of a row or column are inserted or removed
2404 return changedItemCount
<= maximum
* 2 / 3;
2408 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2410 const QSizeF oldSize
= m_layouter
->size();
2412 m_layouter
->setSize(size
);
2413 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2414 m_layouter
->setSize(oldSize
);
2416 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2417 : maxOffset
> size
.width();
2420 int KItemListView::showDropIndicator(const QPointF
& pos
)
2422 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2423 while (it
.hasNext()) {
2425 const KItemListWidget
* widget
= it
.value();
2427 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2428 const QRectF rect
= itemRect(widget
->index());
2429 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2430 if (m_model
->supportsDropping(widget
->index())) {
2431 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2432 const int gap
= qMax(4.0, 0.3 * rect
.height());
2433 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2438 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2439 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2441 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2442 if (m_dropIndicator
!= draggingInsertIndicator
) {
2443 m_dropIndicator
= draggingInsertIndicator
;
2447 int index
= widget
->index();
2455 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2456 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2459 void KItemListView::hideDropIndicator()
2461 if (!m_dropIndicator
.isNull()) {
2462 m_dropIndicator
= QRectF();
2467 void KItemListView::updateGroupHeaderHeight()
2469 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2470 qreal groupHeaderMargin
= 0;
2472 if (scrollOrientation() == Qt::Horizontal
) {
2473 // The vertical margin above and below the header should be
2474 // equal to the horizontal margin, not the vertical margin
2475 // from m_styleOption.
2476 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2477 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2478 } else if (m_itemSize
.isEmpty()){
2479 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2480 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2482 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2483 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2485 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2486 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2488 updateVisibleGroupHeaders();
2491 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2493 if (!supportsItemExpanding() || !m_model
) {
2497 if (firstIndex
< 0 || lastIndex
< 0) {
2498 firstIndex
= m_layouter
->firstVisibleIndex();
2499 lastIndex
= m_layouter
->lastVisibleIndex();
2501 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2502 lastIndex
>= m_layouter
->firstVisibleIndex());
2503 if (!isRangeVisible
) {
2508 int previousParents
= 0;
2509 QBitArray previousSiblings
;
2511 // The rootIndex describes the first index where the siblings get
2512 // calculated from. For the calculation the upper most parent item
2513 // is required. For performance reasons it is checked first whether
2514 // the visible items before or after the current range already
2515 // contain a siblings information which can be used as base.
2516 int rootIndex
= firstIndex
;
2518 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2520 // There is no visible widget before the range, check whether there
2521 // is one after the range:
2522 widget
= m_visibleItems
.value(lastIndex
+ 1);
2524 // The sibling information of the widget may only be used if
2525 // all items of the range have the same number of parents.
2526 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2527 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2528 if (m_model
->expandedParentsCount(i
) != parents
) {
2537 // Performance optimization: Use the sibling information of the visible
2538 // widget beside the given range.
2539 previousSiblings
= widget
->siblingsInformation();
2540 if (previousSiblings
.isEmpty()) {
2543 previousParents
= previousSiblings
.count() - 1;
2544 previousSiblings
.truncate(previousParents
);
2546 // Potentially slow path: Go back to the upper most parent of firstIndex
2547 // to be able to calculate the initial value for the siblings.
2548 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2553 Q_ASSERT(previousParents
>= 0);
2554 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2555 // Update the parent-siblings in case if the current item represents
2556 // a child or an upper parent.
2557 const int currentParents
= m_model
->expandedParentsCount(i
);
2558 Q_ASSERT(currentParents
>= 0);
2559 if (previousParents
< currentParents
) {
2560 previousParents
= currentParents
;
2561 previousSiblings
.resize(currentParents
);
2562 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2563 } else if (previousParents
> currentParents
) {
2564 previousParents
= currentParents
;
2565 previousSiblings
.truncate(currentParents
);
2568 if (i
>= firstIndex
) {
2569 // The index represents a visible item. Apply the parent-siblings
2570 // and update the sibling of the current item.
2571 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2576 QBitArray siblings
= previousSiblings
;
2577 siblings
.resize(siblings
.count() + 1);
2578 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2580 widget
->setSiblingsInformation(siblings
);
2585 bool KItemListView::hasSiblingSuccessor(int index
) const
2587 bool hasSuccessor
= false;
2588 const int parentsCount
= m_model
->expandedParentsCount(index
);
2589 int successorIndex
= index
+ 1;
2591 // Search the next sibling
2592 const int itemCount
= m_model
->count();
2593 while (successorIndex
< itemCount
) {
2594 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2595 if (currentParentsCount
== parentsCount
) {
2596 hasSuccessor
= true;
2598 } else if (currentParentsCount
< parentsCount
) {
2604 if (m_grouped
&& hasSuccessor
) {
2605 // If the sibling is part of another group, don't mark it as
2606 // successor as the group header is between the sibling connections.
2607 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2608 if (m_layouter
->isFirstGroupItem(i
)) {
2609 hasSuccessor
= false;
2615 return hasSuccessor
;
2618 void KItemListView::disconnectRoleEditingSignals(int index
)
2620 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2625 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2626 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2629 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2633 const int minSpeed
= 4;
2634 const int maxSpeed
= 128;
2635 const int speedLimiter
= 96;
2636 const int autoScrollBorder
= 64;
2638 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2639 // This assures that the autoscrolling speed grows gradually.
2640 const int incLimiter
= 1;
2642 if (pos
< autoScrollBorder
) {
2643 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2644 inc
= qMax(inc
, -maxSpeed
);
2645 inc
= qMax(inc
, oldInc
- incLimiter
);
2646 } else if (pos
> range
- autoScrollBorder
) {
2647 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2648 inc
= qMin(inc
, maxSpeed
);
2649 inc
= qMin(inc
, oldInc
+ incLimiter
);
2655 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2657 const qreal availableSize
= size
- itemMargin
;
2658 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2664 KItemListCreatorBase::~KItemListCreatorBase()
2666 qDeleteAll(m_recycleableWidgets
);
2667 qDeleteAll(m_createdWidgets
);
2670 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2672 m_createdWidgets
.insert(widget
);
2675 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2677 Q_ASSERT(m_createdWidgets
.contains(widget
));
2678 m_createdWidgets
.remove(widget
);
2680 if (m_recycleableWidgets
.count() < 100) {
2681 m_recycleableWidgets
.append(widget
);
2682 widget
->setVisible(false);
2688 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2690 if (m_recycleableWidgets
.isEmpty()) {
2694 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2695 m_createdWidgets
.insert(widget
);
2699 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2703 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2705 widget
->setParentItem(0);
2706 widget
->setOpacity(1.0);
2707 pushRecycleableWidget(widget
);
2710 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2714 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2716 header
->setOpacity(1.0);
2717 pushRecycleableWidget(header
);
2720 #include "kitemlistview.moc"