2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
4 * Based on the Itemviews NG project from Trolltech Labs
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kitemlistview.h"
11 #include "dolphindebug.h"
12 #include "kitemlistcontainer.h"
13 #include "kitemlistcontroller.h"
14 #include "kitemlistheader.h"
15 #include "kitemlistselectionmanager.h"
16 #include "kitemlistviewaccessible.h"
17 #include "kstandarditemlistwidget.h"
19 #include "private/kitemlistheaderwidget.h"
20 #include "private/kitemlistrubberband.h"
21 #include "private/kitemlistsizehintresolver.h"
22 #include "private/kitemlistviewlayouter.h"
24 #include <QElapsedTimer>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QGraphicsView>
27 #include <QPropertyAnimation>
28 #include <QStyleOptionRubberBand>
30 #include <QVariantAnimation>
34 // Time in ms until reaching the autoscroll margin triggers
35 // an initial autoscrolling
36 const int InitialAutoScrollDelay
= 700;
38 // Delay in ms for triggering the next autoscroll
39 const int RepeatingAutoScrollDelay
= 1000 / 60;
41 // Copied from the Kirigami.Units.shortDuration
42 const int RubberFadeSpeed
= 150;
44 const char* RubberPropertyName
= "_kitemviews_rubberBandPosition";
47 #ifndef QT_NO_ACCESSIBILITY
48 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
52 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
53 return new KItemListContainerAccessible(container
);
54 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
55 return new KItemListViewAccessible(view
);
62 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
63 QGraphicsWidget(parent
),
64 m_enabledSelectionToggles(false),
66 m_supportsItemExpanding(false),
68 m_activeTransactions(0),
69 m_endTransactionAnimationHint(Animation
),
71 m_controller(nullptr),
74 m_widgetCreator(nullptr),
75 m_groupHeaderCreator(nullptr),
80 m_sizeHintResolver(nullptr),
83 m_layoutTimer(nullptr),
85 m_oldMaximumScrollOffset(0),
87 m_oldMaximumItemOffset(0),
88 m_skipAutoScrollForRubberBand(false),
89 m_rubberBand(nullptr),
90 m_tapAndHoldIndicator(nullptr),
92 m_autoScrollIncrement(0),
93 m_autoScrollTimer(nullptr),
95 m_headerWidget(nullptr),
96 m_indicatorAnimation(nullptr),
99 setAcceptHoverEvents(true);
100 setAcceptTouchEvents(true);
102 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
104 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
106 m_animation
= new KItemListViewAnimation(this);
107 connect(m_animation
, &KItemListViewAnimation::finished
,
108 this, &KItemListView::slotAnimationFinished
);
110 m_layoutTimer
= new QTimer(this);
111 m_layoutTimer
->setInterval(300);
112 m_layoutTimer
->setSingleShot(true);
113 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
115 m_rubberBand
= new KItemListRubberBand(this);
116 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
118 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
119 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
120 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
122 m_indicatorAnimation
->setDuration(150);
123 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
124 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
125 m_indicatorAnimation
->start();
129 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
130 if (m_tapAndHoldIndicator
->isActive()) {
135 m_headerWidget
= new KItemListHeaderWidget(this);
136 m_headerWidget
->setVisible(false);
138 m_header
= new KItemListHeader(this);
140 #ifndef QT_NO_ACCESSIBILITY
141 QAccessible::installFactory(accessibleInterfaceFactory
);
146 KItemListView::~KItemListView()
148 // The group headers are children of the widgets created by
149 // widgetCreator(). So it is mandatory to delete the group headers
151 delete m_groupHeaderCreator
;
152 m_groupHeaderCreator
= nullptr;
154 delete m_widgetCreator
;
155 m_widgetCreator
= nullptr;
157 delete m_sizeHintResolver
;
158 m_sizeHintResolver
= nullptr;
161 void KItemListView::setScrollOffset(qreal offset
)
167 const qreal previousOffset
= m_layouter
->scrollOffset();
168 if (offset
== previousOffset
) {
172 m_layouter
->setScrollOffset(offset
);
173 m_animation
->setScrollOffset(offset
);
175 // Don't check whether the m_layoutTimer is active: Changing the
176 // scroll offset must always trigger a synchronous layout, otherwise
177 // the smooth-scrolling might get jerky.
178 doLayout(NoAnimation
);
179 onScrollOffsetChanged(offset
, previousOffset
);
182 qreal
KItemListView::scrollOffset() const
184 return m_layouter
->scrollOffset();
187 qreal
KItemListView::maximumScrollOffset() const
189 return m_layouter
->maximumScrollOffset();
192 void KItemListView::setItemOffset(qreal offset
)
194 if (m_layouter
->itemOffset() == offset
) {
198 m_layouter
->setItemOffset(offset
);
199 if (m_headerWidget
->isVisible()) {
200 m_headerWidget
->setOffset(offset
);
203 // Don't check whether the m_layoutTimer is active: Changing the
204 // item offset must always trigger a synchronous layout, otherwise
205 // the smooth-scrolling might get jerky.
206 doLayout(NoAnimation
);
209 qreal
KItemListView::itemOffset() const
211 return m_layouter
->itemOffset();
214 qreal
KItemListView::maximumItemOffset() const
216 return m_layouter
->maximumItemOffset();
219 int KItemListView::maximumVisibleItems() const
221 return m_layouter
->maximumVisibleItems();
224 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
226 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
227 m_visibleRoles
= roles
;
228 onVisibleRolesChanged(roles
, previousRoles
);
230 m_sizeHintResolver
->clearCache();
231 m_layouter
->markAsDirty();
233 if (m_itemSize
.isEmpty()) {
234 m_headerWidget
->setColumns(roles
);
235 updatePreferredColumnWidths();
236 if (!m_headerWidget
->automaticColumnResizing()) {
237 // The column-width of new roles are still 0. Apply the preferred
238 // column-width as default with.
239 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
240 if (m_headerWidget
->columnWidth(role
) == 0) {
241 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
242 m_headerWidget
->setColumnWidth(role
, width
);
246 applyColumnWidthsFromHeader();
250 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
251 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
252 (roles
.count() <= 1 && previousRoles
.count() > 1));
254 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
255 while (it
.hasNext()) {
257 KItemListWidget
* widget
= it
.value();
258 widget
->setVisibleRoles(roles
);
259 if (alternateBackgroundsChanged
) {
260 updateAlternateBackgroundForWidget(widget
);
264 doLayout(NoAnimation
);
267 QList
<QByteArray
> KItemListView::visibleRoles() const
269 return m_visibleRoles
;
272 void KItemListView::setAutoScroll(bool enabled
)
274 if (enabled
&& !m_autoScrollTimer
) {
275 m_autoScrollTimer
= new QTimer(this);
276 m_autoScrollTimer
->setSingleShot(true);
277 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
278 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
279 } else if (!enabled
&& m_autoScrollTimer
) {
280 delete m_autoScrollTimer
;
281 m_autoScrollTimer
= nullptr;
285 bool KItemListView::autoScroll() const
287 return m_autoScrollTimer
!= nullptr;
290 void KItemListView::setEnabledSelectionToggles(bool enabled
)
292 if (m_enabledSelectionToggles
!= enabled
) {
293 m_enabledSelectionToggles
= enabled
;
295 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
296 while (it
.hasNext()) {
298 it
.value()->setEnabledSelectionToggle(enabled
);
303 bool KItemListView::enabledSelectionToggles() const
305 return m_enabledSelectionToggles
;
308 KItemListController
* KItemListView::controller() const
313 KItemModelBase
* KItemListView::model() const
318 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
320 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 delete m_groupHeaderCreator
;
335 m_groupHeaderCreator
= groupHeaderCreator
;
338 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
340 if (!m_groupHeaderCreator
) {
341 m_groupHeaderCreator
= defaultGroupHeaderCreator();
343 return m_groupHeaderCreator
;
346 QSizeF
KItemListView::itemSize() const
351 const KItemListStyleOption
& KItemListView::styleOption() const
353 return m_styleOption
;
356 void KItemListView::setGeometry(const QRectF
& rect
)
358 QGraphicsWidget::setGeometry(rect
);
364 const QSizeF newSize
= rect
.size();
365 if (m_itemSize
.isEmpty()) {
366 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
367 if (m_headerWidget
->automaticColumnResizing()) {
368 applyAutomaticColumnWidths();
370 const qreal requiredWidth
= columnWidthsSum();
371 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
372 m_itemSize
.height());
373 m_layouter
->setItemSize(dynamicItemSize
);
376 // Triggering a synchronous layout is fine from a performance point of view,
377 // as with dynamic item sizes no moving animation must be done.
378 m_layouter
->setSize(newSize
);
379 doLayout(NoAnimation
);
381 const bool animate
= !changesItemGridLayout(newSize
,
382 m_layouter
->itemSize(),
383 m_layouter
->itemMargin());
384 m_layouter
->setSize(newSize
);
387 // Trigger an asynchronous relayout with m_layoutTimer to prevent
388 // performance bottlenecks. If the timer is exceeded, an animated layout
389 // will be triggered.
390 if (!m_layoutTimer
->isActive()) {
391 m_layoutTimer
->start();
394 m_layoutTimer
->stop();
395 doLayout(NoAnimation
);
400 qreal
KItemListView::verticalPageStep() const
402 qreal headerHeight
= 0;
403 if (m_headerWidget
->isVisible()) {
404 headerHeight
= m_headerWidget
->size().height();
406 return size().height() - headerHeight
;
409 int KItemListView::itemAt(const QPointF
& pos
) const
411 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
412 while (it
.hasNext()) {
415 const KItemListWidget
* widget
= it
.value();
416 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
417 if (widget
->contains(mappedPos
)) {
425 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
427 if (!m_enabledSelectionToggles
) {
431 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
433 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
434 if (!selectionToggleRect
.isEmpty()) {
435 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
436 return selectionToggleRect
.contains(mappedPos
);
442 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
444 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
446 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
447 if (!expansionToggleRect
.isEmpty()) {
448 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
449 return expansionToggleRect
.contains(mappedPos
);
455 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
457 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
459 const QRectF
&textRect
= widget
->textRect();
460 if (!textRect
.isEmpty()) {
461 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
462 return textRect
.contains(mappedPos
);
468 int KItemListView::firstVisibleIndex() const
470 return m_layouter
->firstVisibleIndex();
473 int KItemListView::lastVisibleIndex() const
475 return m_layouter
->lastVisibleIndex();
478 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
480 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
483 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
485 if (m_supportsItemExpanding
!= supportsExpanding
) {
486 m_supportsItemExpanding
= supportsExpanding
;
487 updateSiblingsInformation();
488 onSupportsItemExpandingChanged(supportsExpanding
);
492 bool KItemListView::supportsItemExpanding() const
494 return m_supportsItemExpanding
;
497 QRectF
KItemListView::itemRect(int index
) const
499 return m_layouter
->itemRect(index
);
502 QRectF
KItemListView::itemContextRect(int index
) const
506 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
508 contextRect
= widget
->iconRect() | widget
->textRect();
509 contextRect
.translate(itemRect(index
).topLeft());
515 void KItemListView::scrollToItem(int index
)
517 QRectF viewGeometry
= geometry();
518 if (m_headerWidget
->isVisible()) {
519 const qreal headerHeight
= m_headerWidget
->size().height();
520 viewGeometry
.adjust(0, headerHeight
, 0, 0);
522 QRectF currentRect
= itemRect(index
);
524 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
525 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
526 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
528 if (!viewGeometry
.contains(currentRect
)) {
529 qreal newOffset
= scrollOffset();
530 if (scrollOrientation() == Qt::Vertical
) {
531 if (currentRect
.top() < viewGeometry
.top()) {
532 newOffset
+= currentRect
.top() - viewGeometry
.top();
533 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
534 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
537 if (currentRect
.left() < viewGeometry
.left()) {
538 newOffset
+= currentRect
.left() - viewGeometry
.left();
539 } else if (currentRect
.right() > viewGeometry
.right()) {
540 newOffset
+= currentRect
.right() - viewGeometry
.right();
544 if (newOffset
!= scrollOffset()) {
545 Q_EMIT
scrollTo(newOffset
);
550 void KItemListView::beginTransaction()
552 ++m_activeTransactions
;
553 if (m_activeTransactions
== 1) {
554 onTransactionBegin();
558 void KItemListView::endTransaction()
560 --m_activeTransactions
;
561 if (m_activeTransactions
< 0) {
562 m_activeTransactions
= 0;
563 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
566 if (m_activeTransactions
== 0) {
568 doLayout(m_endTransactionAnimationHint
);
569 m_endTransactionAnimationHint
= Animation
;
573 bool KItemListView::isTransactionActive() const
575 return m_activeTransactions
> 0;
578 void KItemListView::setHeaderVisible(bool visible
)
580 if (visible
&& !m_headerWidget
->isVisible()) {
581 QStyleOptionHeader option
;
582 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
585 m_headerWidget
->setPos(0, 0);
586 m_headerWidget
->resize(size().width(), headerSize
.height());
587 m_headerWidget
->setModel(m_model
);
588 m_headerWidget
->setColumns(m_visibleRoles
);
589 m_headerWidget
->setZValue(1);
591 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
592 this, &KItemListView::slotHeaderColumnWidthChanged
);
593 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
594 this, &KItemListView::slotHeaderColumnMoved
);
595 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
596 this, &KItemListView::sortOrderChanged
);
597 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
598 this, &KItemListView::sortRoleChanged
);
600 m_layouter
->setHeaderHeight(headerSize
.height());
601 m_headerWidget
->setVisible(true);
602 } else if (!visible
&& m_headerWidget
->isVisible()) {
603 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
604 this, &KItemListView::slotHeaderColumnWidthChanged
);
605 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
606 this, &KItemListView::slotHeaderColumnMoved
);
607 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
608 this, &KItemListView::sortOrderChanged
);
609 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
610 this, &KItemListView::sortRoleChanged
);
612 m_layouter
->setHeaderHeight(0);
613 m_headerWidget
->setVisible(false);
617 bool KItemListView::isHeaderVisible() const
619 return m_headerWidget
->isVisible();
622 KItemListHeader
* KItemListView::header() const
627 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
631 if (indexes
.count() == 1) {
632 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
633 QGraphicsView
* graphicsView
= scene()->views()[0];
634 if (item
&& graphicsView
) {
635 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
638 // TODO: Not implemented yet. Probably extend the interface
639 // from KItemListWidget::createDragPixmap() to return a pixmap
640 // that can be used for multiple indexes.
646 void KItemListView::editRole(int index
, const QByteArray
& role
)
648 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
649 if (!widget
|| m_editingRole
) {
653 m_editingRole
= true;
654 widget
->setEditedRole(role
);
656 connect(widget
, &KItemListWidget::roleEditingCanceled
,
657 this, &KItemListView::slotRoleEditingCanceled
);
658 connect(widget
, &KItemListWidget::roleEditingFinished
,
659 this, &KItemListView::slotRoleEditingFinished
);
661 connect(this, &KItemListView::scrollOffsetChanged
,
662 widget
, &KStandardItemListWidget::finishRoleEditing
);
665 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
667 QGraphicsWidget::paint(painter
, option
, widget
);
669 for (auto animation
: qAsConst(m_rubberBandAnimations
)) {
670 QRectF rubberBandRect
= animation
->property(RubberPropertyName
).toRectF();
672 const QPointF topLeft
= rubberBandRect
.topLeft();
673 if (scrollOrientation() == Qt::Vertical
) {
674 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
676 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
679 QStyleOptionRubberBand opt
;
680 initStyleOption(&opt
);
681 opt
.shape
= QRubberBand::Rectangle
;
683 opt
.rect
= rubberBandRect
.toRect();
687 painter
->setOpacity(animation
->currentValue().toReal());
688 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
693 if (m_rubberBand
->isActive()) {
694 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
695 m_rubberBand
->endPosition()).normalized();
697 const QPointF topLeft
= rubberBandRect
.topLeft();
698 if (scrollOrientation() == Qt::Vertical
) {
699 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
701 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
704 QStyleOptionRubberBand opt
;
705 initStyleOption(&opt
);
706 opt
.shape
= QRubberBand::Rectangle
;
708 opt
.rect
= rubberBandRect
.toRect();
709 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
712 if (m_tapAndHoldIndicator
->isActive()) {
713 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
714 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
715 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
716 QStyleOptionRubberBand opt
;
717 initStyleOption(&opt
);
718 opt
.shape
= QRubberBand::Rectangle
;
720 opt
.rect
= rubberBandRect
.toRect();
721 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
724 if (!m_dropIndicator
.isEmpty()) {
725 const QRectF r
= m_dropIndicator
.toRect();
727 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
728 painter
->setPen(color
);
730 // TODO: The following implementation works only for a vertical scroll-orientation
731 // and assumes a height of the m_draggingInsertIndicator of 1.
732 Q_ASSERT(r
.height() == 1);
733 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
736 painter
->setPen(color
);
737 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
741 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
743 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
744 if (!scene()->views().isEmpty()) {
745 m_styleOption
.palette
= scene()->views().at(0)->palette();
748 return QGraphicsItem::itemChange(change
, value
);
751 void KItemListView::setItemSize(const QSizeF
& size
)
753 const QSizeF previousSize
= m_itemSize
;
754 if (size
== previousSize
) {
758 // Skip animations when the number of rows or columns
759 // are changed in the grid layout. Although the animation
760 // engine can handle this usecase, it looks obtrusive.
761 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
763 m_layouter
->itemMargin());
765 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
766 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
767 (!m_itemSize
.isEmpty() && size
.isEmpty()));
771 if (alternateBackgroundsChanged
) {
772 // For an empty item size alternate backgrounds are drawn if more than
773 // one role is shown. Assure that the backgrounds for visible items are
774 // updated when changing the size in this context.
775 updateAlternateBackgrounds();
778 if (size
.isEmpty()) {
779 if (m_headerWidget
->automaticColumnResizing()) {
780 updatePreferredColumnWidths();
782 // Only apply the changed height and respect the header widths
784 const qreal currentWidth
= m_layouter
->itemSize().width();
785 const QSizeF
newSize(currentWidth
, size
.height());
786 m_layouter
->setItemSize(newSize
);
789 m_layouter
->setItemSize(size
);
792 m_sizeHintResolver
->clearCache();
793 doLayout(animate
? Animation
: NoAnimation
);
794 onItemSizeChanged(size
, previousSize
);
797 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
799 if (m_styleOption
== option
) {
803 const KItemListStyleOption previousOption
= m_styleOption
;
804 m_styleOption
= option
;
807 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
808 if (margin
!= m_layouter
->itemMargin()) {
809 // Skip animations when the number of rows or columns
810 // are changed in the grid layout. Although the animation
811 // engine can handle this usecase, it looks obtrusive.
812 animate
= !changesItemGridLayout(m_layouter
->size(),
813 m_layouter
->itemSize(),
815 m_layouter
->setItemMargin(margin
);
819 updateGroupHeaderHeight();
823 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
824 // Animating a change of the maximum text size just results in expensive
825 // temporary eliding and clipping operations and does not look good visually.
829 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
830 while (it
.hasNext()) {
832 it
.value()->setStyleOption(option
);
835 m_sizeHintResolver
->clearCache();
836 m_layouter
->markAsDirty();
837 doLayout(animate
? Animation
: NoAnimation
);
839 if (m_itemSize
.isEmpty()) {
840 updatePreferredColumnWidths();
843 onStyleOptionChanged(option
, previousOption
);
846 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
848 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
849 if (orientation
== previousOrientation
) {
853 m_layouter
->setScrollOrientation(orientation
);
854 m_animation
->setScrollOrientation(orientation
);
855 m_sizeHintResolver
->clearCache();
858 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
859 while (it
.hasNext()) {
861 it
.value()->setScrollOrientation(orientation
);
863 updateGroupHeaderHeight();
867 doLayout(NoAnimation
);
869 onScrollOrientationChanged(orientation
, previousOrientation
);
870 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
873 Qt::Orientation
KItemListView::scrollOrientation() const
875 return m_layouter
->scrollOrientation();
878 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
883 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
888 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
893 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
895 Q_UNUSED(changedRoles
)
899 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
905 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
911 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
917 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
923 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
929 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
935 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
941 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
943 Q_UNUSED(supportsExpanding
)
946 void KItemListView::onTransactionBegin()
950 void KItemListView::onTransactionEnd()
954 bool KItemListView::event(QEvent
* event
)
956 switch (event
->type()) {
957 case QEvent::PaletteChange
:
961 case QEvent::FontChange
:
966 // Forward all other events to the controller and handle them there
967 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
973 return QGraphicsWidget::event(event
);
976 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
978 m_mousePos
= transform().map(event
->pos());
982 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
984 QGraphicsWidget::mouseMoveEvent(event
);
986 m_mousePos
= transform().map(event
->pos());
987 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
988 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
992 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
994 event
->setAccepted(true);
998 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
1000 QGraphicsWidget::dragMoveEvent(event
);
1002 m_mousePos
= transform().map(event
->pos());
1003 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1004 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1008 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
1010 QGraphicsWidget::dragLeaveEvent(event
);
1011 setAutoScroll(false);
1014 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
1016 QGraphicsWidget::dropEvent(event
);
1017 setAutoScroll(false);
1020 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
1022 return m_visibleItems
.values();
1025 void KItemListView::updateFont()
1027 if (scene() && !scene()->views().isEmpty()) {
1028 KItemListStyleOption option
= styleOption();
1029 option
.font
= scene()->views().first()->font();
1030 option
.fontMetrics
= QFontMetrics(option
.font
);
1032 setStyleOption(option
);
1036 void KItemListView::updatePalette()
1038 if (scene() && !scene()->views().isEmpty()) {
1039 KItemListStyleOption option
= styleOption();
1040 option
.palette
= scene()->views().first()->palette();
1042 setStyleOption(option
);
1046 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1048 if (m_itemSize
.isEmpty()) {
1049 updatePreferredColumnWidths(itemRanges
);
1052 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1053 if (hasMultipleRanges
) {
1057 m_layouter
->markAsDirty();
1059 m_sizeHintResolver
->itemsInserted(itemRanges
);
1061 int previouslyInsertedCount
= 0;
1062 for (const KItemRange
& range
: itemRanges
) {
1063 // range.index is related to the model before anything has been inserted.
1064 // As in each loop the current item-range gets inserted the index must
1065 // be increased by the already previously inserted items.
1066 const int index
= range
.index
+ previouslyInsertedCount
;
1067 const int count
= range
.count
;
1068 if (index
< 0 || count
<= 0) {
1069 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1072 previouslyInsertedCount
+= count
;
1074 // Determine which visible items must be moved
1075 QList
<int> itemsToMove
;
1076 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1077 while (it
.hasNext()) {
1079 const int visibleItemIndex
= it
.key();
1080 if (visibleItemIndex
>= index
) {
1081 itemsToMove
.append(visibleItemIndex
);
1085 // Update the indexes of all KItemListWidget instances that are located
1086 // after the inserted items. It is important to adjust the indexes in the order
1087 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1088 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1089 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1090 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1092 const int newIndex
= widget
->index() + count
;
1093 if (hasMultipleRanges
) {
1094 setWidgetIndex(widget
, newIndex
);
1096 // Try to animate the moving of the item
1097 moveWidgetToIndex(widget
, newIndex
);
1101 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1102 // Check whether a scrollbar is required to show the inserted items. In this case
1103 // the size of the layouter will be decreased before calling doLayout(): This prevents
1104 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1105 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1106 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1107 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1108 if (decreaseLayouterSize
) {
1109 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1111 int scrollbarSpacing
= 0;
1112 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1113 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1116 QSizeF layouterSize
= m_layouter
->size();
1117 if (verticalScrollOrientation
) {
1118 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1120 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1122 m_layouter
->setSize(layouterSize
);
1126 if (!hasMultipleRanges
) {
1127 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1128 updateSiblingsInformation();
1133 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1136 if (hasMultipleRanges
) {
1137 m_endTransactionAnimationHint
= NoAnimation
;
1140 updateSiblingsInformation();
1143 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1144 // In case if items of the same group have been inserted before an item that
1145 // currently represents the first item of the group, the group header of
1146 // this item must be removed.
1147 updateVisibleGroupHeaders();
1150 if (useAlternateBackgrounds()) {
1151 updateAlternateBackgrounds();
1155 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1157 if (m_itemSize
.isEmpty()) {
1158 // Don't pass the item-range: The preferred column-widths of
1159 // all items must be adjusted when removing items.
1160 updatePreferredColumnWidths();
1163 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1164 if (hasMultipleRanges
) {
1168 m_layouter
->markAsDirty();
1170 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1172 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1173 const KItemRange
& range
= itemRanges
[i
];
1174 const int index
= range
.index
;
1175 const int count
= range
.count
;
1176 if (index
< 0 || count
<= 0) {
1177 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1181 const int firstRemovedIndex
= index
;
1182 const int lastRemovedIndex
= index
+ count
- 1;
1184 // Remember which items have to be moved because they are behind the removed range.
1185 QVector
<int> itemsToMove
;
1187 // Remove all KItemListWidget instances that got deleted
1188 // Iterate over a const copy because the container is mutated within the loop
1189 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1190 const auto visibleItems
= m_visibleItems
;
1191 for (KItemListWidget
* widget
: visibleItems
) {
1192 const int i
= widget
->index();
1193 if (i
< firstRemovedIndex
) {
1195 } else if (i
> lastRemovedIndex
) {
1196 itemsToMove
.append(i
);
1200 m_animation
->stop(widget
);
1201 // Stopping the animation might lead to recycling the widget if
1202 // it is invisible (see slotAnimationFinished()).
1203 // Check again whether it is still visible:
1204 if (!m_visibleItems
.contains(i
)) {
1208 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1209 // Remove the widget without animation
1210 recycleWidget(widget
);
1212 // Animate the removing of the items. Special case: When removing an item there
1213 // is no valid model index available anymore. For the
1214 // remove-animation the item gets removed from m_visibleItems but the widget
1215 // will stay alive until the animation has been finished and will
1216 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1217 m_visibleItems
.remove(i
);
1218 widget
->setIndex(-1);
1219 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1223 // Update the indexes of all KItemListWidget instances that are located
1224 // after the deleted items. It is important to update them in ascending
1225 // order to prevent overlaps when setting the new index.
1226 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1227 for (int i
: qAsConst(itemsToMove
)) {
1228 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1230 const int newIndex
= i
- count
;
1231 if (hasMultipleRanges
) {
1232 setWidgetIndex(widget
, newIndex
);
1234 // Try to animate the moving of the item
1235 moveWidgetToIndex(widget
, newIndex
);
1239 if (!hasMultipleRanges
) {
1240 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1241 // assumes an updated geometry. If items are removed during an active transaction,
1242 // the transaction will be temporary deactivated so that doLayout() triggers a
1243 // geometry update if necessary.
1244 const int activeTransactions
= m_activeTransactions
;
1245 m_activeTransactions
= 0;
1246 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1247 m_activeTransactions
= activeTransactions
;
1248 updateSiblingsInformation();
1253 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1256 if (hasMultipleRanges
) {
1257 m_endTransactionAnimationHint
= NoAnimation
;
1259 updateSiblingsInformation();
1262 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1263 // In case if the first item of a group has been removed, the group header
1264 // must be applied to the next visible item.
1265 updateVisibleGroupHeaders();
1268 if (useAlternateBackgrounds()) {
1269 updateAlternateBackgrounds();
1273 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1275 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1276 m_layouter
->markAsDirty();
1279 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1282 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1283 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1285 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1286 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1288 updateWidgetProperties(widget
, index
);
1289 initializeItemListWidget(widget
);
1293 doLayout(NoAnimation
);
1294 updateSiblingsInformation();
1297 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1298 const QSet
<QByteArray
>& roles
)
1300 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1301 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1302 updatePreferredColumnWidths(itemRanges
);
1305 for (const KItemRange
& itemRange
: itemRanges
) {
1306 const int index
= itemRange
.index
;
1307 const int count
= itemRange
.count
;
1309 if (updateSizeHints
) {
1310 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1311 m_layouter
->markAsDirty();
1313 if (!m_layoutTimer
->isActive()) {
1314 m_layoutTimer
->start();
1318 // Apply the changed roles to the visible item-widgets
1319 const int lastIndex
= index
+ count
- 1;
1320 for (int i
= index
; i
<= lastIndex
; ++i
) {
1321 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1323 widget
->setData(m_model
->data(i
), roles
);
1327 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1328 // The sort-role has been changed which might result
1329 // in modified group headers
1330 updateVisibleGroupHeaders();
1331 doLayout(NoAnimation
);
1334 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1335 ev
.setFirstRow(itemRange
.index
);
1336 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1337 QAccessible::updateAccessibility(&ev
);
1341 void KItemListView::slotGroupsChanged()
1343 updateVisibleGroupHeaders();
1344 doLayout(NoAnimation
);
1345 updateSiblingsInformation();
1348 void KItemListView::slotGroupedSortingChanged(bool current
)
1350 m_grouped
= current
;
1351 m_layouter
->markAsDirty();
1354 updateGroupHeaderHeight();
1356 // Clear all visible headers. Note that the QHashIterator takes a copy of
1357 // m_visibleGroups. Therefore, it remains valid even if items are removed
1358 // from m_visibleGroups in recycleGroupHeaderForWidget().
1359 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1360 while (it
.hasNext()) {
1362 recycleGroupHeaderForWidget(it
.key());
1364 Q_ASSERT(m_visibleGroups
.isEmpty());
1367 if (useAlternateBackgrounds()) {
1368 // Changing the group mode requires to update the alternate backgrounds
1369 // as with the enabled group mode the altering is done on base of the first
1371 updateAlternateBackgrounds();
1373 updateSiblingsInformation();
1374 doLayout(NoAnimation
);
1377 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1382 updateVisibleGroupHeaders();
1383 doLayout(NoAnimation
);
1387 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1392 updateVisibleGroupHeaders();
1393 doLayout(NoAnimation
);
1397 void KItemListView::slotCurrentChanged(int current
, int previous
)
1401 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1402 // always the selected item. It is not necessary to highlight the current item then.
1403 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1404 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1405 if (previousWidget
) {
1406 previousWidget
->setCurrent(false);
1409 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1410 if (currentWidget
) {
1411 currentWidget
->setCurrent(true);
1415 QAccessibleEvent
ev(this, QAccessible::Focus
);
1416 ev
.setChild(current
);
1417 QAccessible::updateAccessibility(&ev
);
1420 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1424 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1425 while (it
.hasNext()) {
1427 const int index
= it
.key();
1428 KItemListWidget
* widget
= it
.value();
1429 widget
->setSelected(current
.contains(index
));
1433 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1434 KItemListViewAnimation::AnimationType type
)
1436 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1437 Q_ASSERT(itemListWidget
);
1440 case KItemListViewAnimation::DeleteAnimation
: {
1441 // As we recycle the widget in this case it is important to assure that no
1442 // other animation has been started. This is a convention in KItemListView and
1443 // not a requirement defined by KItemListViewAnimation.
1444 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1446 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1447 // by m_visibleWidgets and must be deleted manually after the animation has
1449 recycleGroupHeaderForWidget(itemListWidget
);
1450 widgetCreator()->recycle(itemListWidget
);
1454 case KItemListViewAnimation::CreateAnimation
:
1455 case KItemListViewAnimation::MovingAnimation
:
1456 case KItemListViewAnimation::ResizeAnimation
: {
1457 const int index
= itemListWidget
->index();
1458 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1459 (index
> m_layouter
->lastVisibleIndex());
1460 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1461 recycleWidget(itemListWidget
);
1470 void KItemListView::slotLayoutTimerFinished()
1472 m_layouter
->setSize(geometry().size());
1473 doLayout(Animation
);
1476 void KItemListView::slotRubberBandPosChanged()
1481 void KItemListView::slotRubberBandActivationChanged(bool active
)
1484 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1485 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1486 m_skipAutoScrollForRubberBand
= true;
1488 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
1489 m_rubberBand
->endPosition()).normalized();
1491 auto animation
= new QVariantAnimation(this);
1492 animation
->setStartValue(1.0);
1493 animation
->setEndValue(0.0);
1494 animation
->setDuration(RubberFadeSpeed
);
1495 animation
->setProperty(RubberPropertyName
, rubberBandRect
);
1498 curve
.setType(QEasingCurve::BezierSpline
);
1499 curve
.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1500 animation
->setEasingCurve(curve
);
1502 connect(animation
, &QVariantAnimation::valueChanged
, this, [=](const QVariant
&) {
1505 connect(animation
, &QVariantAnimation::finished
, this, [=]() {
1506 m_rubberBandAnimations
.removeAll(animation
);
1510 m_rubberBandAnimations
<< animation
;
1512 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1513 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1514 m_skipAutoScrollForRubberBand
= false;
1520 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1522 qreal previousWidth
)
1525 Q_UNUSED(currentWidth
)
1526 Q_UNUSED(previousWidth
)
1528 m_headerWidget
->setAutomaticColumnResizing(false);
1529 applyColumnWidthsFromHeader();
1530 doLayout(NoAnimation
);
1533 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1537 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1539 const QList
<QByteArray
> previous
= m_visibleRoles
;
1541 QList
<QByteArray
> current
= m_visibleRoles
;
1542 current
.removeAt(previousIndex
);
1543 current
.insert(currentIndex
, role
);
1545 setVisibleRoles(current
);
1547 Q_EMIT
visibleRolesChanged(current
, previous
);
1550 void KItemListView::triggerAutoScrolling()
1552 if (!m_autoScrollTimer
) {
1557 int visibleSize
= 0;
1558 if (scrollOrientation() == Qt::Vertical
) {
1559 pos
= m_mousePos
.y();
1560 visibleSize
= size().height();
1562 pos
= m_mousePos
.x();
1563 visibleSize
= size().width();
1566 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1567 m_autoScrollIncrement
= 0;
1570 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1571 if (m_autoScrollIncrement
== 0) {
1572 // The mouse position is not above an autoscroll margin (the autoscroll timer
1573 // will be restarted in mouseMoveEvent())
1574 m_autoScrollTimer
->stop();
1578 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1579 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1580 // if the direction of the rubberband is similar to the autoscroll direction. This
1581 // prevents that starting to create a rubberband within the autoscroll margins starts
1582 // an autoscrolling.
1584 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1585 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1586 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1587 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1588 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1589 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1590 // been moved up although the autoscroll direction might be down)
1591 m_autoScrollTimer
->stop();
1596 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1597 // the autoscrolling may not get skipped anymore until a new rubberband is created
1598 m_skipAutoScrollForRubberBand
= false;
1600 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1601 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1602 setScrollOffset(newScrollOffset
);
1604 // Trigger the autoscroll timer which will periodically call
1605 // triggerAutoScrolling()
1606 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1609 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1611 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1613 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1614 Q_ASSERT(groupHeader
);
1615 updateGroupHeaderLayout(widget
);
1618 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1620 disconnectRoleEditingSignals(index
);
1622 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1623 m_editingRole
= false;
1626 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1628 disconnectRoleEditingSignals(index
);
1630 Q_EMIT
roleEditingFinished(index
, role
, value
);
1631 m_editingRole
= false;
1634 void KItemListView::setController(KItemListController
* controller
)
1636 if (m_controller
!= controller
) {
1637 KItemListController
* previous
= m_controller
;
1639 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1640 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1641 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1644 m_controller
= controller
;
1647 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1648 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1649 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1652 onControllerChanged(controller
, previous
);
1656 void KItemListView::setModel(KItemModelBase
* model
)
1658 if (m_model
== model
) {
1662 KItemModelBase
* previous
= m_model
;
1665 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1666 this, &KItemListView::slotItemsChanged
);
1667 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1668 this, &KItemListView::slotItemsInserted
);
1669 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1670 this, &KItemListView::slotItemsRemoved
);
1671 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1672 this, &KItemListView::slotItemsMoved
);
1673 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1674 this, &KItemListView::slotGroupsChanged
);
1675 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1676 this, &KItemListView::slotGroupedSortingChanged
);
1677 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1678 this, &KItemListView::slotSortOrderChanged
);
1679 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1680 this, &KItemListView::slotSortRoleChanged
);
1682 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1686 m_layouter
->setModel(model
);
1687 m_grouped
= model
->groupedSorting();
1690 connect(m_model
, &KItemModelBase::itemsChanged
,
1691 this, &KItemListView::slotItemsChanged
);
1692 connect(m_model
, &KItemModelBase::itemsInserted
,
1693 this, &KItemListView::slotItemsInserted
);
1694 connect(m_model
, &KItemModelBase::itemsRemoved
,
1695 this, &KItemListView::slotItemsRemoved
);
1696 connect(m_model
, &KItemModelBase::itemsMoved
,
1697 this, &KItemListView::slotItemsMoved
);
1698 connect(m_model
, &KItemModelBase::groupsChanged
,
1699 this, &KItemListView::slotGroupsChanged
);
1700 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1701 this, &KItemListView::slotGroupedSortingChanged
);
1702 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1703 this, &KItemListView::slotSortOrderChanged
);
1704 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1705 this, &KItemListView::slotSortRoleChanged
);
1707 const int itemCount
= m_model
->count();
1708 if (itemCount
> 0) {
1709 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1713 onModelChanged(model
, previous
);
1716 KItemListRubberBand
* KItemListView::rubberBand() const
1718 return m_rubberBand
;
1721 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1723 if (m_layoutTimer
->isActive()) {
1724 m_layoutTimer
->stop();
1727 if (m_activeTransactions
> 0) {
1728 if (hint
== NoAnimation
) {
1729 // As soon as at least one property change should be done without animation,
1730 // the whole transaction will be marked as not animated.
1731 m_endTransactionAnimationHint
= NoAnimation
;
1736 if (!m_model
|| m_model
->count() < 0) {
1740 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1741 if (firstVisibleIndex
< 0) {
1742 emitOffsetChanges();
1746 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1747 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1748 // is still shown if the maximum offset got decreased.
1749 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1750 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1751 if (scrollOffset() > maxOffsetToShowFullRange
) {
1752 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1753 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1756 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1758 int firstSibblingIndex
= -1;
1759 int lastSibblingIndex
= -1;
1760 const bool supportsExpanding
= supportsItemExpanding();
1762 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1764 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1765 // instances from invisible items are reused. If no reusable items are
1766 // found then new KItemListWidget instances get created.
1767 const bool animate
= (hint
== Animation
);
1768 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1769 bool applyNewPos
= true;
1770 bool wasHidden
= false;
1772 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1773 const QPointF newPos
= itemBounds
.topLeft();
1774 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1777 if (!reusableItems
.isEmpty()) {
1778 // Reuse a KItemListWidget instance from an invisible item
1779 const int oldIndex
= reusableItems
.takeLast();
1780 widget
= m_visibleItems
.value(oldIndex
);
1781 setWidgetIndex(widget
, i
);
1782 updateWidgetProperties(widget
, i
);
1783 initializeItemListWidget(widget
);
1785 // No reusable KItemListWidget instance is available, create a new one
1786 widget
= createWidget(i
);
1788 widget
->resize(itemBounds
.size());
1790 if (animate
&& changedCount
< 0) {
1791 // Items have been deleted.
1792 if (i
>= changedIndex
) {
1793 // The item is located behind the removed range. Move the
1794 // created item to the imaginary old position outside the
1795 // view. It will get animated to the new position later.
1796 const int previousIndex
= i
- changedCount
;
1797 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1798 if (itemRect
.isEmpty()) {
1799 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1800 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1801 widget
->setPos(invisibleOldPos
);
1803 widget
->setPos(itemRect
.topLeft());
1805 applyNewPos
= false;
1809 if (supportsExpanding
&& changedCount
== 0) {
1810 if (firstSibblingIndex
< 0) {
1811 firstSibblingIndex
= i
;
1813 lastSibblingIndex
= i
;
1818 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1819 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1820 applyNewPos
= false;
1823 const bool itemsRemoved
= (changedCount
< 0);
1824 const bool itemsInserted
= (changedCount
> 0);
1825 if (itemsRemoved
&& (i
>= changedIndex
)) {
1826 // The item is located after the removed items. Animate the moving of the position.
1827 applyNewPos
= !moveWidget(widget
, newPos
);
1828 } else if (itemsInserted
&& i
>= changedIndex
) {
1829 // The item is located after the first inserted item
1830 if (i
<= changedIndex
+ changedCount
- 1) {
1831 // The item is an inserted item. Animate the appearing of the item.
1832 // For performance reasons no animation is done when changedCount is equal
1833 // to all available items.
1834 if (changedCount
< m_model
->count()) {
1835 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1837 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1838 // The item was already there before, so animate the moving of the position.
1839 // No moving animation is done if the item is animated by a create animation: This
1840 // prevents a "move animation mess" when inserting several ranges in parallel.
1841 applyNewPos
= !moveWidget(widget
, newPos
);
1843 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1844 // The size of the view might have been changed. Animate the moving of the position.
1845 applyNewPos
= !moveWidget(widget
, newPos
);
1848 m_animation
->stop(widget
);
1852 widget
->setPos(newPos
);
1855 Q_ASSERT(widget
->index() == i
);
1856 widget
->setVisible(true);
1858 if (widget
->size() != itemBounds
.size()) {
1859 // Resize the widget for the item to the changed size.
1861 // If a dynamic item size is used then no animation is done in the direction
1862 // of the dynamic size.
1863 if (m_itemSize
.width() <= 0) {
1864 // The width is dynamic, apply the new width without animation.
1865 widget
->resize(itemBounds
.width(), widget
->size().height());
1866 } else if (m_itemSize
.height() <= 0) {
1867 // The height is dynamic, apply the new height without animation.
1868 widget
->resize(widget
->size().width(), itemBounds
.height());
1870 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1872 widget
->resize(itemBounds
.size());
1876 // Updating the cell-information must be done as last step: The decision whether the
1877 // moving-animation should be started at all is based on the previous cell-information.
1878 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1879 m_visibleCells
.insert(i
, cell
);
1882 // Delete invisible KItemListWidget instances that have not been reused
1883 for (int index
: qAsConst(reusableItems
)) {
1884 recycleWidget(m_visibleItems
.value(index
));
1887 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1888 Q_ASSERT(lastSibblingIndex
>= 0);
1889 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1893 // Update the layout of all visible group headers
1894 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1895 while (it
.hasNext()) {
1897 updateGroupHeaderLayout(it
.key());
1901 emitOffsetChanges();
1904 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1905 int lastVisibleIndex
,
1906 LayoutAnimationHint hint
)
1908 // Determine all items that are completely invisible and might be
1909 // reused for items that just got (at least partly) visible. If the
1910 // animation hint is set to 'Animation' items that do e.g. an animated
1911 // moving of their position are not marked as invisible: This assures
1912 // that a scrolling inside the view can be done without breaking an animation.
1916 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1917 while (it
.hasNext()) {
1920 KItemListWidget
* widget
= it
.value();
1921 const int index
= widget
->index();
1922 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1925 if (m_animation
->isStarted(widget
)) {
1926 if (hint
== NoAnimation
) {
1927 // Stopping the animation will call KItemListView::slotAnimationFinished()
1928 // and the widget will be recycled if necessary there.
1929 m_animation
->stop(widget
);
1932 widget
->setVisible(false);
1933 items
.append(index
);
1936 recycleGroupHeaderForWidget(widget
);
1945 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1947 if (widget
->pos() == newPos
) {
1951 bool startMovingAnim
= false;
1953 if (m_itemSize
.isEmpty()) {
1954 // The items are not aligned in a grid but either as columns or rows.
1955 startMovingAnim
= true;
1957 // When having a grid the moving-animation should only be started, if it is done within
1958 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1959 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1960 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1961 const int index
= widget
->index();
1962 const Cell cell
= m_visibleCells
.value(index
);
1963 if (cell
.column
>= 0 && cell
.row
>= 0) {
1964 if (scrollOrientation() == Qt::Vertical
) {
1965 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1967 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1972 if (startMovingAnim
) {
1973 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1977 m_animation
->stop(widget
);
1978 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1982 void KItemListView::emitOffsetChanges()
1984 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1985 if (m_oldScrollOffset
!= newScrollOffset
) {
1986 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1987 m_oldScrollOffset
= newScrollOffset
;
1990 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1991 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1992 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1993 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1996 const qreal newItemOffset
= m_layouter
->itemOffset();
1997 if (m_oldItemOffset
!= newItemOffset
) {
1998 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1999 m_oldItemOffset
= newItemOffset
;
2002 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
2003 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
2004 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
2005 m_oldMaximumItemOffset
= newMaximumItemOffset
;
2009 KItemListWidget
* KItemListView::createWidget(int index
)
2011 KItemListWidget
* widget
= widgetCreator()->create(this);
2012 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
2014 m_visibleItems
.insert(index
, widget
);
2015 m_visibleCells
.insert(index
, Cell());
2016 updateWidgetProperties(widget
, index
);
2017 initializeItemListWidget(widget
);
2021 void KItemListView::recycleWidget(KItemListWidget
* widget
)
2024 recycleGroupHeaderForWidget(widget
);
2027 const int index
= widget
->index();
2028 m_visibleItems
.remove(index
);
2029 m_visibleCells
.remove(index
);
2031 widgetCreator()->recycle(widget
);
2034 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
2036 const int oldIndex
= widget
->index();
2037 m_visibleItems
.remove(oldIndex
);
2038 m_visibleCells
.remove(oldIndex
);
2040 m_visibleItems
.insert(index
, widget
);
2041 m_visibleCells
.insert(index
, Cell());
2043 widget
->setIndex(index
);
2046 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
2048 const int oldIndex
= widget
->index();
2049 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
2051 setWidgetIndex(widget
, index
);
2053 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2054 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2055 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
2056 (!vertical
&& oldCell
.column
== newCell
.column
);
2058 m_visibleCells
.insert(index
, newCell
);
2062 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2065 case LayouterSize
: m_layouter
->setSize(size
); break;
2066 case ItemSize
: m_layouter
->setItemSize(size
); break;
2071 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2073 widget
->setVisibleRoles(m_visibleRoles
);
2074 updateWidgetColumnWidths(widget
);
2075 widget
->setStyleOption(m_styleOption
);
2077 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2079 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2080 // always the selected item. It is not necessary to highlight the current item then.
2081 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2082 widget
->setCurrent(index
== selectionManager
->currentItem());
2084 widget
->setSelected(selectionManager
->isSelected(index
));
2085 widget
->setHovered(false);
2086 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2087 widget
->setIndex(index
);
2088 widget
->setData(m_model
->data(index
));
2089 widget
->setSiblingsInformation(QBitArray());
2090 updateAlternateBackgroundForWidget(widget
);
2093 updateGroupHeaderForWidget(widget
);
2097 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2099 Q_ASSERT(m_grouped
);
2101 const int index
= widget
->index();
2102 if (!m_layouter
->isFirstGroupItem(index
)) {
2103 // The widget does not represent the first item of a group
2104 // and hence requires no header
2105 recycleGroupHeaderForWidget(widget
);
2109 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2110 if (groups
.isEmpty() || !groupHeaderCreator()) {
2114 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2116 groupHeader
= groupHeaderCreator()->create(this);
2117 groupHeader
->setParentItem(widget
);
2118 m_visibleGroups
.insert(widget
, groupHeader
);
2119 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2121 Q_ASSERT(groupHeader
->parentItem() == widget
);
2123 const int groupIndex
= groupIndexForItem(index
);
2124 Q_ASSERT(groupIndex
>= 0);
2125 groupHeader
->setData(groups
.at(groupIndex
).second
);
2126 groupHeader
->setRole(model()->sortRole());
2127 groupHeader
->setStyleOption(m_styleOption
);
2128 groupHeader
->setScrollOrientation(scrollOrientation());
2129 groupHeader
->setItemIndex(index
);
2131 groupHeader
->show();
2134 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2136 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2137 Q_ASSERT(groupHeader
);
2139 const int index
= widget
->index();
2140 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2141 const QRectF itemRect
= m_layouter
->itemRect(index
);
2143 // The group-header is a child of the itemlist widget. Translate the
2144 // group header position to the relative position.
2145 if (scrollOrientation() == Qt::Vertical
) {
2146 // In the vertical scroll orientation the group header should always span
2147 // the whole width no matter which temporary position the parent widget
2148 // has. In this case the x-position and width will be adjusted manually.
2149 const qreal x
= -widget
->x() - itemOffset();
2150 const qreal width
= maximumItemOffset();
2151 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2152 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2154 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2155 groupHeader
->resize(groupHeaderRect
.size());
2159 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2161 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2163 header
->setParentItem(nullptr);
2164 groupHeaderCreator()->recycle(header
);
2165 m_visibleGroups
.remove(widget
);
2166 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2170 void KItemListView::updateVisibleGroupHeaders()
2172 Q_ASSERT(m_grouped
);
2173 m_layouter
->markAsDirty();
2175 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2176 while (it
.hasNext()) {
2178 updateGroupHeaderForWidget(it
.value());
2182 int KItemListView::groupIndexForItem(int index
) const
2184 Q_ASSERT(m_grouped
);
2186 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2187 if (groups
.isEmpty()) {
2192 int max
= groups
.count() - 1;
2195 mid
= (min
+ max
) / 2;
2196 if (index
> groups
[mid
].first
) {
2201 } while (groups
[mid
].first
!= index
&& min
<= max
);
2204 while (groups
[mid
].first
> index
&& mid
> 0) {
2212 void KItemListView::updateAlternateBackgrounds()
2214 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2215 while (it
.hasNext()) {
2217 updateAlternateBackgroundForWidget(it
.value());
2221 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2223 bool enabled
= useAlternateBackgrounds();
2225 const int index
= widget
->index();
2226 enabled
= (index
& 0x1) > 0;
2228 const int groupIndex
= groupIndexForItem(index
);
2229 if (groupIndex
>= 0) {
2230 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2231 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2232 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2233 enabled
= (relativeIndex
& 0x1) > 0;
2237 widget
->setAlternateBackground(enabled
);
2240 bool KItemListView::useAlternateBackgrounds() const
2242 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2245 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2247 QElapsedTimer timer
;
2250 QHash
<QByteArray
, qreal
> widths
;
2252 // Calculate the minimum width for each column that is required
2253 // to show the headline unclipped.
2254 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2255 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2256 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2257 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2258 const QString headerText
= m_model
->roleDescription(visibleRole
);
2259 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2260 widths
.insert(visibleRole
, headerWidth
);
2263 // Calculate the preferred column withs for each item and ignore values
2264 // smaller than the width for showing the headline unclipped.
2265 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2266 int calculatedItemCount
= 0;
2267 bool maxTimeExceeded
= false;
2268 for (const KItemRange
& itemRange
: itemRanges
) {
2269 const int startIndex
= itemRange
.index
;
2270 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2272 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2273 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2274 qreal maxWidth
= widths
.value(visibleRole
, 0);
2275 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2276 maxWidth
= qMax(width
, maxWidth
);
2277 widths
.insert(visibleRole
, maxWidth
);
2280 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2281 // When having several thousands of items calculating the sizes can get
2282 // very expensive. We accept a possibly too small role-size in favour
2283 // of having no blocking user interface.
2284 maxTimeExceeded
= true;
2287 ++calculatedItemCount
;
2289 if (maxTimeExceeded
) {
2297 void KItemListView::applyColumnWidthsFromHeader()
2299 // Apply the new size to the layouter
2300 const qreal requiredWidth
= columnWidthsSum();
2301 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2302 m_itemSize
.height());
2303 m_layouter
->setItemSize(dynamicItemSize
);
2305 // Update the role sizes for all visible widgets
2306 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2307 while (it
.hasNext()) {
2309 updateWidgetColumnWidths(it
.value());
2313 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2315 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2316 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2320 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2322 Q_ASSERT(m_itemSize
.isEmpty());
2323 const int itemCount
= m_model
->count();
2324 int rangesItemCount
= 0;
2325 for (const KItemRange
& range
: itemRanges
) {
2326 rangesItemCount
+= range
.count
;
2329 if (itemCount
== rangesItemCount
) {
2330 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2331 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2332 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2335 // Only a sub range of the roles need to be determined.
2336 // The chances are good that the widths of the sub ranges
2337 // already fit into the available widths and hence no
2338 // expensive update might be required.
2339 bool changed
= false;
2341 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2342 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2343 while (it
.hasNext()) {
2345 const QByteArray
& role
= it
.key();
2346 const qreal updatedWidth
= it
.value();
2347 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2348 if (updatedWidth
> currentWidth
) {
2349 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2355 // All the updated sizes are smaller than the current sizes and no change
2356 // of the stretched roles-widths is required
2361 if (m_headerWidget
->automaticColumnResizing()) {
2362 applyAutomaticColumnWidths();
2366 void KItemListView::updatePreferredColumnWidths()
2369 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2373 void KItemListView::applyAutomaticColumnWidths()
2375 Q_ASSERT(m_itemSize
.isEmpty());
2376 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2377 if (m_visibleRoles
.isEmpty()) {
2381 // Calculate the maximum size of an item by considering the
2382 // visible role sizes and apply them to the layouter. If the
2383 // size does not use the available view-size the size of the
2384 // first role will get stretched.
2386 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2387 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2388 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2391 const QByteArray firstRole
= m_visibleRoles
.first();
2392 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2393 QSizeF dynamicItemSize
= m_itemSize
;
2395 qreal requiredWidth
= columnWidthsSum();
2396 const qreal availableWidth
= size().width();
2397 if (requiredWidth
< availableWidth
) {
2398 // Stretch the first column to use the whole remaining width
2399 firstColumnWidth
+= availableWidth
- requiredWidth
;
2400 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2401 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2402 // Shrink the first column to be able to show as much other
2403 // columns as possible
2404 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2406 // TODO: A proper calculation of the minimum width depends on the implementation
2407 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2409 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2410 if (shrinkedFirstColumnWidth
< minWidth
) {
2411 shrinkedFirstColumnWidth
= minWidth
;
2414 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2415 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2418 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2420 m_layouter
->setItemSize(dynamicItemSize
);
2422 // Update the role sizes for all visible widgets
2423 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2424 while (it
.hasNext()) {
2426 updateWidgetColumnWidths(it
.value());
2430 qreal
KItemListView::columnWidthsSum() const
2432 qreal widthsSum
= 0;
2433 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2434 widthsSum
+= m_headerWidget
->columnWidth(role
);
2439 QRectF
KItemListView::headerBoundaries() const
2441 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2444 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2445 const QSizeF
& newItemSize
,
2446 const QSizeF
& newItemMargin
) const
2448 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2452 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2453 const qreal itemWidth
= m_layouter
->itemSize().width();
2454 if (itemWidth
> 0) {
2455 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2456 newItemSize
.width(),
2457 newItemMargin
.width());
2458 if (m_model
->count() > newColumnCount
) {
2459 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2461 m_layouter
->itemMargin().width());
2462 return oldColumnCount
!= newColumnCount
;
2466 const qreal itemHeight
= m_layouter
->itemSize().height();
2467 if (itemHeight
> 0) {
2468 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2469 newItemSize
.height(),
2470 newItemMargin
.height());
2471 if (m_model
->count() > newRowCount
) {
2472 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2474 m_layouter
->itemMargin().height());
2475 return oldRowCount
!= newRowCount
;
2483 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2485 if (m_itemSize
.isEmpty()) {
2486 // We have only columns or only rows, but no grid: An animation is usually
2487 // welcome when inserting or removing items.
2488 return !supportsItemExpanding();
2491 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2495 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2496 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2497 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2498 // Only animate if up to 2/3 of a row or column are inserted or removed
2499 return changedItemCount
<= maximum
* 2 / 3;
2503 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2505 const QSizeF oldSize
= m_layouter
->size();
2507 m_layouter
->setSize(size
);
2508 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2509 m_layouter
->setSize(oldSize
);
2511 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2512 : maxOffset
> size
.width();
2515 int KItemListView::showDropIndicator(const QPointF
& pos
)
2517 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2518 while (it
.hasNext()) {
2520 const KItemListWidget
* widget
= it
.value();
2522 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2523 const QRectF rect
= itemRect(widget
->index());
2524 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2525 if (m_model
->supportsDropping(widget
->index())) {
2526 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2527 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2528 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2533 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2534 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2536 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2537 if (m_dropIndicator
!= draggingInsertIndicator
) {
2538 m_dropIndicator
= draggingInsertIndicator
;
2542 int index
= widget
->index();
2550 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2551 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2554 void KItemListView::hideDropIndicator()
2556 if (!m_dropIndicator
.isNull()) {
2557 m_dropIndicator
= QRectF();
2562 void KItemListView::updateGroupHeaderHeight()
2564 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2565 qreal groupHeaderMargin
= 0;
2567 if (scrollOrientation() == Qt::Horizontal
) {
2568 // The vertical margin above and below the header should be
2569 // equal to the horizontal margin, not the vertical margin
2570 // from m_styleOption.
2571 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2572 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2573 } else if (m_itemSize
.isEmpty()){
2574 groupHeaderHeight
+= 2 * m_styleOption
.padding
;
2575 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2577 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2578 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2580 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2581 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2583 updateVisibleGroupHeaders();
2586 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2588 if (!supportsItemExpanding() || !m_model
) {
2592 if (firstIndex
< 0 || lastIndex
< 0) {
2593 firstIndex
= m_layouter
->firstVisibleIndex();
2594 lastIndex
= m_layouter
->lastVisibleIndex();
2596 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2597 lastIndex
>= m_layouter
->firstVisibleIndex());
2598 if (!isRangeVisible
) {
2603 int previousParents
= 0;
2604 QBitArray previousSiblings
;
2606 // The rootIndex describes the first index where the siblings get
2607 // calculated from. For the calculation the upper most parent item
2608 // is required. For performance reasons it is checked first whether
2609 // the visible items before or after the current range already
2610 // contain a siblings information which can be used as base.
2611 int rootIndex
= firstIndex
;
2613 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2615 // There is no visible widget before the range, check whether there
2616 // is one after the range:
2617 widget
= m_visibleItems
.value(lastIndex
+ 1);
2619 // The sibling information of the widget may only be used if
2620 // all items of the range have the same number of parents.
2621 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2622 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2623 if (m_model
->expandedParentsCount(i
) != parents
) {
2632 // Performance optimization: Use the sibling information of the visible
2633 // widget beside the given range.
2634 previousSiblings
= widget
->siblingsInformation();
2635 if (previousSiblings
.isEmpty()) {
2638 previousParents
= previousSiblings
.count() - 1;
2639 previousSiblings
.truncate(previousParents
);
2641 // Potentially slow path: Go back to the upper most parent of firstIndex
2642 // to be able to calculate the initial value for the siblings.
2643 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2648 Q_ASSERT(previousParents
>= 0);
2649 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2650 // Update the parent-siblings in case if the current item represents
2651 // a child or an upper parent.
2652 const int currentParents
= m_model
->expandedParentsCount(i
);
2653 Q_ASSERT(currentParents
>= 0);
2654 if (previousParents
< currentParents
) {
2655 previousParents
= currentParents
;
2656 previousSiblings
.resize(currentParents
);
2657 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2658 } else if (previousParents
> currentParents
) {
2659 previousParents
= currentParents
;
2660 previousSiblings
.truncate(currentParents
);
2663 if (i
>= firstIndex
) {
2664 // The index represents a visible item. Apply the parent-siblings
2665 // and update the sibling of the current item.
2666 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2671 QBitArray siblings
= previousSiblings
;
2672 siblings
.resize(siblings
.count() + 1);
2673 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2675 widget
->setSiblingsInformation(siblings
);
2680 bool KItemListView::hasSiblingSuccessor(int index
) const
2682 bool hasSuccessor
= false;
2683 const int parentsCount
= m_model
->expandedParentsCount(index
);
2684 int successorIndex
= index
+ 1;
2686 // Search the next sibling
2687 const int itemCount
= m_model
->count();
2688 while (successorIndex
< itemCount
) {
2689 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2690 if (currentParentsCount
== parentsCount
) {
2691 hasSuccessor
= true;
2693 } else if (currentParentsCount
< parentsCount
) {
2699 if (m_grouped
&& hasSuccessor
) {
2700 // If the sibling is part of another group, don't mark it as
2701 // successor as the group header is between the sibling connections.
2702 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2703 if (m_layouter
->isFirstGroupItem(i
)) {
2704 hasSuccessor
= false;
2710 return hasSuccessor
;
2713 void KItemListView::disconnectRoleEditingSignals(int index
)
2715 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2720 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2721 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2722 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2725 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2729 const int minSpeed
= 4;
2730 const int maxSpeed
= 128;
2731 const int speedLimiter
= 96;
2732 const int autoScrollBorder
= 64;
2734 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2735 // This assures that the autoscrolling speed grows gradually.
2736 const int incLimiter
= 1;
2738 if (pos
< autoScrollBorder
) {
2739 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2740 inc
= qMax(inc
, -maxSpeed
);
2741 inc
= qMax(inc
, oldInc
- incLimiter
);
2742 } else if (pos
> range
- autoScrollBorder
) {
2743 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2744 inc
= qMin(inc
, maxSpeed
);
2745 inc
= qMin(inc
, oldInc
+ incLimiter
);
2751 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2753 const qreal availableSize
= size
- itemMargin
;
2754 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2760 KItemListCreatorBase::~KItemListCreatorBase()
2762 qDeleteAll(m_recycleableWidgets
);
2763 qDeleteAll(m_createdWidgets
);
2766 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2768 m_createdWidgets
.insert(widget
);
2771 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2773 Q_ASSERT(m_createdWidgets
.contains(widget
));
2774 m_createdWidgets
.remove(widget
);
2776 if (m_recycleableWidgets
.count() < 100) {
2777 m_recycleableWidgets
.append(widget
);
2778 widget
->setVisible(false);
2784 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2786 if (m_recycleableWidgets
.isEmpty()) {
2790 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2791 m_createdWidgets
.insert(widget
);
2795 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2799 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2801 widget
->setParentItem(nullptr);
2802 widget
->setOpacity(1.0);
2803 pushRecycleableWidget(widget
);
2806 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2810 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2812 header
->setOpacity(1.0);
2813 pushRecycleableWidget(header
);