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_highlightEntireRow(false),
67 m_alternateBackgrounds(false),
68 m_supportsItemExpanding(false),
70 m_activeTransactions(0),
71 m_endTransactionAnimationHint(Animation
),
73 m_controller(nullptr),
76 m_widgetCreator(nullptr),
77 m_groupHeaderCreator(nullptr),
86 m_oldMaximumScrollOffset(0),
88 m_oldMaximumItemOffset(0),
89 m_skipAutoScrollForRubberBand(false),
90 m_rubberBand(nullptr),
91 m_tapAndHoldIndicator(nullptr),
93 m_autoScrollIncrement(0),
94 m_autoScrollTimer(nullptr),
96 m_headerWidget(nullptr),
97 m_indicatorAnimation(nullptr),
99 m_sizeHintResolver(nullptr)
101 setAcceptHoverEvents(true);
102 setAcceptTouchEvents(true);
104 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
106 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
108 m_animation
= new KItemListViewAnimation(this);
109 connect(m_animation
, &KItemListViewAnimation::finished
,
110 this, &KItemListView::slotAnimationFinished
);
112 m_rubberBand
= new KItemListRubberBand(this);
113 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
115 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
116 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
117 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
119 m_indicatorAnimation
->setDuration(150);
120 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
121 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
122 m_indicatorAnimation
->start();
126 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
127 if (m_tapAndHoldIndicator
->isActive()) {
132 m_headerWidget
= new KItemListHeaderWidget(this);
133 m_headerWidget
->setVisible(false);
135 m_header
= new KItemListHeader(this);
137 #ifndef QT_NO_ACCESSIBILITY
138 QAccessible::installFactory(accessibleInterfaceFactory
);
143 KItemListView::~KItemListView()
145 // The group headers are children of the widgets created by
146 // widgetCreator(). So it is mandatory to delete the group headers
148 delete m_groupHeaderCreator
;
149 m_groupHeaderCreator
= nullptr;
151 delete m_widgetCreator
;
152 m_widgetCreator
= nullptr;
154 delete m_sizeHintResolver
;
155 m_sizeHintResolver
= nullptr;
158 void KItemListView::setScrollOffset(qreal offset
)
164 const qreal previousOffset
= m_layouter
->scrollOffset();
165 if (offset
== previousOffset
) {
169 m_layouter
->setScrollOffset(offset
);
170 m_animation
->setScrollOffset(offset
);
172 // Don't check whether the m_layoutTimer is active: Changing the
173 // scroll offset must always trigger a synchronous layout, otherwise
174 // the smooth-scrolling might get jerky.
175 doLayout(NoAnimation
);
176 onScrollOffsetChanged(offset
, previousOffset
);
179 qreal
KItemListView::scrollOffset() const
181 return m_layouter
->scrollOffset();
184 qreal
KItemListView::maximumScrollOffset() const
186 return m_layouter
->maximumScrollOffset();
189 void KItemListView::setItemOffset(qreal offset
)
191 if (m_layouter
->itemOffset() == offset
) {
195 m_layouter
->setItemOffset(offset
);
196 if (m_headerWidget
->isVisible()) {
197 m_headerWidget
->setOffset(offset
);
200 // Don't check whether the m_layoutTimer is active: Changing the
201 // item offset must always trigger a synchronous layout, otherwise
202 // the smooth-scrolling might get jerky.
203 doLayout(NoAnimation
);
206 qreal
KItemListView::itemOffset() const
208 return m_layouter
->itemOffset();
211 qreal
KItemListView::maximumItemOffset() const
213 return m_layouter
->maximumItemOffset();
216 int KItemListView::maximumVisibleItems() const
218 return m_layouter
->maximumVisibleItems();
221 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
223 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
224 m_visibleRoles
= roles
;
225 onVisibleRolesChanged(roles
, previousRoles
);
227 m_sizeHintResolver
->clearCache();
228 m_layouter
->markAsDirty();
230 if (m_itemSize
.isEmpty()) {
231 m_headerWidget
->setColumns(roles
);
232 updatePreferredColumnWidths();
233 if (!m_headerWidget
->automaticColumnResizing()) {
234 // The column-width of new roles are still 0. Apply the preferred
235 // column-width as default with.
236 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
237 if (m_headerWidget
->columnWidth(role
) == 0) {
238 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
239 m_headerWidget
->setColumnWidth(role
, width
);
243 applyColumnWidthsFromHeader();
247 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
248 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
249 (roles
.count() <= 1 && previousRoles
.count() > 1));
251 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
252 while (it
.hasNext()) {
254 KItemListWidget
* widget
= it
.value();
255 widget
->setVisibleRoles(roles
);
256 if (alternateBackgroundsChanged
) {
257 updateAlternateBackgroundForWidget(widget
);
261 doLayout(NoAnimation
);
264 QList
<QByteArray
> KItemListView::visibleRoles() const
266 return m_visibleRoles
;
269 void KItemListView::setAutoScroll(bool enabled
)
271 if (enabled
&& !m_autoScrollTimer
) {
272 m_autoScrollTimer
= new QTimer(this);
273 m_autoScrollTimer
->setSingleShot(true);
274 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
275 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
276 } else if (!enabled
&& m_autoScrollTimer
) {
277 delete m_autoScrollTimer
;
278 m_autoScrollTimer
= nullptr;
282 bool KItemListView::autoScroll() const
284 return m_autoScrollTimer
!= nullptr;
287 void KItemListView::setEnabledSelectionToggles(bool enabled
)
289 if (m_enabledSelectionToggles
!= enabled
) {
290 m_enabledSelectionToggles
= enabled
;
292 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
293 while (it
.hasNext()) {
295 it
.value()->setEnabledSelectionToggle(enabled
);
300 bool KItemListView::enabledSelectionToggles() const
302 return m_enabledSelectionToggles
;
305 KItemListController
* KItemListView::controller() const
310 KItemModelBase
* KItemListView::model() const
315 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
317 delete m_widgetCreator
;
318 m_widgetCreator
= widgetCreator
;
321 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
323 if (!m_widgetCreator
) {
324 m_widgetCreator
= defaultWidgetCreator();
326 return m_widgetCreator
;
329 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
331 delete m_groupHeaderCreator
;
332 m_groupHeaderCreator
= groupHeaderCreator
;
335 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
337 if (!m_groupHeaderCreator
) {
338 m_groupHeaderCreator
= defaultGroupHeaderCreator();
340 return m_groupHeaderCreator
;
343 QSizeF
KItemListView::itemSize() const
348 const KItemListStyleOption
& KItemListView::styleOption() const
350 return m_styleOption
;
353 void KItemListView::setGeometry(const QRectF
& rect
)
355 QGraphicsWidget::setGeometry(rect
);
361 const QSizeF newSize
= rect
.size();
362 if (m_itemSize
.isEmpty()) {
363 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
364 if (m_headerWidget
->automaticColumnResizing()) {
365 applyAutomaticColumnWidths();
367 const qreal requiredWidth
= columnWidthsSum();
368 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
369 m_itemSize
.height());
370 m_layouter
->setItemSize(dynamicItemSize
);
374 m_layouter
->setSize(newSize
);
375 // We don't animate the moving of the items here because
376 // it would look like the items are slow to find their position.
377 doLayout(NoAnimation
);
380 qreal
KItemListView::verticalPageStep() const
382 qreal headerHeight
= 0;
383 if (m_headerWidget
->isVisible()) {
384 headerHeight
= m_headerWidget
->size().height();
386 return size().height() - headerHeight
;
389 std::optional
<int> KItemListView::itemAt(const QPointF
& pos
) const
391 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
392 while (it
.hasNext()) {
395 const KItemListWidget
* widget
= it
.value();
396 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
397 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
405 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
407 if (!m_enabledSelectionToggles
) {
411 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
413 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
414 if (!selectionToggleRect
.isEmpty()) {
415 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
416 return selectionToggleRect
.contains(mappedPos
);
422 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
424 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
426 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
427 if (!expansionToggleRect
.isEmpty()) {
428 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
429 return expansionToggleRect
.contains(mappedPos
);
435 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
437 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
439 const QRectF
&textRect
= widget
->textRect();
440 if (!textRect
.isEmpty()) {
441 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
442 return textRect
.contains(mappedPos
);
448 int KItemListView::firstVisibleIndex() const
450 return m_layouter
->firstVisibleIndex();
453 int KItemListView::lastVisibleIndex() const
455 return m_layouter
->lastVisibleIndex();
458 void KItemListView::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
) const
460 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
463 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
465 if (m_supportsItemExpanding
!= supportsExpanding
) {
466 m_supportsItemExpanding
= supportsExpanding
;
467 updateSiblingsInformation();
468 onSupportsItemExpandingChanged(supportsExpanding
);
472 bool KItemListView::supportsItemExpanding() const
474 return m_supportsItemExpanding
;
477 void KItemListView::setHighlightEntireRow(bool highlightEntireRow
)
479 if (m_highlightEntireRow
!= highlightEntireRow
) {
480 m_highlightEntireRow
= highlightEntireRow
;
481 onHighlightEntireRowChanged(highlightEntireRow
);
485 bool KItemListView::highlightEntireRow() const
487 return m_highlightEntireRow
;
490 void KItemListView::setAlternateBackgrounds(bool alternate
)
492 if (m_alternateBackgrounds
!= alternate
) {
493 m_alternateBackgrounds
= alternate
;
494 updateAlternateBackgrounds();
498 bool KItemListView::alternateBackgrounds() const
500 return m_alternateBackgrounds
;
503 QRectF
KItemListView::itemRect(int index
) const
505 return m_layouter
->itemRect(index
);
508 QRectF
KItemListView::itemContextRect(int index
) const
512 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
514 contextRect
= widget
->iconRect() | widget
->textRect();
515 contextRect
.translate(itemRect(index
).topLeft());
521 bool KItemListView::isElided(int index
) const
523 return m_sizeHintResolver
->isElided(index
);
526 void KItemListView::scrollToItem(int index
)
528 QRectF viewGeometry
= geometry();
529 if (m_headerWidget
->isVisible()) {
530 const qreal headerHeight
= m_headerWidget
->size().height();
531 viewGeometry
.adjust(0, headerHeight
, 0, 0);
533 QRectF currentRect
= itemRect(index
);
535 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
536 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
537 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
539 if (!viewGeometry
.contains(currentRect
)) {
540 qreal newOffset
= scrollOffset();
541 if (scrollOrientation() == Qt::Vertical
) {
542 if (currentRect
.top() < viewGeometry
.top()) {
543 newOffset
+= currentRect
.top() - viewGeometry
.top();
544 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
545 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
548 if (currentRect
.left() < viewGeometry
.left()) {
549 newOffset
+= currentRect
.left() - viewGeometry
.left();
550 } else if (currentRect
.right() > viewGeometry
.right()) {
551 newOffset
+= currentRect
.right() - viewGeometry
.right();
555 if (newOffset
!= scrollOffset()) {
556 Q_EMIT
scrollTo(newOffset
);
561 Q_EMIT
scrollingStopped();
564 void KItemListView::beginTransaction()
566 ++m_activeTransactions
;
567 if (m_activeTransactions
== 1) {
568 onTransactionBegin();
572 void KItemListView::endTransaction()
574 --m_activeTransactions
;
575 if (m_activeTransactions
< 0) {
576 m_activeTransactions
= 0;
577 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
580 if (m_activeTransactions
== 0) {
582 doLayout(m_endTransactionAnimationHint
);
583 m_endTransactionAnimationHint
= Animation
;
587 bool KItemListView::isTransactionActive() const
589 return m_activeTransactions
> 0;
592 void KItemListView::setHeaderVisible(bool visible
)
594 if (visible
&& !m_headerWidget
->isVisible()) {
595 QStyleOptionHeader option
;
596 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
599 m_headerWidget
->setPos(0, 0);
600 m_headerWidget
->resize(size().width(), headerSize
.height());
601 m_headerWidget
->setModel(m_model
);
602 m_headerWidget
->setColumns(m_visibleRoles
);
603 m_headerWidget
->setZValue(1);
605 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
606 this, &KItemListView::slotHeaderColumnWidthChanged
);
607 connect(m_headerWidget
, &KItemListHeaderWidget::sidePaddingChanged
,
608 this, &KItemListView::slotSidePaddingChanged
);
609 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
610 this, &KItemListView::slotHeaderColumnMoved
);
611 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
612 this, &KItemListView::sortOrderChanged
);
613 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
614 this, &KItemListView::sortRoleChanged
);
616 m_layouter
->setHeaderHeight(headerSize
.height());
617 m_headerWidget
->setVisible(true);
618 } else if (!visible
&& m_headerWidget
->isVisible()) {
619 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
620 this, &KItemListView::slotHeaderColumnWidthChanged
);
621 disconnect(m_headerWidget
, &KItemListHeaderWidget::sidePaddingChanged
,
622 this, &KItemListView::slotSidePaddingChanged
);
623 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
624 this, &KItemListView::slotHeaderColumnMoved
);
625 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
626 this, &KItemListView::sortOrderChanged
);
627 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
628 this, &KItemListView::sortRoleChanged
);
630 m_layouter
->setHeaderHeight(0);
631 m_headerWidget
->setVisible(false);
635 bool KItemListView::isHeaderVisible() const
637 return m_headerWidget
->isVisible();
640 KItemListHeader
* KItemListView::header() const
645 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
649 if (indexes
.count() == 1) {
650 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
651 QGraphicsView
* graphicsView
= scene()->views()[0];
652 if (item
&& graphicsView
) {
653 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
656 // TODO: Not implemented yet. Probably extend the interface
657 // from KItemListWidget::createDragPixmap() to return a pixmap
658 // that can be used for multiple indexes.
664 void KItemListView::editRole(int index
, const QByteArray
& role
)
666 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
667 if (!widget
|| m_editingRole
) {
671 m_editingRole
= true;
672 widget
->setEditedRole(role
);
674 connect(widget
, &KItemListWidget::roleEditingCanceled
,
675 this, &KItemListView::slotRoleEditingCanceled
);
676 connect(widget
, &KItemListWidget::roleEditingFinished
,
677 this, &KItemListView::slotRoleEditingFinished
);
679 connect(this, &KItemListView::scrollOffsetChanged
,
680 widget
, &KStandardItemListWidget::finishRoleEditing
);
683 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
685 QGraphicsWidget::paint(painter
, option
, widget
);
687 for (auto animation
: qAsConst(m_rubberBandAnimations
)) {
688 QRectF rubberBandRect
= animation
->property(RubberPropertyName
).toRectF();
690 const QPointF topLeft
= rubberBandRect
.topLeft();
691 if (scrollOrientation() == Qt::Vertical
) {
692 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
694 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
697 QStyleOptionRubberBand opt
;
698 initStyleOption(&opt
);
699 opt
.shape
= QRubberBand::Rectangle
;
701 opt
.rect
= rubberBandRect
.toRect();
705 painter
->setOpacity(animation
->currentValue().toReal());
706 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
711 if (m_rubberBand
->isActive()) {
712 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
713 m_rubberBand
->endPosition()).normalized();
715 const QPointF topLeft
= rubberBandRect
.topLeft();
716 if (scrollOrientation() == Qt::Vertical
) {
717 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
719 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
722 QStyleOptionRubberBand opt
;
723 initStyleOption(&opt
);
724 opt
.shape
= QRubberBand::Rectangle
;
726 opt
.rect
= rubberBandRect
.toRect();
727 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
730 if (m_tapAndHoldIndicator
->isActive()) {
731 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
732 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
733 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
734 QStyleOptionRubberBand opt
;
735 initStyleOption(&opt
);
736 opt
.shape
= QRubberBand::Rectangle
;
738 opt
.rect
= rubberBandRect
.toRect();
739 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
742 if (!m_dropIndicator
.isEmpty()) {
743 const QRectF r
= m_dropIndicator
.toRect();
745 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
746 painter
->setPen(color
);
748 // TODO: The following implementation works only for a vertical scroll-orientation
749 // and assumes a height of the m_draggingInsertIndicator of 1.
750 Q_ASSERT(r
.height() == 1);
751 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
754 painter
->setPen(color
);
755 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
759 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
761 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
762 if (!scene()->views().isEmpty()) {
763 m_styleOption
.palette
= scene()->views().at(0)->palette();
766 return QGraphicsItem::itemChange(change
, value
);
769 void KItemListView::setItemSize(const QSizeF
& size
)
771 const QSizeF previousSize
= m_itemSize
;
772 if (size
== previousSize
) {
776 // Skip animations when the number of rows or columns
777 // are changed in the grid layout. Although the animation
778 // engine can handle this usecase, it looks obtrusive.
779 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
781 m_layouter
->itemMargin());
783 const bool alternateBackgroundsChanged
= m_alternateBackgrounds
&&
784 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
785 (!m_itemSize
.isEmpty() && size
.isEmpty()));
789 if (alternateBackgroundsChanged
) {
790 // For an empty item size alternate backgrounds are drawn if more than
791 // one role is shown. Assure that the backgrounds for visible items are
792 // updated when changing the size in this context.
793 updateAlternateBackgrounds();
796 if (size
.isEmpty()) {
797 if (m_headerWidget
->automaticColumnResizing()) {
798 updatePreferredColumnWidths();
800 // Only apply the changed height and respect the header widths
802 const qreal currentWidth
= m_layouter
->itemSize().width();
803 const QSizeF
newSize(currentWidth
, size
.height());
804 m_layouter
->setItemSize(newSize
);
807 m_layouter
->setItemSize(size
);
810 m_sizeHintResolver
->clearCache();
811 doLayout(animate
? Animation
: NoAnimation
);
812 onItemSizeChanged(size
, previousSize
);
815 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
817 if (m_styleOption
== option
) {
821 const KItemListStyleOption previousOption
= m_styleOption
;
822 m_styleOption
= option
;
825 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
826 if (margin
!= m_layouter
->itemMargin()) {
827 // Skip animations when the number of rows or columns
828 // are changed in the grid layout. Although the animation
829 // engine can handle this usecase, it looks obtrusive.
830 animate
= !changesItemGridLayout(m_layouter
->size(),
831 m_layouter
->itemSize(),
833 m_layouter
->setItemMargin(margin
);
837 updateGroupHeaderHeight();
841 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
842 // Animating a change of the maximum text size just results in expensive
843 // temporary eliding and clipping operations and does not look good visually.
847 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
848 while (it
.hasNext()) {
850 it
.value()->setStyleOption(option
);
853 m_sizeHintResolver
->clearCache();
854 m_layouter
->markAsDirty();
855 doLayout(animate
? Animation
: NoAnimation
);
857 if (m_itemSize
.isEmpty()) {
858 updatePreferredColumnWidths();
861 onStyleOptionChanged(option
, previousOption
);
864 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
866 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
867 if (orientation
== previousOrientation
) {
871 m_layouter
->setScrollOrientation(orientation
);
872 m_animation
->setScrollOrientation(orientation
);
873 m_sizeHintResolver
->clearCache();
876 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
877 while (it
.hasNext()) {
879 it
.value()->setScrollOrientation(orientation
);
881 updateGroupHeaderHeight();
885 doLayout(NoAnimation
);
887 onScrollOrientationChanged(orientation
, previousOrientation
);
888 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
891 Qt::Orientation
KItemListView::scrollOrientation() const
893 return m_layouter
->scrollOrientation();
896 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
901 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
906 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
911 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
913 Q_UNUSED(changedRoles
)
917 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
923 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
929 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
935 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
941 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
947 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
953 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
959 void KItemListView::onHighlightEntireRowChanged(bool highlightEntireRow
)
961 Q_UNUSED(highlightEntireRow
)
964 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
966 Q_UNUSED(supportsExpanding
)
969 void KItemListView::onTransactionBegin()
973 void KItemListView::onTransactionEnd()
977 bool KItemListView::event(QEvent
* event
)
979 switch (event
->type()) {
980 case QEvent::PaletteChange
:
984 case QEvent::FontChange
:
989 // Forward all other events to the controller and handle them there
990 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
996 return QGraphicsWidget::event(event
);
999 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
1001 m_mousePos
= transform().map(event
->pos());
1005 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
1007 QGraphicsWidget::mouseMoveEvent(event
);
1009 m_mousePos
= transform().map(event
->pos());
1010 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1011 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1015 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
1017 event
->setAccepted(true);
1018 setAutoScroll(true);
1021 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
1023 QGraphicsWidget::dragMoveEvent(event
);
1025 m_mousePos
= transform().map(event
->pos());
1026 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1027 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1031 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
1033 QGraphicsWidget::dragLeaveEvent(event
);
1034 setAutoScroll(false);
1037 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
1039 QGraphicsWidget::dropEvent(event
);
1040 setAutoScroll(false);
1043 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
1045 return m_visibleItems
.values();
1048 void KItemListView::updateFont()
1050 if (scene() && !scene()->views().isEmpty()) {
1051 KItemListStyleOption option
= styleOption();
1052 option
.font
= scene()->views().first()->font();
1053 option
.fontMetrics
= QFontMetrics(option
.font
);
1055 setStyleOption(option
);
1059 void KItemListView::updatePalette()
1061 if (scene() && !scene()->views().isEmpty()) {
1062 KItemListStyleOption option
= styleOption();
1063 option
.palette
= scene()->views().first()->palette();
1065 setStyleOption(option
);
1069 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1071 if (m_itemSize
.isEmpty()) {
1072 updatePreferredColumnWidths(itemRanges
);
1075 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1076 if (hasMultipleRanges
) {
1080 m_layouter
->markAsDirty();
1082 m_sizeHintResolver
->itemsInserted(itemRanges
);
1084 int previouslyInsertedCount
= 0;
1085 for (const KItemRange
& range
: itemRanges
) {
1086 // range.index is related to the model before anything has been inserted.
1087 // As in each loop the current item-range gets inserted the index must
1088 // be increased by the already previously inserted items.
1089 const int index
= range
.index
+ previouslyInsertedCount
;
1090 const int count
= range
.count
;
1091 if (index
< 0 || count
<= 0) {
1092 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1095 previouslyInsertedCount
+= count
;
1097 // Determine which visible items must be moved
1098 QList
<int> itemsToMove
;
1099 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1100 while (it
.hasNext()) {
1102 const int visibleItemIndex
= it
.key();
1103 if (visibleItemIndex
>= index
) {
1104 itemsToMove
.append(visibleItemIndex
);
1108 // Update the indexes of all KItemListWidget instances that are located
1109 // after the inserted items. It is important to adjust the indexes in the order
1110 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1111 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1112 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1113 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1115 const int newIndex
= widget
->index() + count
;
1116 if (hasMultipleRanges
) {
1117 setWidgetIndex(widget
, newIndex
);
1119 // Try to animate the moving of the item
1120 moveWidgetToIndex(widget
, newIndex
);
1124 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1125 // Check whether a scrollbar is required to show the inserted items. In this case
1126 // the size of the layouter will be decreased before calling doLayout(): This prevents
1127 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1128 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1129 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1130 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1131 if (decreaseLayouterSize
) {
1132 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1134 int scrollbarSpacing
= 0;
1135 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1136 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1139 QSizeF layouterSize
= m_layouter
->size();
1140 if (verticalScrollOrientation
) {
1141 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1143 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1145 m_layouter
->setSize(layouterSize
);
1149 if (!hasMultipleRanges
) {
1150 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1151 updateSiblingsInformation();
1156 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1159 if (hasMultipleRanges
) {
1160 m_endTransactionAnimationHint
= NoAnimation
;
1163 updateSiblingsInformation();
1166 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1167 // In case if items of the same group have been inserted before an item that
1168 // currently represents the first item of the group, the group header of
1169 // this item must be removed.
1170 updateVisibleGroupHeaders();
1173 if (useAlternateBackgrounds()) {
1174 updateAlternateBackgrounds();
1178 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1180 if (m_itemSize
.isEmpty()) {
1181 // Don't pass the item-range: The preferred column-widths of
1182 // all items must be adjusted when removing items.
1183 updatePreferredColumnWidths();
1186 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1187 if (hasMultipleRanges
) {
1191 m_layouter
->markAsDirty();
1193 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1195 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1196 const KItemRange
& range
= itemRanges
[i
];
1197 const int index
= range
.index
;
1198 const int count
= range
.count
;
1199 if (index
< 0 || count
<= 0) {
1200 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1204 const int firstRemovedIndex
= index
;
1205 const int lastRemovedIndex
= index
+ count
- 1;
1207 // Remember which items have to be moved because they are behind the removed range.
1208 QVector
<int> itemsToMove
;
1210 // Remove all KItemListWidget instances that got deleted
1211 // Iterate over a const copy because the container is mutated within the loop
1212 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1213 const auto visibleItems
= m_visibleItems
;
1214 for (KItemListWidget
* widget
: visibleItems
) {
1215 const int i
= widget
->index();
1216 if (i
< firstRemovedIndex
) {
1218 } else if (i
> lastRemovedIndex
) {
1219 itemsToMove
.append(i
);
1223 m_animation
->stop(widget
);
1224 // Stopping the animation might lead to recycling the widget if
1225 // it is invisible (see slotAnimationFinished()).
1226 // Check again whether it is still visible:
1227 if (!m_visibleItems
.contains(i
)) {
1231 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1232 // Remove the widget without animation
1233 recycleWidget(widget
);
1235 // Animate the removing of the items. Special case: When removing an item there
1236 // is no valid model index available anymore. For the
1237 // remove-animation the item gets removed from m_visibleItems but the widget
1238 // will stay alive until the animation has been finished and will
1239 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1240 m_visibleItems
.remove(i
);
1241 widget
->setIndex(-1);
1242 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1246 // Update the indexes of all KItemListWidget instances that are located
1247 // after the deleted items. It is important to update them in ascending
1248 // order to prevent overlaps when setting the new index.
1249 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1250 for (int i
: qAsConst(itemsToMove
)) {
1251 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1253 const int newIndex
= i
- count
;
1254 if (hasMultipleRanges
) {
1255 setWidgetIndex(widget
, newIndex
);
1257 // Try to animate the moving of the item
1258 moveWidgetToIndex(widget
, newIndex
);
1262 if (!hasMultipleRanges
) {
1263 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1264 // assumes an updated geometry. If items are removed during an active transaction,
1265 // the transaction will be temporary deactivated so that doLayout() triggers a
1266 // geometry update if necessary.
1267 const int activeTransactions
= m_activeTransactions
;
1268 m_activeTransactions
= 0;
1269 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1270 m_activeTransactions
= activeTransactions
;
1271 updateSiblingsInformation();
1276 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1279 if (hasMultipleRanges
) {
1280 m_endTransactionAnimationHint
= NoAnimation
;
1282 updateSiblingsInformation();
1285 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1286 // In case if the first item of a group has been removed, the group header
1287 // must be applied to the next visible item.
1288 updateVisibleGroupHeaders();
1291 if (useAlternateBackgrounds()) {
1292 updateAlternateBackgrounds();
1296 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1298 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1299 m_layouter
->markAsDirty();
1302 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1305 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1306 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1308 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1309 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1311 updateWidgetProperties(widget
, index
);
1312 initializeItemListWidget(widget
);
1316 doLayout(NoAnimation
);
1317 updateSiblingsInformation();
1320 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1321 const QSet
<QByteArray
>& roles
)
1323 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1324 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1325 updatePreferredColumnWidths(itemRanges
);
1328 for (const KItemRange
& itemRange
: itemRanges
) {
1329 const int index
= itemRange
.index
;
1330 const int count
= itemRange
.count
;
1332 if (updateSizeHints
) {
1333 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1334 m_layouter
->markAsDirty();
1337 // Apply the changed roles to the visible item-widgets
1338 const int lastIndex
= index
+ count
- 1;
1339 for (int i
= index
; i
<= lastIndex
; ++i
) {
1340 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1342 widget
->setData(m_model
->data(i
), roles
);
1346 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1347 // The sort-role has been changed which might result
1348 // in modified group headers
1349 updateVisibleGroupHeaders();
1350 doLayout(NoAnimation
);
1353 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1354 ev
.setFirstRow(itemRange
.index
);
1355 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1356 QAccessible::updateAccessibility(&ev
);
1359 doLayout(NoAnimation
);
1362 void KItemListView::slotGroupsChanged()
1364 updateVisibleGroupHeaders();
1365 doLayout(NoAnimation
);
1366 updateSiblingsInformation();
1369 void KItemListView::slotGroupedSortingChanged(bool current
)
1371 m_grouped
= current
;
1372 m_layouter
->markAsDirty();
1375 updateGroupHeaderHeight();
1377 // Clear all visible headers. Note that the QHashIterator takes a copy of
1378 // m_visibleGroups. Therefore, it remains valid even if items are removed
1379 // from m_visibleGroups in recycleGroupHeaderForWidget().
1380 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1381 while (it
.hasNext()) {
1383 recycleGroupHeaderForWidget(it
.key());
1385 Q_ASSERT(m_visibleGroups
.isEmpty());
1388 if (useAlternateBackgrounds()) {
1389 // Changing the group mode requires to update the alternate backgrounds
1390 // as with the enabled group mode the altering is done on base of the first
1392 updateAlternateBackgrounds();
1394 updateSiblingsInformation();
1395 doLayout(NoAnimation
);
1398 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1403 updateVisibleGroupHeaders();
1404 doLayout(NoAnimation
);
1408 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1413 updateVisibleGroupHeaders();
1414 doLayout(NoAnimation
);
1418 void KItemListView::slotCurrentChanged(int current
, int previous
)
1422 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1423 // always the selected item. It is not necessary to highlight the current item then.
1424 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1425 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1426 if (previousWidget
) {
1427 previousWidget
->setCurrent(false);
1430 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1431 if (currentWidget
) {
1432 currentWidget
->setCurrent(true);
1436 QAccessibleEvent
ev(this, QAccessible::Focus
);
1437 ev
.setChild(current
);
1438 QAccessible::updateAccessibility(&ev
);
1441 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1445 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1446 while (it
.hasNext()) {
1448 const int index
= it
.key();
1449 KItemListWidget
* widget
= it
.value();
1450 widget
->setSelected(current
.contains(index
));
1454 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1455 KItemListViewAnimation::AnimationType type
)
1457 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1458 Q_ASSERT(itemListWidget
);
1460 if (type
== KItemListViewAnimation::DeleteAnimation
) {
1461 // As we recycle the widget in this case it is important to assure that no
1462 // other animation has been started. This is a convention in KItemListView and
1463 // not a requirement defined by KItemListViewAnimation.
1464 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1466 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1467 // by m_visibleWidgets and must be deleted manually after the animation has
1469 recycleGroupHeaderForWidget(itemListWidget
);
1470 widgetCreator()->recycle(itemListWidget
);
1472 const int index
= itemListWidget
->index();
1473 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1474 (index
> m_layouter
->lastVisibleIndex());
1475 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1476 recycleWidget(itemListWidget
);
1481 void KItemListView::slotRubberBandPosChanged()
1486 void KItemListView::slotRubberBandActivationChanged(bool active
)
1489 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1490 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1491 m_skipAutoScrollForRubberBand
= true;
1493 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
1494 m_rubberBand
->endPosition()).normalized();
1496 auto animation
= new QVariantAnimation(this);
1497 animation
->setStartValue(1.0);
1498 animation
->setEndValue(0.0);
1499 animation
->setDuration(RubberFadeSpeed
);
1500 animation
->setProperty(RubberPropertyName
, rubberBandRect
);
1503 curve
.setType(QEasingCurve::BezierSpline
);
1504 curve
.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1505 animation
->setEasingCurve(curve
);
1507 connect(animation
, &QVariantAnimation::valueChanged
, this, [=](const QVariant
&) {
1510 connect(animation
, &QVariantAnimation::finished
, this, [=]() {
1511 m_rubberBandAnimations
.removeAll(animation
);
1515 m_rubberBandAnimations
<< animation
;
1517 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1518 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1519 m_skipAutoScrollForRubberBand
= false;
1525 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1527 qreal previousWidth
)
1530 Q_UNUSED(currentWidth
)
1531 Q_UNUSED(previousWidth
)
1533 m_headerWidget
->setAutomaticColumnResizing(false);
1534 applyColumnWidthsFromHeader();
1535 doLayout(NoAnimation
);
1538 void KItemListView::slotSidePaddingChanged(qreal width
)
1541 if (m_headerWidget
->automaticColumnResizing()) {
1542 applyAutomaticColumnWidths();
1544 applyColumnWidthsFromHeader();
1545 doLayout(NoAnimation
);
1548 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1552 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1554 const QList
<QByteArray
> previous
= m_visibleRoles
;
1556 QList
<QByteArray
> current
= m_visibleRoles
;
1557 current
.removeAt(previousIndex
);
1558 current
.insert(currentIndex
, role
);
1560 setVisibleRoles(current
);
1562 Q_EMIT
visibleRolesChanged(current
, previous
);
1565 void KItemListView::triggerAutoScrolling()
1567 if (!m_autoScrollTimer
) {
1572 int visibleSize
= 0;
1573 if (scrollOrientation() == Qt::Vertical
) {
1574 pos
= m_mousePos
.y();
1575 visibleSize
= size().height();
1577 pos
= m_mousePos
.x();
1578 visibleSize
= size().width();
1581 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1582 m_autoScrollIncrement
= 0;
1585 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1586 if (m_autoScrollIncrement
== 0) {
1587 // The mouse position is not above an autoscroll margin (the autoscroll timer
1588 // will be restarted in mouseMoveEvent())
1589 m_autoScrollTimer
->stop();
1593 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1594 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1595 // if the direction of the rubberband is similar to the autoscroll direction. This
1596 // prevents that starting to create a rubberband within the autoscroll margins starts
1597 // an autoscrolling.
1599 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1600 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1601 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1602 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1603 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1604 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1605 // been moved up although the autoscroll direction might be down)
1606 m_autoScrollTimer
->stop();
1611 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1612 // the autoscrolling may not get skipped anymore until a new rubberband is created
1613 m_skipAutoScrollForRubberBand
= false;
1615 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1616 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1617 setScrollOffset(newScrollOffset
);
1619 // Trigger the autoscroll timer which will periodically call
1620 // triggerAutoScrolling()
1621 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1624 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1626 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1628 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1629 Q_ASSERT(groupHeader
);
1630 updateGroupHeaderLayout(widget
);
1633 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1635 disconnectRoleEditingSignals(index
);
1637 m_editingRole
= false;
1638 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1641 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1643 disconnectRoleEditingSignals(index
);
1645 m_editingRole
= false;
1646 Q_EMIT
roleEditingFinished(index
, role
, value
);
1649 void KItemListView::setController(KItemListController
* controller
)
1651 if (m_controller
!= controller
) {
1652 KItemListController
* previous
= m_controller
;
1654 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1655 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1656 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1659 m_controller
= controller
;
1662 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1663 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1664 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1667 onControllerChanged(controller
, previous
);
1671 void KItemListView::setModel(KItemModelBase
* model
)
1673 if (m_model
== model
) {
1677 KItemModelBase
* previous
= m_model
;
1680 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1681 this, &KItemListView::slotItemsChanged
);
1682 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1683 this, &KItemListView::slotItemsInserted
);
1684 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1685 this, &KItemListView::slotItemsRemoved
);
1686 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1687 this, &KItemListView::slotItemsMoved
);
1688 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1689 this, &KItemListView::slotGroupsChanged
);
1690 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1691 this, &KItemListView::slotGroupedSortingChanged
);
1692 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1693 this, &KItemListView::slotSortOrderChanged
);
1694 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1695 this, &KItemListView::slotSortRoleChanged
);
1697 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1701 m_layouter
->setModel(model
);
1702 m_grouped
= model
->groupedSorting();
1705 connect(m_model
, &KItemModelBase::itemsChanged
,
1706 this, &KItemListView::slotItemsChanged
);
1707 connect(m_model
, &KItemModelBase::itemsInserted
,
1708 this, &KItemListView::slotItemsInserted
);
1709 connect(m_model
, &KItemModelBase::itemsRemoved
,
1710 this, &KItemListView::slotItemsRemoved
);
1711 connect(m_model
, &KItemModelBase::itemsMoved
,
1712 this, &KItemListView::slotItemsMoved
);
1713 connect(m_model
, &KItemModelBase::groupsChanged
,
1714 this, &KItemListView::slotGroupsChanged
);
1715 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1716 this, &KItemListView::slotGroupedSortingChanged
);
1717 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1718 this, &KItemListView::slotSortOrderChanged
);
1719 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1720 this, &KItemListView::slotSortRoleChanged
);
1722 const int itemCount
= m_model
->count();
1723 if (itemCount
> 0) {
1724 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1728 onModelChanged(model
, previous
);
1731 KItemListRubberBand
* KItemListView::rubberBand() const
1733 return m_rubberBand
;
1736 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1738 if (m_activeTransactions
> 0) {
1739 if (hint
== NoAnimation
) {
1740 // As soon as at least one property change should be done without animation,
1741 // the whole transaction will be marked as not animated.
1742 m_endTransactionAnimationHint
= NoAnimation
;
1747 if (!m_model
|| m_model
->count() < 0) {
1751 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1752 if (firstVisibleIndex
< 0) {
1753 emitOffsetChanges();
1757 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1758 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1759 // is still shown if the maximum offset got decreased.
1760 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1761 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1762 if (scrollOffset() > maxOffsetToShowFullRange
) {
1763 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1764 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1767 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1769 int firstSibblingIndex
= -1;
1770 int lastSibblingIndex
= -1;
1771 const bool supportsExpanding
= supportsItemExpanding();
1773 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1775 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1776 // instances from invisible items are reused. If no reusable items are
1777 // found then new KItemListWidget instances get created.
1778 const bool animate
= (hint
== Animation
);
1779 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1780 bool applyNewPos
= true;
1782 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1783 const QPointF newPos
= itemBounds
.topLeft();
1784 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1786 if (!reusableItems
.isEmpty()) {
1787 // Reuse a KItemListWidget instance from an invisible item
1788 const int oldIndex
= reusableItems
.takeLast();
1789 widget
= m_visibleItems
.value(oldIndex
);
1790 setWidgetIndex(widget
, i
);
1791 updateWidgetProperties(widget
, i
);
1792 initializeItemListWidget(widget
);
1794 // No reusable KItemListWidget instance is available, create a new one
1795 widget
= createWidget(i
);
1797 widget
->resize(itemBounds
.size());
1799 if (animate
&& changedCount
< 0) {
1800 // Items have been deleted.
1801 if (i
>= changedIndex
) {
1802 // The item is located behind the removed range. Move the
1803 // created item to the imaginary old position outside the
1804 // view. It will get animated to the new position later.
1805 const int previousIndex
= i
- changedCount
;
1806 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1807 if (itemRect
.isEmpty()) {
1808 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1809 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1810 widget
->setPos(invisibleOldPos
);
1812 widget
->setPos(itemRect
.topLeft());
1814 applyNewPos
= false;
1818 if (supportsExpanding
&& changedCount
== 0) {
1819 if (firstSibblingIndex
< 0) {
1820 firstSibblingIndex
= i
;
1822 lastSibblingIndex
= i
;
1827 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1828 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1829 applyNewPos
= false;
1832 const bool itemsRemoved
= (changedCount
< 0);
1833 const bool itemsInserted
= (changedCount
> 0);
1834 if (itemsRemoved
&& (i
>= changedIndex
)) {
1835 // The item is located after the removed items. Animate the moving of the position.
1836 applyNewPos
= !moveWidget(widget
, newPos
);
1837 } else if (itemsInserted
&& i
>= changedIndex
) {
1838 // The item is located after the first inserted item
1839 if (i
<= changedIndex
+ changedCount
- 1) {
1840 // The item is an inserted item. Animate the appearing of the item.
1841 // For performance reasons no animation is done when changedCount is equal
1842 // to all available items.
1843 if (changedCount
< m_model
->count()) {
1844 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1846 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1847 // The item was already there before, so animate the moving of the position.
1848 // No moving animation is done if the item is animated by a create animation: This
1849 // prevents a "move animation mess" when inserting several ranges in parallel.
1850 applyNewPos
= !moveWidget(widget
, newPos
);
1854 m_animation
->stop(widget
);
1858 widget
->setPos(newPos
);
1861 Q_ASSERT(widget
->index() == i
);
1862 widget
->setVisible(true);
1864 bool animateIconResizing
= animate
;
1866 if (widget
->size() != itemBounds
.size()) {
1867 // Resize the widget for the item to the changed size.
1869 // If a dynamic item size is used then no animation is done in the direction
1870 // of the dynamic size.
1871 if (m_itemSize
.width() <= 0) {
1872 // The width is dynamic, apply the new width without animation.
1873 widget
->resize(itemBounds
.width(), widget
->size().height());
1874 } else if (m_itemSize
.height() <= 0) {
1875 // The height is dynamic, apply the new height without animation.
1876 widget
->resize(widget
->size().width(), itemBounds
.height());
1878 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1880 widget
->resize(itemBounds
.size());
1883 animateIconResizing
= false;
1886 const int newIconSize
= widget
->styleOption().iconSize
;
1887 if (widget
->iconSize() != newIconSize
) {
1888 if (animateIconResizing
) {
1889 m_animation
->start(widget
, KItemListViewAnimation::IconResizeAnimation
, newIconSize
);
1891 widget
->setIconSize(newIconSize
);
1895 // Updating the cell-information must be done as last step: The decision whether the
1896 // moving-animation should be started at all is based on the previous cell-information.
1897 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1898 m_visibleCells
.insert(i
, cell
);
1901 // Delete invisible KItemListWidget instances that have not been reused
1902 for (int index
: qAsConst(reusableItems
)) {
1903 recycleWidget(m_visibleItems
.value(index
));
1906 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1907 Q_ASSERT(lastSibblingIndex
>= 0);
1908 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1912 // Update the layout of all visible group headers
1913 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1914 while (it
.hasNext()) {
1916 updateGroupHeaderLayout(it
.key());
1920 emitOffsetChanges();
1923 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1924 int lastVisibleIndex
,
1925 LayoutAnimationHint hint
)
1927 // Determine all items that are completely invisible and might be
1928 // reused for items that just got (at least partly) visible. If the
1929 // animation hint is set to 'Animation' items that do e.g. an animated
1930 // moving of their position are not marked as invisible: This assures
1931 // that a scrolling inside the view can be done without breaking an animation.
1935 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1936 while (it
.hasNext()) {
1939 KItemListWidget
* widget
= it
.value();
1940 const int index
= widget
->index();
1941 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1944 if (m_animation
->isStarted(widget
)) {
1945 if (hint
== NoAnimation
) {
1946 // Stopping the animation will call KItemListView::slotAnimationFinished()
1947 // and the widget will be recycled if necessary there.
1948 m_animation
->stop(widget
);
1951 widget
->setVisible(false);
1952 items
.append(index
);
1955 recycleGroupHeaderForWidget(widget
);
1964 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1966 if (widget
->pos() == newPos
) {
1970 bool startMovingAnim
= false;
1972 if (m_itemSize
.isEmpty()) {
1973 // The items are not aligned in a grid but either as columns or rows.
1974 startMovingAnim
= true;
1976 // When having a grid the moving-animation should only be started, if it is done within
1977 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1978 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1979 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1980 const int index
= widget
->index();
1981 const Cell cell
= m_visibleCells
.value(index
);
1982 if (cell
.column
>= 0 && cell
.row
>= 0) {
1983 if (scrollOrientation() == Qt::Vertical
) {
1984 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1986 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1991 if (startMovingAnim
) {
1992 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1996 m_animation
->stop(widget
);
1997 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
2001 void KItemListView::emitOffsetChanges()
2003 const qreal newScrollOffset
= m_layouter
->scrollOffset();
2004 if (m_oldScrollOffset
!= newScrollOffset
) {
2005 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
2006 m_oldScrollOffset
= newScrollOffset
;
2009 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
2010 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
2011 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
2012 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
2015 const qreal newItemOffset
= m_layouter
->itemOffset();
2016 if (m_oldItemOffset
!= newItemOffset
) {
2017 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
2018 m_oldItemOffset
= newItemOffset
;
2021 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
2022 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
2023 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
2024 m_oldMaximumItemOffset
= newMaximumItemOffset
;
2028 KItemListWidget
* KItemListView::createWidget(int index
)
2030 KItemListWidget
* widget
= widgetCreator()->create(this);
2031 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
2033 m_visibleItems
.insert(index
, widget
);
2034 m_visibleCells
.insert(index
, Cell());
2035 updateWidgetProperties(widget
, index
);
2036 initializeItemListWidget(widget
);
2040 void KItemListView::recycleWidget(KItemListWidget
* widget
)
2043 recycleGroupHeaderForWidget(widget
);
2046 const int index
= widget
->index();
2047 m_visibleItems
.remove(index
);
2048 m_visibleCells
.remove(index
);
2050 widgetCreator()->recycle(widget
);
2053 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
2055 const int oldIndex
= widget
->index();
2056 m_visibleItems
.remove(oldIndex
);
2057 m_visibleCells
.remove(oldIndex
);
2059 m_visibleItems
.insert(index
, widget
);
2060 m_visibleCells
.insert(index
, Cell());
2062 widget
->setIndex(index
);
2065 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
2067 const int oldIndex
= widget
->index();
2068 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
2070 setWidgetIndex(widget
, index
);
2072 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2073 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2074 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
2075 (!vertical
&& oldCell
.column
== newCell
.column
);
2077 m_visibleCells
.insert(index
, newCell
);
2081 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2084 case LayouterSize
: m_layouter
->setSize(size
); break;
2085 case ItemSize
: m_layouter
->setItemSize(size
); break;
2090 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2092 widget
->setVisibleRoles(m_visibleRoles
);
2093 updateWidgetColumnWidths(widget
);
2094 widget
->setStyleOption(m_styleOption
);
2096 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2098 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2099 // always the selected item. It is not necessary to highlight the current item then.
2100 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2101 widget
->setCurrent(index
== selectionManager
->currentItem());
2103 widget
->setSelected(selectionManager
->isSelected(index
));
2104 widget
->setHovered(false);
2105 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2106 widget
->setIndex(index
);
2107 widget
->setData(m_model
->data(index
));
2108 widget
->setSiblingsInformation(QBitArray());
2109 updateAlternateBackgroundForWidget(widget
);
2112 updateGroupHeaderForWidget(widget
);
2116 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2118 Q_ASSERT(m_grouped
);
2120 const int index
= widget
->index();
2121 if (!m_layouter
->isFirstGroupItem(index
)) {
2122 // The widget does not represent the first item of a group
2123 // and hence requires no header
2124 recycleGroupHeaderForWidget(widget
);
2128 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2129 if (groups
.isEmpty() || !groupHeaderCreator()) {
2133 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2135 groupHeader
= groupHeaderCreator()->create(this);
2136 groupHeader
->setParentItem(widget
);
2137 m_visibleGroups
.insert(widget
, groupHeader
);
2138 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2140 Q_ASSERT(groupHeader
->parentItem() == widget
);
2142 const int groupIndex
= groupIndexForItem(index
);
2143 Q_ASSERT(groupIndex
>= 0);
2144 groupHeader
->setData(groups
.at(groupIndex
).second
);
2145 groupHeader
->setRole(model()->sortRole());
2146 groupHeader
->setStyleOption(m_styleOption
);
2147 groupHeader
->setScrollOrientation(scrollOrientation());
2148 groupHeader
->setItemIndex(index
);
2150 groupHeader
->show();
2153 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2155 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2156 Q_ASSERT(groupHeader
);
2158 const int index
= widget
->index();
2159 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2160 const QRectF itemRect
= m_layouter
->itemRect(index
);
2162 // The group-header is a child of the itemlist widget. Translate the
2163 // group header position to the relative position.
2164 if (scrollOrientation() == Qt::Vertical
) {
2165 // In the vertical scroll orientation the group header should always span
2166 // the whole width no matter which temporary position the parent widget
2167 // has. In this case the x-position and width will be adjusted manually.
2168 const qreal x
= -widget
->x() - itemOffset();
2169 const qreal width
= maximumItemOffset();
2170 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2171 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2173 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2174 groupHeader
->resize(groupHeaderRect
.size());
2178 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2180 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2182 header
->setParentItem(nullptr);
2183 groupHeaderCreator()->recycle(header
);
2184 m_visibleGroups
.remove(widget
);
2185 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2189 void KItemListView::updateVisibleGroupHeaders()
2191 Q_ASSERT(m_grouped
);
2192 m_layouter
->markAsDirty();
2194 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2195 while (it
.hasNext()) {
2197 updateGroupHeaderForWidget(it
.value());
2201 int KItemListView::groupIndexForItem(int index
) const
2203 Q_ASSERT(m_grouped
);
2205 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2206 if (groups
.isEmpty()) {
2211 int max
= groups
.count() - 1;
2214 mid
= (min
+ max
) / 2;
2215 if (index
> groups
[mid
].first
) {
2220 } while (groups
[mid
].first
!= index
&& min
<= max
);
2223 while (groups
[mid
].first
> index
&& mid
> 0) {
2231 void KItemListView::updateAlternateBackgrounds()
2233 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2234 while (it
.hasNext()) {
2236 updateAlternateBackgroundForWidget(it
.value());
2240 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2242 bool enabled
= useAlternateBackgrounds();
2244 const int index
= widget
->index();
2245 enabled
= (index
& 0x1) > 0;
2247 const int groupIndex
= groupIndexForItem(index
);
2248 if (groupIndex
>= 0) {
2249 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2250 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2251 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2252 enabled
= (relativeIndex
& 0x1) > 0;
2256 widget
->setAlternateBackground(enabled
);
2259 bool KItemListView::useAlternateBackgrounds() const
2261 return m_alternateBackgrounds
&& m_itemSize
.isEmpty();
2264 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2266 QElapsedTimer timer
;
2269 QHash
<QByteArray
, qreal
> widths
;
2271 // Calculate the minimum width for each column that is required
2272 // to show the headline unclipped.
2273 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2274 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2275 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2276 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2277 const QString headerText
= m_model
->roleDescription(visibleRole
);
2278 const qreal headerWidth
= fontMetrics
.horizontalAdvance(headerText
) + gripMargin
+ headerMargin
* 2;
2279 widths
.insert(visibleRole
, headerWidth
);
2282 // Calculate the preferred column widths for each item and ignore values
2283 // smaller than the width for showing the headline unclipped.
2284 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2285 int calculatedItemCount
= 0;
2286 bool maxTimeExceeded
= false;
2287 for (const KItemRange
& itemRange
: itemRanges
) {
2288 const int startIndex
= itemRange
.index
;
2289 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2291 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2292 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2293 qreal maxWidth
= widths
.value(visibleRole
, 0);
2294 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2295 maxWidth
= qMax(width
, maxWidth
);
2296 widths
.insert(visibleRole
, maxWidth
);
2299 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2300 // When having several thousands of items calculating the sizes can get
2301 // very expensive. We accept a possibly too small role-size in favour
2302 // of having no blocking user interface.
2303 maxTimeExceeded
= true;
2306 ++calculatedItemCount
;
2308 if (maxTimeExceeded
) {
2316 void KItemListView::applyColumnWidthsFromHeader()
2318 // Apply the new size to the layouter
2319 const qreal requiredWidth
= columnWidthsSum() + m_headerWidget
->sidePadding();
2320 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2321 m_itemSize
.height());
2322 m_layouter
->setItemSize(dynamicItemSize
);
2324 // Update the role sizes for all visible widgets
2325 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2326 while (it
.hasNext()) {
2328 updateWidgetColumnWidths(it
.value());
2332 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2334 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2335 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2337 widget
->setSidePadding(m_headerWidget
->sidePadding());
2340 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2342 Q_ASSERT(m_itemSize
.isEmpty());
2343 const int itemCount
= m_model
->count();
2344 int rangesItemCount
= 0;
2345 for (const KItemRange
& range
: itemRanges
) {
2346 rangesItemCount
+= range
.count
;
2349 if (itemCount
== rangesItemCount
) {
2350 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2351 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2352 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2355 // Only a sub range of the roles need to be determined.
2356 // The chances are good that the widths of the sub ranges
2357 // already fit into the available widths and hence no
2358 // expensive update might be required.
2359 bool changed
= false;
2361 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2362 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2363 while (it
.hasNext()) {
2365 const QByteArray
& role
= it
.key();
2366 const qreal updatedWidth
= it
.value();
2367 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2368 if (updatedWidth
> currentWidth
) {
2369 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2375 // All the updated sizes are smaller than the current sizes and no change
2376 // of the stretched roles-widths is required
2381 if (m_headerWidget
->automaticColumnResizing()) {
2382 applyAutomaticColumnWidths();
2386 void KItemListView::updatePreferredColumnWidths()
2389 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2393 void KItemListView::applyAutomaticColumnWidths()
2395 Q_ASSERT(m_itemSize
.isEmpty());
2396 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2397 if (m_visibleRoles
.isEmpty()) {
2401 // Calculate the maximum size of an item by considering the
2402 // visible role sizes and apply them to the layouter. If the
2403 // size does not use the available view-size the size of the
2404 // first role will get stretched.
2406 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2407 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2408 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2411 const QByteArray firstRole
= m_visibleRoles
.first();
2412 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2413 QSizeF dynamicItemSize
= m_itemSize
;
2415 qreal requiredWidth
= columnWidthsSum() + m_headerWidget
->sidePadding()
2416 + m_headerWidget
->sidePadding(); // Adding the padding a second time so we have the same padding symmetrically on both sides of the view.
2417 // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files.
2418 const qreal availableWidth
= size().width();
2419 if (requiredWidth
< availableWidth
) {
2420 // Stretch the first column to use the whole remaining width
2421 firstColumnWidth
+= availableWidth
- requiredWidth
;
2422 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2423 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2424 // Shrink the first column to be able to show as much other
2425 // columns as possible
2426 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2428 // TODO: A proper calculation of the minimum width depends on the implementation
2429 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2431 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2432 if (shrinkedFirstColumnWidth
< minWidth
) {
2433 shrinkedFirstColumnWidth
= minWidth
;
2436 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2437 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2440 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2442 m_layouter
->setItemSize(dynamicItemSize
);
2444 // Update the role sizes for all visible widgets
2445 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2446 while (it
.hasNext()) {
2448 updateWidgetColumnWidths(it
.value());
2452 qreal
KItemListView::columnWidthsSum() const
2454 qreal widthsSum
= 0;
2455 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2456 widthsSum
+= m_headerWidget
->columnWidth(role
);
2461 QRectF
KItemListView::headerBoundaries() const
2463 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2466 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2467 const QSizeF
& newItemSize
,
2468 const QSizeF
& newItemMargin
) const
2470 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2474 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2475 const qreal itemWidth
= m_layouter
->itemSize().width();
2476 if (itemWidth
> 0) {
2477 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2478 newItemSize
.width(),
2479 newItemMargin
.width());
2480 if (m_model
->count() > newColumnCount
) {
2481 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2483 m_layouter
->itemMargin().width());
2484 return oldColumnCount
!= newColumnCount
;
2488 const qreal itemHeight
= m_layouter
->itemSize().height();
2489 if (itemHeight
> 0) {
2490 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2491 newItemSize
.height(),
2492 newItemMargin
.height());
2493 if (m_model
->count() > newRowCount
) {
2494 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2496 m_layouter
->itemMargin().height());
2497 return oldRowCount
!= newRowCount
;
2505 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2507 if (m_itemSize
.isEmpty()) {
2508 // We have only columns or only rows, but no grid: An animation is usually
2509 // welcome when inserting or removing items.
2510 return !supportsItemExpanding();
2513 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2517 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2518 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2519 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2520 // Only animate if up to 2/3 of a row or column are inserted or removed
2521 return changedItemCount
<= maximum
* 2 / 3;
2525 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2527 const QSizeF oldSize
= m_layouter
->size();
2529 m_layouter
->setSize(size
);
2530 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2531 m_layouter
->setSize(oldSize
);
2533 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2534 : maxOffset
> size
.width();
2537 int KItemListView::showDropIndicator(const QPointF
& pos
)
2539 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2540 while (it
.hasNext()) {
2542 const KItemListWidget
* widget
= it
.value();
2544 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2545 const QRectF rect
= itemRect(widget
->index());
2546 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2547 if (m_model
->supportsDropping(widget
->index())) {
2548 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2549 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2550 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2555 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2556 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2558 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2559 if (m_dropIndicator
!= draggingInsertIndicator
) {
2560 m_dropIndicator
= draggingInsertIndicator
;
2564 int index
= widget
->index();
2572 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2573 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2576 void KItemListView::hideDropIndicator()
2578 if (!m_dropIndicator
.isNull()) {
2579 m_dropIndicator
= QRectF();
2584 void KItemListView::updateGroupHeaderHeight()
2586 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2587 qreal groupHeaderMargin
= 0;
2589 if (scrollOrientation() == Qt::Horizontal
) {
2590 // The vertical margin above and below the header should be
2591 // equal to the horizontal margin, not the vertical margin
2592 // from m_styleOption.
2593 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2594 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2595 } else if (m_itemSize
.isEmpty()){
2596 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2597 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2599 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2600 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2602 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2603 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2605 updateVisibleGroupHeaders();
2608 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2610 if (!supportsItemExpanding() || !m_model
) {
2614 if (firstIndex
< 0 || lastIndex
< 0) {
2615 firstIndex
= m_layouter
->firstVisibleIndex();
2616 lastIndex
= m_layouter
->lastVisibleIndex();
2618 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2619 lastIndex
>= m_layouter
->firstVisibleIndex());
2620 if (!isRangeVisible
) {
2625 int previousParents
= 0;
2626 QBitArray previousSiblings
;
2628 // The rootIndex describes the first index where the siblings get
2629 // calculated from. For the calculation the upper most parent item
2630 // is required. For performance reasons it is checked first whether
2631 // the visible items before or after the current range already
2632 // contain a siblings information which can be used as base.
2633 int rootIndex
= firstIndex
;
2635 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2637 // There is no visible widget before the range, check whether there
2638 // is one after the range:
2639 widget
= m_visibleItems
.value(lastIndex
+ 1);
2641 // The sibling information of the widget may only be used if
2642 // all items of the range have the same number of parents.
2643 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2644 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2645 if (m_model
->expandedParentsCount(i
) != parents
) {
2654 // Performance optimization: Use the sibling information of the visible
2655 // widget beside the given range.
2656 previousSiblings
= widget
->siblingsInformation();
2657 if (previousSiblings
.isEmpty()) {
2660 previousParents
= previousSiblings
.count() - 1;
2661 previousSiblings
.truncate(previousParents
);
2663 // Potentially slow path: Go back to the upper most parent of firstIndex
2664 // to be able to calculate the initial value for the siblings.
2665 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2670 Q_ASSERT(previousParents
>= 0);
2671 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2672 // Update the parent-siblings in case if the current item represents
2673 // a child or an upper parent.
2674 const int currentParents
= m_model
->expandedParentsCount(i
);
2675 Q_ASSERT(currentParents
>= 0);
2676 if (previousParents
< currentParents
) {
2677 previousParents
= currentParents
;
2678 previousSiblings
.resize(currentParents
);
2679 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2680 } else if (previousParents
> currentParents
) {
2681 previousParents
= currentParents
;
2682 previousSiblings
.truncate(currentParents
);
2685 if (i
>= firstIndex
) {
2686 // The index represents a visible item. Apply the parent-siblings
2687 // and update the sibling of the current item.
2688 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2693 QBitArray siblings
= previousSiblings
;
2694 siblings
.resize(siblings
.count() + 1);
2695 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2697 widget
->setSiblingsInformation(siblings
);
2702 bool KItemListView::hasSiblingSuccessor(int index
) const
2704 bool hasSuccessor
= false;
2705 const int parentsCount
= m_model
->expandedParentsCount(index
);
2706 int successorIndex
= index
+ 1;
2708 // Search the next sibling
2709 const int itemCount
= m_model
->count();
2710 while (successorIndex
< itemCount
) {
2711 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2712 if (currentParentsCount
== parentsCount
) {
2713 hasSuccessor
= true;
2715 } else if (currentParentsCount
< parentsCount
) {
2721 if (m_grouped
&& hasSuccessor
) {
2722 // If the sibling is part of another group, don't mark it as
2723 // successor as the group header is between the sibling connections.
2724 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2725 if (m_layouter
->isFirstGroupItem(i
)) {
2726 hasSuccessor
= false;
2732 return hasSuccessor
;
2735 void KItemListView::disconnectRoleEditingSignals(int index
)
2737 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2742 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2743 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2744 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2747 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2751 const int minSpeed
= 4;
2752 const int maxSpeed
= 128;
2753 const int speedLimiter
= 96;
2754 const int autoScrollBorder
= 64;
2756 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2757 // This assures that the autoscrolling speed grows gradually.
2758 const int incLimiter
= 1;
2760 if (pos
< autoScrollBorder
) {
2761 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2762 inc
= qMax(inc
, -maxSpeed
);
2763 inc
= qMax(inc
, oldInc
- incLimiter
);
2764 } else if (pos
> range
- autoScrollBorder
) {
2765 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2766 inc
= qMin(inc
, maxSpeed
);
2767 inc
= qMin(inc
, oldInc
+ incLimiter
);
2773 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2775 const qreal availableSize
= size
- itemMargin
;
2776 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2782 KItemListCreatorBase::~KItemListCreatorBase()
2784 qDeleteAll(m_recycleableWidgets
);
2785 qDeleteAll(m_createdWidgets
);
2788 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2790 m_createdWidgets
.insert(widget
);
2793 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2795 Q_ASSERT(m_createdWidgets
.contains(widget
));
2796 m_createdWidgets
.remove(widget
);
2798 if (m_recycleableWidgets
.count() < 100) {
2799 m_recycleableWidgets
.append(widget
);
2800 widget
->setVisible(false);
2806 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2808 if (m_recycleableWidgets
.isEmpty()) {
2812 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2813 m_createdWidgets
.insert(widget
);
2817 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2821 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2823 widget
->setParentItem(nullptr);
2824 widget
->setOpacity(1.0);
2825 pushRecycleableWidget(widget
);
2828 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2832 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2834 header
->setOpacity(1.0);
2835 pushRecycleableWidget(header
);