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 #ifndef QT_NO_ACCESSIBILITY
12 #include "accessibility/kitemlistcontaineraccessible.h"
13 #include "accessibility/kitemlistdelegateaccessible.h"
14 #include "accessibility/kitemlistviewaccessible.h"
16 #include "dolphindebug.h"
17 #include "kitemlistcontainer.h"
18 #include "kitemlistcontroller.h"
19 #include "kitemlistheader.h"
20 #include "kitemlistselectionmanager.h"
21 #include "kstandarditemlistwidget.h"
23 #include "private/kitemlistheaderwidget.h"
24 #include "private/kitemlistrubberband.h"
25 #include "private/kitemlistsizehintresolver.h"
26 #include "private/kitemlistviewlayouter.h"
28 #include <QElapsedTimer>
29 #include <QGraphicsSceneMouseEvent>
30 #include <QGraphicsView>
31 #include <QPropertyAnimation>
32 #include <QStyleOptionRubberBand>
34 #include <QVariantAnimation>
38 // Time in ms until reaching the autoscroll margin triggers
39 // an initial autoscrolling
40 const int InitialAutoScrollDelay
= 700;
42 // Delay in ms for triggering the next autoscroll
43 const int RepeatingAutoScrollDelay
= 1000 / 60;
45 // Copied from the Kirigami.Units.shortDuration
46 const int RubberFadeSpeed
= 150;
48 const char *RubberPropertyName
= "_kitemviews_rubberBandPosition";
51 #ifndef QT_NO_ACCESSIBILITY
52 QAccessibleInterface
*accessibleInterfaceFactory(const QString
&key
, QObject
*object
)
56 if (KItemListContainer
*container
= qobject_cast
<KItemListContainer
*>(object
)) {
57 if (auto controller
= container
->controller(); controller
) {
58 if (KItemListView
*view
= controller
->view(); view
&& view
->accessibleParent()) {
59 return view
->accessibleParent();
62 return new KItemListContainerAccessible(container
);
63 } else if (KItemListView
*view
= qobject_cast
<KItemListView
*>(object
)) {
64 return new KItemListViewAccessible(view
, view
->accessibleParent());
71 KItemListView::KItemListView(QGraphicsWidget
*parent
)
72 : QGraphicsWidget(parent
)
73 , m_enabledSelectionToggles(false)
75 , m_highlightEntireRow(false)
76 , m_alternateBackgrounds(false)
77 , m_supportsItemExpanding(false)
78 , m_editingRole(false)
79 , m_activeTransactions(0)
80 , m_endTransactionAnimationHint(Animation
)
82 , m_controller(nullptr)
85 , m_widgetCreator(nullptr)
86 , m_groupHeaderCreator(nullptr)
91 , m_scrollBarExtent(0)
93 , m_animation(nullptr)
94 , m_oldScrollOffset(0)
95 , m_oldMaximumScrollOffset(0)
97 , m_oldMaximumItemOffset(0)
98 , m_skipAutoScrollForRubberBand(false)
99 , m_rubberBand(nullptr)
100 , m_tapAndHoldIndicator(nullptr)
102 , m_autoScrollIncrement(0)
103 , m_autoScrollTimer(nullptr)
105 , m_headerWidget(nullptr)
106 , m_indicatorAnimation(nullptr)
108 , m_sizeHintResolver(nullptr)
110 setAcceptHoverEvents(true);
111 setAcceptTouchEvents(true);
113 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
115 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
117 m_animation
= new KItemListViewAnimation(this);
118 connect(m_animation
, &KItemListViewAnimation::finished
, this, &KItemListView::slotAnimationFinished
);
120 m_rubberBand
= new KItemListRubberBand(this);
121 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
123 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
124 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
125 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
127 m_indicatorAnimation
->setDuration(150);
128 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
129 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
130 m_indicatorAnimation
->start();
134 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
135 if (m_tapAndHoldIndicator
->isActive()) {
140 m_headerWidget
= new KItemListHeaderWidget(this);
141 m_headerWidget
->setVisible(false);
143 m_header
= new KItemListHeader(this);
145 #ifndef QT_NO_ACCESSIBILITY
146 QAccessible::installFactory(accessibleInterfaceFactory
);
150 KItemListView::~KItemListView()
152 // The group headers are children of the widgets created by
153 // widgetCreator(). So it is mandatory to delete the group headers
155 delete m_groupHeaderCreator
;
156 m_groupHeaderCreator
= nullptr;
158 delete m_widgetCreator
;
159 m_widgetCreator
= nullptr;
161 delete m_sizeHintResolver
;
162 m_sizeHintResolver
= nullptr;
165 void KItemListView::setScrollOffset(qreal offset
)
171 const qreal previousOffset
= m_layouter
->scrollOffset();
172 if (offset
== previousOffset
) {
176 m_layouter
->setScrollOffset(offset
);
177 m_animation
->setScrollOffset(offset
);
179 // Don't check whether the m_layoutTimer is active: Changing the
180 // scroll offset must always trigger a synchronous layout, otherwise
181 // the smooth-scrolling might get jerky.
182 doLayout(NoAnimation
);
183 onScrollOffsetChanged(offset
, previousOffset
);
186 qreal
KItemListView::scrollOffset() const
188 return m_layouter
->scrollOffset();
191 qreal
KItemListView::maximumScrollOffset() const
193 return m_layouter
->maximumScrollOffset();
196 void KItemListView::setItemOffset(qreal offset
)
198 if (m_layouter
->itemOffset() == offset
) {
202 m_layouter
->setItemOffset(offset
);
203 if (m_headerWidget
->isVisible()) {
204 m_headerWidget
->setOffset(offset
);
207 // Don't check whether the m_layoutTimer is active: Changing the
208 // item offset must always trigger a synchronous layout, otherwise
209 // the smooth-scrolling might get jerky.
210 doLayout(NoAnimation
);
213 qreal
KItemListView::itemOffset() const
215 return m_layouter
->itemOffset();
218 qreal
KItemListView::maximumItemOffset() const
220 return m_layouter
->maximumItemOffset();
223 int KItemListView::maximumVisibleItems() const
225 return m_layouter
->maximumVisibleItems();
228 void KItemListView::setVisibleRoles(const QList
<QByteArray
> &roles
)
230 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
231 m_visibleRoles
= roles
;
232 onVisibleRolesChanged(roles
, previousRoles
);
234 m_sizeHintResolver
->clearCache();
235 m_layouter
->markAsDirty();
237 if (m_itemSize
.isEmpty()) {
238 m_headerWidget
->setColumns(roles
);
239 updatePreferredColumnWidths();
240 if (!m_headerWidget
->automaticColumnResizing()) {
241 // The column-width of new roles are still 0. Apply the preferred
242 // column-width as default with.
243 for (const QByteArray
&role
: std::as_const(m_visibleRoles
)) {
244 if (m_headerWidget
->columnWidth(role
) == 0) {
245 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
246 m_headerWidget
->setColumnWidth(role
, width
);
250 applyColumnWidthsFromHeader();
254 const bool alternateBackgroundsChanged
=
255 m_itemSize
.isEmpty() && ((roles
.count() > 1 && previousRoles
.count() <= 1) || (roles
.count() <= 1 && previousRoles
.count() > 1));
257 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
258 while (it
.hasNext()) {
260 KItemListWidget
*widget
= it
.value();
261 widget
->setVisibleRoles(roles
);
262 if (alternateBackgroundsChanged
) {
263 updateAlternateBackgroundForWidget(widget
);
267 doLayout(NoAnimation
);
270 QList
<QByteArray
> KItemListView::visibleRoles() const
272 return m_visibleRoles
;
275 void KItemListView::setAutoScroll(bool enabled
)
277 if (enabled
&& !m_autoScrollTimer
) {
278 m_autoScrollTimer
= new QTimer(this);
279 m_autoScrollTimer
->setSingleShot(true);
280 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
281 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
282 } else if (!enabled
&& m_autoScrollTimer
) {
283 delete m_autoScrollTimer
;
284 m_autoScrollTimer
= nullptr;
288 bool KItemListView::autoScroll() const
290 return m_autoScrollTimer
!= nullptr;
293 void KItemListView::setEnabledSelectionToggles(bool enabled
)
295 if (m_enabledSelectionToggles
!= enabled
) {
296 m_enabledSelectionToggles
= enabled
;
298 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
299 while (it
.hasNext()) {
301 it
.value()->setEnabledSelectionToggle(enabled
);
306 bool KItemListView::enabledSelectionToggles() const
308 return m_enabledSelectionToggles
;
311 KItemListController
*KItemListView::controller() const
316 KItemModelBase
*KItemListView::model() const
321 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
*widgetCreator
)
323 delete m_widgetCreator
;
324 m_widgetCreator
= widgetCreator
;
327 KItemListWidgetCreatorBase
*KItemListView::widgetCreator() const
329 if (!m_widgetCreator
) {
330 m_widgetCreator
= defaultWidgetCreator();
332 return m_widgetCreator
;
335 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
*groupHeaderCreator
)
337 delete m_groupHeaderCreator
;
338 m_groupHeaderCreator
= groupHeaderCreator
;
341 KItemListGroupHeaderCreatorBase
*KItemListView::groupHeaderCreator() const
343 if (!m_groupHeaderCreator
) {
344 m_groupHeaderCreator
= defaultGroupHeaderCreator();
346 return m_groupHeaderCreator
;
349 #ifndef QT_NO_ACCESSIBILITY
350 void KItemListView::setAccessibleParentsObject(KItemListContainer
*accessibleParentsObject
)
352 Q_ASSERT(!m_accessibleParent
);
353 m_accessibleParent
= new KItemListContainerAccessible(accessibleParentsObject
);
355 KItemListContainerAccessible
*KItemListView::accessibleParent()
357 Q_CHECK_PTR(m_accessibleParent
); // We always want the accessibility tree/hierarchy to be complete.
358 return m_accessibleParent
;
362 QSizeF
KItemListView::itemSize() const
367 const KItemListStyleOption
&KItemListView::styleOption() const
369 return m_styleOption
;
372 void KItemListView::setGeometry(const QRectF
&rect
)
374 QGraphicsWidget::setGeometry(rect
);
380 const QSizeF newSize
= rect
.size();
381 if (m_itemSize
.isEmpty()) {
382 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
383 if (m_headerWidget
->automaticColumnResizing()) {
384 applyAutomaticColumnWidths();
386 const qreal requiredWidth
= columnWidthsSum() + 2 * m_headerWidget
->sidePadding();
387 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
), m_itemSize
.height());
388 m_layouter
->setItemSize(dynamicItemSize
);
392 m_layouter
->setSize(newSize
);
393 // We don't animate the moving of the items here because
394 // it would look like the items are slow to find their position.
395 doLayout(NoAnimation
);
398 qreal
KItemListView::verticalPageStep() const
400 qreal headerHeight
= 0;
401 if (m_headerWidget
->isVisible()) {
402 headerHeight
= m_headerWidget
->size().height();
404 return size().height() - headerHeight
;
407 std::optional
<int> KItemListView::itemAt(const QPointF
&pos
) const
409 if (headerBoundaries().contains(pos
)) {
413 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
414 while (it
.hasNext()) {
417 const KItemListWidget
*widget
= it
.value();
418 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
419 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
427 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
&pos
) const
429 if (!m_enabledSelectionToggles
) {
433 const KItemListWidget
*widget
= m_visibleItems
.value(index
);
435 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
436 if (!selectionToggleRect
.isEmpty()) {
437 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
438 return selectionToggleRect
.contains(mappedPos
);
444 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
&pos
) const
446 const KItemListWidget
*widget
= m_visibleItems
.value(index
);
448 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
449 if (!expansionToggleRect
.isEmpty()) {
450 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
451 return expansionToggleRect
.contains(mappedPos
);
457 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
459 const KItemListWidget
*widget
= m_visibleItems
.value(index
);
461 const QRectF
&textRect
= widget
->textRect();
462 if (!textRect
.isEmpty()) {
463 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
464 return textRect
.contains(mappedPos
);
470 int KItemListView::firstVisibleIndex() const
472 return m_layouter
->firstVisibleIndex();
475 int KItemListView::lastVisibleIndex() const
477 return m_layouter
->lastVisibleIndex();
480 void KItemListView::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
, qreal
&logicalWidthHint
) const
482 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
485 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
487 if (m_supportsItemExpanding
!= supportsExpanding
) {
488 m_supportsItemExpanding
= supportsExpanding
;
489 updateSiblingsInformation();
490 onSupportsItemExpandingChanged(supportsExpanding
);
494 bool KItemListView::supportsItemExpanding() const
496 return m_supportsItemExpanding
;
499 void KItemListView::setHighlightEntireRow(bool highlightEntireRow
)
501 if (m_highlightEntireRow
!= highlightEntireRow
) {
502 m_highlightEntireRow
= highlightEntireRow
;
503 onHighlightEntireRowChanged(highlightEntireRow
);
507 bool KItemListView::highlightEntireRow() const
509 return m_highlightEntireRow
;
512 void KItemListView::setAlternateBackgrounds(bool alternate
)
514 if (m_alternateBackgrounds
!= alternate
) {
515 m_alternateBackgrounds
= alternate
;
516 updateAlternateBackgrounds();
520 bool KItemListView::alternateBackgrounds() const
522 return m_alternateBackgrounds
;
525 QRectF
KItemListView::itemRect(int index
) const
527 return m_layouter
->itemRect(index
);
530 QRectF
KItemListView::itemContextRect(int index
) const
534 const KItemListWidget
*widget
= m_visibleItems
.value(index
);
536 contextRect
= widget
->iconRect() | widget
->textRect();
537 contextRect
.translate(itemRect(index
).topLeft());
543 bool KItemListView::isElided(int index
) const
545 return m_sizeHintResolver
->isElided(index
);
548 void KItemListView::scrollToItem(int index
, ViewItemPosition viewItemPosition
)
550 QRectF viewGeometry
= geometry();
551 if (m_headerWidget
->isVisible()) {
552 const qreal headerHeight
= m_headerWidget
->size().height();
553 viewGeometry
.adjust(0, headerHeight
, 0, 0);
555 QRectF currentRect
= itemRect(index
);
557 if (layoutDirection() == Qt::RightToLeft
&& scrollOrientation() == Qt::Horizontal
) {
558 currentRect
.moveLeft(m_layouter
->size().width() - currentRect
.right());
561 // Fix for Bug 311099 - View the underscore when using Ctrl + PageDown
562 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
, m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
565 switch (scrollOrientation()) {
567 if (currentRect
.top() < viewGeometry
.top() || currentRect
.bottom() > viewGeometry
.bottom()) {
568 switch (viewItemPosition
) {
570 offset
= currentRect
.top() - viewGeometry
.top();
573 offset
= 0.5 * (currentRect
.top() + currentRect
.bottom() - (viewGeometry
.top() + viewGeometry
.bottom()));
576 offset
= currentRect
.bottom() - viewGeometry
.bottom();
579 if (currentRect
.top() < viewGeometry
.top()) {
580 offset
= currentRect
.top() - viewGeometry
.top();
582 if (currentRect
.bottom() > viewGeometry
.bottom() + offset
) {
583 offset
+= currentRect
.bottom() - viewGeometry
.bottom() - offset
;
592 if (currentRect
.left() < viewGeometry
.left() || currentRect
.right() > viewGeometry
.right()) {
593 switch (viewItemPosition
) {
595 if (layoutDirection() == Qt::RightToLeft
) {
596 offset
= currentRect
.right() - viewGeometry
.right();
598 offset
= currentRect
.left() - viewGeometry
.left();
602 offset
= 0.5 * (currentRect
.left() + currentRect
.right() - (viewGeometry
.left() + viewGeometry
.right()));
605 if (layoutDirection() == Qt::RightToLeft
) {
606 offset
= currentRect
.left() - viewGeometry
.left();
608 offset
= currentRect
.right() - viewGeometry
.right();
612 if (layoutDirection() == Qt::RightToLeft
) {
613 if (currentRect
.left() < viewGeometry
.left()) {
614 offset
= currentRect
.left() - viewGeometry
.left();
616 if (currentRect
.right() > viewGeometry
.right() + offset
) {
617 offset
+= currentRect
.right() - viewGeometry
.right() - offset
;
620 if (currentRect
.right() > viewGeometry
.right()) {
621 offset
= currentRect
.right() - viewGeometry
.right();
623 if (currentRect
.left() < viewGeometry
.left() + offset
) {
624 offset
+= currentRect
.left() - viewGeometry
.left() - offset
;
637 if (!qFuzzyIsNull(offset
)) {
638 Q_EMIT
scrollTo(scrollOffset() + offset
);
642 Q_EMIT
scrollingStopped();
645 void KItemListView::beginTransaction()
647 ++m_activeTransactions
;
648 if (m_activeTransactions
== 1) {
649 onTransactionBegin();
653 void KItemListView::endTransaction()
655 --m_activeTransactions
;
656 if (m_activeTransactions
< 0) {
657 m_activeTransactions
= 0;
658 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
661 if (m_activeTransactions
== 0) {
663 doLayout(m_endTransactionAnimationHint
);
664 m_endTransactionAnimationHint
= Animation
;
668 bool KItemListView::isTransactionActive() const
670 return m_activeTransactions
> 0;
673 void KItemListView::setHeaderVisible(bool visible
)
675 if (visible
&& !m_headerWidget
->isVisible()) {
676 QStyleOptionHeader option
;
677 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
, &option
, QSize());
679 m_headerWidget
->setPos(0, 0);
680 m_headerWidget
->resize(size().width(), headerSize
.height());
681 m_headerWidget
->setModel(m_model
);
682 m_headerWidget
->setColumns(m_visibleRoles
);
683 m_headerWidget
->setZValue(1);
685 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
, this, &KItemListView::slotHeaderColumnWidthChanged
);
686 connect(m_headerWidget
, &KItemListHeaderWidget::sidePaddingChanged
, this, &KItemListView::slotSidePaddingChanged
);
687 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
, this, &KItemListView::slotHeaderColumnMoved
);
688 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
, this, &KItemListView::sortOrderChanged
);
689 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
, this, &KItemListView::sortRoleChanged
);
690 connect(m_headerWidget
, &KItemListHeaderWidget::columnHovered
, this, &KItemListView::columnHovered
);
691 connect(m_headerWidget
, &KItemListHeaderWidget::columnUnHovered
, this, &KItemListView::columnUnHovered
);
693 m_layouter
->setHeaderHeight(headerSize
.height());
694 m_headerWidget
->setVisible(true);
695 } else if (!visible
&& m_headerWidget
->isVisible()) {
696 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
, this, &KItemListView::slotHeaderColumnWidthChanged
);
697 disconnect(m_headerWidget
, &KItemListHeaderWidget::sidePaddingChanged
, this, &KItemListView::slotSidePaddingChanged
);
698 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
, this, &KItemListView::slotHeaderColumnMoved
);
699 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
, this, &KItemListView::sortOrderChanged
);
700 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
, this, &KItemListView::sortRoleChanged
);
701 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnHovered
, this, &KItemListView::columnHovered
);
702 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnUnHovered
, this, &KItemListView::columnUnHovered
);
704 m_layouter
->setHeaderHeight(0);
705 m_headerWidget
->setVisible(false);
709 bool KItemListView::isHeaderVisible() const
711 return m_headerWidget
->isVisible();
714 KItemListHeader
*KItemListView::header() const
719 QPixmap
KItemListView::createDragPixmap(const KItemSet
&indexes
) const
723 if (indexes
.count() == 1) {
724 KItemListWidget
*item
= m_visibleItems
.value(indexes
.first());
725 QGraphicsView
*graphicsView
= scene()->views()[0];
726 if (item
&& graphicsView
) {
727 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
730 // TODO: Not implemented yet. Probably extend the interface
731 // from KItemListWidget::createDragPixmap() to return a pixmap
732 // that can be used for multiple indexes.
738 void KItemListView::editRole(int index
, const QByteArray
&role
)
740 KStandardItemListWidget
*widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
741 if (!widget
|| m_editingRole
) {
745 m_editingRole
= true;
746 widget
->setEditedRole(role
);
748 connect(widget
, &KItemListWidget::roleEditingCanceled
, this, &KItemListView::slotRoleEditingCanceled
);
749 connect(widget
, &KItemListWidget::roleEditingFinished
, this, &KItemListView::slotRoleEditingFinished
);
751 connect(this, &KItemListView::scrollOffsetChanged
, widget
, &KStandardItemListWidget::finishRoleEditing
);
754 void KItemListView::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
756 QGraphicsWidget::paint(painter
, option
, widget
);
758 for (auto animation
: std::as_const(m_rubberBandAnimations
)) {
759 QRectF rubberBandRect
= animation
->property(RubberPropertyName
).toRectF();
761 const QPointF topLeft
= rubberBandRect
.topLeft();
762 if (scrollOrientation() == Qt::Vertical
) {
763 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
765 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
768 QStyleOptionRubberBand opt
;
769 initStyleOption(&opt
);
770 opt
.shape
= QRubberBand::Rectangle
;
772 opt
.rect
= rubberBandRect
.toRect();
776 painter
->setOpacity(animation
->currentValue().toReal());
777 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
782 if (m_rubberBand
->isActive()) {
783 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(), m_rubberBand
->endPosition()).normalized();
785 const QPointF topLeft
= rubberBandRect
.topLeft();
786 if (scrollOrientation() == Qt::Vertical
) {
787 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
789 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
792 QStyleOptionRubberBand opt
;
793 initStyleOption(&opt
);
794 opt
.shape
= QRubberBand::Rectangle
;
796 opt
.rect
= rubberBandRect
.toRect();
797 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
800 if (m_tapAndHoldIndicator
->isActive()) {
801 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
802 const QRectF rubberBandRect
=
803 QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
, (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
804 QStyleOptionRubberBand opt
;
805 initStyleOption(&opt
);
806 opt
.shape
= QRubberBand::Rectangle
;
808 opt
.rect
= rubberBandRect
.toRect();
809 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
812 if (!m_dropIndicator
.isEmpty()) {
813 const QRectF r
= m_dropIndicator
.toRect();
815 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
816 painter
->setPen(color
);
818 // TODO: The following implementation works only for a vertical scroll-orientation
819 // and assumes a height of the m_draggingInsertIndicator of 1.
820 Q_ASSERT(r
.height() == 1);
821 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
824 painter
->setPen(color
);
825 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
829 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
831 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
832 if (!scene()->views().isEmpty()) {
833 m_styleOption
.palette
= scene()->views().at(0)->palette();
836 return QGraphicsItem::itemChange(change
, value
);
839 void KItemListView::setItemSize(const QSizeF
&size
)
841 const QSizeF previousSize
= m_itemSize
;
842 if (size
== previousSize
) {
846 // Skip animations when the number of rows or columns
847 // are changed in the grid layout. Although the animation
848 // engine can handle this usecase, it looks obtrusive.
849 const bool animate
= !changesItemGridLayout(m_layouter
->size(), size
, m_layouter
->itemMargin());
851 const bool alternateBackgroundsChanged
= m_alternateBackgrounds
&& ((m_itemSize
.isEmpty() && !size
.isEmpty()) || (!m_itemSize
.isEmpty() && size
.isEmpty()));
855 if (alternateBackgroundsChanged
) {
856 // For an empty item size alternate backgrounds are drawn if more than
857 // one role is shown. Assure that the backgrounds for visible items are
858 // updated when changing the size in this context.
859 updateAlternateBackgrounds();
862 if (size
.isEmpty()) {
863 if (m_headerWidget
->automaticColumnResizing()) {
864 updatePreferredColumnWidths();
866 // Only apply the changed height and respect the header widths
868 const qreal currentWidth
= m_layouter
->itemSize().width();
869 const QSizeF
newSize(currentWidth
, size
.height());
870 m_layouter
->setItemSize(newSize
);
873 m_layouter
->setItemSize(size
);
876 m_sizeHintResolver
->clearCache();
877 doLayout(animate
? Animation
: NoAnimation
);
878 onItemSizeChanged(size
, previousSize
);
881 void KItemListView::setStyleOption(const KItemListStyleOption
&option
)
883 if (m_styleOption
== option
) {
887 const KItemListStyleOption previousOption
= m_styleOption
;
888 m_styleOption
= option
;
891 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
892 if (margin
!= m_layouter
->itemMargin()) {
893 // Skip animations when the number of rows or columns
894 // are changed in the grid layout. Although the animation
895 // engine can handle this usecase, it looks obtrusive.
896 animate
= !changesItemGridLayout(m_layouter
->size(), m_layouter
->itemSize(), margin
);
897 m_layouter
->setItemMargin(margin
);
901 updateGroupHeaderHeight();
904 if (animate
&& (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
905 // Animating a change of the maximum text size just results in expensive
906 // temporary eliding and clipping operations and does not look good visually.
910 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
911 while (it
.hasNext()) {
913 it
.value()->setStyleOption(option
);
916 m_sizeHintResolver
->clearCache();
917 m_layouter
->markAsDirty();
918 doLayout(animate
? Animation
: NoAnimation
);
920 if (m_itemSize
.isEmpty()) {
921 updatePreferredColumnWidths();
924 onStyleOptionChanged(option
, previousOption
);
927 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
929 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
930 if (orientation
== previousOrientation
) {
934 m_layouter
->setScrollOrientation(orientation
);
935 m_animation
->setScrollOrientation(orientation
);
936 m_sizeHintResolver
->clearCache();
939 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
940 while (it
.hasNext()) {
942 it
.value()->setScrollOrientation(orientation
);
944 updateGroupHeaderHeight();
947 doLayout(NoAnimation
);
949 onScrollOrientationChanged(orientation
, previousOrientation
);
950 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
953 Qt::Orientation
KItemListView::scrollOrientation() const
955 return m_layouter
->scrollOrientation();
958 KItemListWidgetCreatorBase
*KItemListView::defaultWidgetCreator() const
963 KItemListGroupHeaderCreatorBase
*KItemListView::defaultGroupHeaderCreator() const
968 void KItemListView::initializeItemListWidget(KItemListWidget
*item
)
973 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
> &changedRoles
) const
975 Q_UNUSED(changedRoles
)
979 void KItemListView::onControllerChanged(KItemListController
*current
, KItemListController
*previous
)
985 void KItemListView::onModelChanged(KItemModelBase
*current
, KItemModelBase
*previous
)
991 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
997 void KItemListView::onItemSizeChanged(const QSizeF
¤t
, const QSizeF
&previous
)
1003 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
1009 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
1015 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
1021 void KItemListView::onHighlightEntireRowChanged(bool highlightEntireRow
)
1023 Q_UNUSED(highlightEntireRow
)
1026 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
1028 Q_UNUSED(supportsExpanding
)
1031 void KItemListView::onTransactionBegin()
1035 void KItemListView::onTransactionEnd()
1039 bool KItemListView::event(QEvent
*event
)
1041 switch (event
->type()) {
1042 case QEvent::PaletteChange
:
1046 case QEvent::FontChange
:
1050 case QEvent::FocusIn
:
1051 focusInEvent(static_cast<QFocusEvent
*>(event
));
1056 case QEvent::FocusOut
:
1057 focusOutEvent(static_cast<QFocusEvent
*>(event
));
1063 // Forward all other events to the controller and handle them there
1064 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
1070 return QGraphicsWidget::event(event
);
1073 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
*event
)
1075 m_mousePos
= transform().map(event
->pos());
1079 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
)
1081 QGraphicsWidget::mouseMoveEvent(event
);
1083 m_mousePos
= transform().map(event
->pos());
1084 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1085 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1089 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
)
1091 event
->setAccepted(true);
1092 setAutoScroll(true);
1095 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
1097 QGraphicsWidget::dragMoveEvent(event
);
1099 m_mousePos
= transform().map(event
->pos());
1100 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1101 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1105 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
1107 QGraphicsWidget::dragLeaveEvent(event
);
1108 setAutoScroll(false);
1111 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
*event
)
1113 QGraphicsWidget::dropEvent(event
);
1114 setAutoScroll(false);
1117 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
1119 return m_visibleItems
.values();
1122 void KItemListView::updateFont()
1124 if (scene() && !scene()->views().isEmpty()) {
1125 KItemListStyleOption option
= styleOption();
1126 option
.font
= scene()->views().first()->font();
1127 option
.fontMetrics
= QFontMetrics(option
.font
);
1129 setStyleOption(option
);
1133 void KItemListView::updatePalette()
1135 KItemListStyleOption option
= styleOption();
1136 option
.palette
= palette();
1137 setStyleOption(option
);
1140 void KItemListView::slotItemsInserted(const KItemRangeList
&itemRanges
)
1142 if (m_itemSize
.isEmpty()) {
1143 updatePreferredColumnWidths(itemRanges
);
1146 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1147 if (hasMultipleRanges
) {
1151 m_layouter
->markAsDirty();
1153 m_sizeHintResolver
->itemsInserted(itemRanges
);
1155 int previouslyInsertedCount
= 0;
1156 for (const KItemRange
&range
: itemRanges
) {
1157 // range.index is related to the model before anything has been inserted.
1158 // As in each loop the current item-range gets inserted the index must
1159 // be increased by the already previously inserted items.
1160 const int index
= range
.index
+ previouslyInsertedCount
;
1161 const int count
= range
.count
;
1162 if (index
< 0 || count
<= 0) {
1163 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1166 previouslyInsertedCount
+= count
;
1168 // Determine which visible items must be moved
1169 QList
<int> itemsToMove
;
1170 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1171 while (it
.hasNext()) {
1173 const int visibleItemIndex
= it
.key();
1174 if (visibleItemIndex
>= index
) {
1175 itemsToMove
.append(visibleItemIndex
);
1179 // Update the indexes of all KItemListWidget instances that are located
1180 // after the inserted items. It is important to adjust the indexes in the order
1181 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1182 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1183 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1184 KItemListWidget
*widget
= m_visibleItems
.value(itemsToMove
[i
]);
1186 const int newIndex
= widget
->index() + count
;
1187 if (hasMultipleRanges
) {
1188 setWidgetIndex(widget
, newIndex
);
1190 // Try to animate the moving of the item
1191 moveWidgetToIndex(widget
, newIndex
);
1195 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1196 // Check whether a scrollbar is required to show the inserted items. In this case
1197 // the size of the layouter will be decreased before calling doLayout(): This prevents
1198 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1199 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1200 const bool decreaseLayouterSize
= (verticalScrollOrientation
&& maximumScrollOffset() > size().height())
1201 || (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1202 if (decreaseLayouterSize
) {
1203 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1205 int scrollbarSpacing
= 0;
1206 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1207 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1210 QSizeF layouterSize
= m_layouter
->size();
1211 if (verticalScrollOrientation
) {
1212 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1214 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1216 m_layouter
->setSize(layouterSize
);
1220 if (!hasMultipleRanges
) {
1221 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1222 updateSiblingsInformation();
1227 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1230 if (hasMultipleRanges
) {
1231 m_endTransactionAnimationHint
= NoAnimation
;
1234 updateSiblingsInformation();
1237 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1238 // In case if items of the same group have been inserted before an item that
1239 // currently represents the first item of the group, the group header of
1240 // this item must be removed.
1241 updateVisibleGroupHeaders();
1244 if (useAlternateBackgrounds()) {
1245 updateAlternateBackgrounds();
1247 #ifndef QT_NO_ACCESSIBILITY
1248 if (QAccessible::isActive()) { // Announce that the count of items has changed.
1249 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(this))->announceDescriptionChange();
1254 void KItemListView::slotItemsRemoved(const KItemRangeList
&itemRanges
)
1256 if (m_itemSize
.isEmpty()) {
1257 // Don't pass the item-range: The preferred column-widths of
1258 // all items must be adjusted when removing items.
1259 updatePreferredColumnWidths();
1262 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1263 if (hasMultipleRanges
) {
1267 m_layouter
->markAsDirty();
1269 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1271 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1272 const KItemRange
&range
= itemRanges
[i
];
1273 const int index
= range
.index
;
1274 const int count
= range
.count
;
1275 if (index
< 0 || count
<= 0) {
1276 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1280 const int firstRemovedIndex
= index
;
1281 const int lastRemovedIndex
= index
+ count
- 1;
1283 // Remember which items have to be moved because they are behind the removed range.
1284 QVector
<int> itemsToMove
;
1286 // Remove all KItemListWidget instances that got deleted
1287 // Iterate over a const copy because the container is mutated within the loop
1288 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1289 const auto visibleItems
= m_visibleItems
;
1290 for (KItemListWidget
*widget
: visibleItems
) {
1291 const int i
= widget
->index();
1292 if (i
< firstRemovedIndex
) {
1294 } else if (i
> lastRemovedIndex
) {
1295 itemsToMove
.append(i
);
1299 m_animation
->stop(widget
);
1300 // Stopping the animation might lead to recycling the widget if
1301 // it is invisible (see slotAnimationFinished()).
1302 // Check again whether it is still visible:
1303 if (!m_visibleItems
.contains(i
)) {
1307 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1308 // Remove the widget without animation
1309 recycleWidget(widget
);
1311 // Animate the removing of the items. Special case: When removing an item there
1312 // is no valid model index available anymore. For the
1313 // remove-animation the item gets removed from m_visibleItems but the widget
1314 // will stay alive until the animation has been finished and will
1315 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1316 m_visibleItems
.remove(i
);
1317 widget
->setIndex(-1);
1318 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1322 // Update the indexes of all KItemListWidget instances that are located
1323 // after the deleted items. It is important to update them in ascending
1324 // order to prevent overlaps when setting the new index.
1325 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1326 for (int i
: std::as_const(itemsToMove
)) {
1327 KItemListWidget
*widget
= m_visibleItems
.value(i
);
1329 const int newIndex
= i
- count
;
1330 if (hasMultipleRanges
) {
1331 setWidgetIndex(widget
, newIndex
);
1333 // Try to animate the moving of the item
1334 moveWidgetToIndex(widget
, newIndex
);
1338 if (!hasMultipleRanges
) {
1339 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1340 // assumes an updated geometry. If items are removed during an active transaction,
1341 // the transaction will be temporary deactivated so that doLayout() triggers a
1342 // geometry update if necessary.
1343 const int activeTransactions
= m_activeTransactions
;
1344 m_activeTransactions
= 0;
1345 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1346 m_activeTransactions
= activeTransactions
;
1347 updateSiblingsInformation();
1352 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1355 if (hasMultipleRanges
) {
1356 m_endTransactionAnimationHint
= NoAnimation
;
1358 updateSiblingsInformation();
1361 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1362 // In case if the first item of a group has been removed, the group header
1363 // must be applied to the next visible item.
1364 updateVisibleGroupHeaders();
1367 if (useAlternateBackgrounds()) {
1368 updateAlternateBackgrounds();
1370 #ifndef QT_NO_ACCESSIBILITY
1371 if (QAccessible::isActive()) { // Announce that the count of items has changed.
1372 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(this))->announceDescriptionChange();
1377 void KItemListView::slotItemsMoved(const KItemRange
&itemRange
, const QList
<int> &movedToIndexes
)
1379 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1380 m_layouter
->markAsDirty();
1383 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1386 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1387 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1389 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1390 KItemListWidget
*widget
= m_visibleItems
.value(index
);
1392 updateWidgetProperties(widget
, index
);
1393 initializeItemListWidget(widget
);
1397 doLayout(NoAnimation
);
1398 updateSiblingsInformation();
1401 void KItemListView::slotItemsChanged(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &roles
)
1403 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1404 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1405 updatePreferredColumnWidths(itemRanges
);
1408 for (const KItemRange
&itemRange
: itemRanges
) {
1409 const int index
= itemRange
.index
;
1410 const int count
= itemRange
.count
;
1412 if (updateSizeHints
) {
1413 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1414 m_layouter
->markAsDirty();
1417 // Apply the changed roles to the visible item-widgets
1418 const int lastIndex
= index
+ count
- 1;
1419 for (int i
= index
; i
<= lastIndex
; ++i
) {
1420 KItemListWidget
*widget
= m_visibleItems
.value(i
);
1422 widget
->setData(m_model
->data(i
), roles
);
1426 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1427 // The sort-role has been changed which might result
1428 // in modified group headers
1429 updateVisibleGroupHeaders();
1430 doLayout(NoAnimation
);
1433 #ifndef QT_NO_ACCESSIBILITY
1434 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1435 ev
.setFirstRow(itemRange
.index
);
1436 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1437 QAccessible::updateAccessibility(&ev
);
1441 doLayout(NoAnimation
);
1444 void KItemListView::slotGroupsChanged()
1446 updateVisibleGroupHeaders();
1447 doLayout(NoAnimation
);
1448 updateSiblingsInformation();
1451 void KItemListView::slotGroupedSortingChanged(bool current
)
1453 m_grouped
= current
;
1454 m_layouter
->markAsDirty();
1457 updateGroupHeaderHeight();
1459 // Clear all visible headers. Note that the QHashIterator takes a copy of
1460 // m_visibleGroups. Therefore, it remains valid even if items are removed
1461 // from m_visibleGroups in recycleGroupHeaderForWidget().
1462 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1463 while (it
.hasNext()) {
1465 recycleGroupHeaderForWidget(it
.key());
1467 Q_ASSERT(m_visibleGroups
.isEmpty());
1470 if (useAlternateBackgrounds()) {
1471 // Changing the group mode requires to update the alternate backgrounds
1472 // as with the enabled group mode the altering is done on base of the first
1474 updateAlternateBackgrounds();
1476 updateSiblingsInformation();
1477 doLayout(NoAnimation
);
1480 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1485 updateVisibleGroupHeaders();
1486 doLayout(NoAnimation
);
1490 void KItemListView::slotSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
1495 updateVisibleGroupHeaders();
1496 doLayout(NoAnimation
);
1500 void KItemListView::slotCurrentChanged(int current
, int previous
)
1502 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1503 // always the selected item. It is not necessary to highlight the current item then.
1504 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1505 KItemListWidget
*previousWidget
= m_visibleItems
.value(previous
, nullptr);
1506 if (previousWidget
) {
1507 previousWidget
->setCurrent(false);
1510 KItemListWidget
*currentWidget
= m_visibleItems
.value(current
, nullptr);
1511 if (currentWidget
) {
1512 currentWidget
->setCurrent(true);
1513 if (hasFocus() || (previousWidget
&& previousWidget
->hasFocus())) {
1514 currentWidget
->setFocus(); // Mostly for accessibility, because keyboard events are handled correctly either way.
1518 #ifndef QT_NO_ACCESSIBILITY
1519 if (QAccessible::isActive()) {
1521 QAccessibleEvent
accessibleFocusCurrentItemEvent(this, QAccessible::Focus
);
1522 accessibleFocusCurrentItemEvent
.setChild(current
);
1523 QAccessible::updateAccessibility(&accessibleFocusCurrentItemEvent
);
1525 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(this))->announceDescriptionChange();
1530 void KItemListView::slotSelectionChanged(const KItemSet
¤t
, const KItemSet
&previous
)
1532 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1533 while (it
.hasNext()) {
1535 const int index
= it
.key();
1536 KItemListWidget
*widget
= it
.value();
1537 const bool isSelected(current
.contains(index
));
1538 widget
->setSelected(isSelected
);
1540 #ifndef QT_NO_ACCESSIBILITY
1541 if (!QAccessible::isActive()) {
1544 // Let the screen reader announce "selected" or "not selected" for the active item.
1545 const bool wasSelected(previous
.contains(index
));
1546 if (isSelected
!= wasSelected
) {
1547 QAccessibleEvent
accessibleSelectionChangedEvent(this, QAccessible::Selection
);
1548 accessibleSelectionChangedEvent
.setChild(index
);
1549 QAccessible::updateAccessibility(&accessibleSelectionChangedEvent
);
1552 // Usually the below does not have an effect because the view will not have focus at this moment but one of its list items. Still we announce the
1553 // change of the accessibility description just in case the user manually moved focus up by one.
1554 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(this))->announceDescriptionChange();
1561 void KItemListView::slotAnimationFinished(QGraphicsWidget
*widget
, KItemListViewAnimation::AnimationType type
)
1563 KItemListWidget
*itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1564 Q_ASSERT(itemListWidget
);
1566 if (type
== KItemListViewAnimation::DeleteAnimation
) {
1567 // As we recycle the widget in this case it is important to assure that no
1568 // other animation has been started. This is a convention in KItemListView and
1569 // not a requirement defined by KItemListViewAnimation.
1570 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1572 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1573 // by m_visibleWidgets and must be deleted manually after the animation has
1575 recycleGroupHeaderForWidget(itemListWidget
);
1576 widgetCreator()->recycle(itemListWidget
);
1578 const int index
= itemListWidget
->index();
1579 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) || (index
> m_layouter
->lastVisibleIndex());
1580 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1581 recycleWidget(itemListWidget
);
1586 void KItemListView::slotRubberBandPosChanged()
1591 void KItemListView::slotRubberBandActivationChanged(bool active
)
1594 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1595 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1596 m_skipAutoScrollForRubberBand
= true;
1598 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(), m_rubberBand
->endPosition()).normalized();
1600 auto animation
= new QVariantAnimation(this);
1601 animation
->setStartValue(1.0);
1602 animation
->setEndValue(0.0);
1603 animation
->setDuration(RubberFadeSpeed
);
1604 animation
->setProperty(RubberPropertyName
, rubberBandRect
);
1607 curve
.setType(QEasingCurve::BezierSpline
);
1608 curve
.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1609 animation
->setEasingCurve(curve
);
1611 connect(animation
, &QVariantAnimation::valueChanged
, this, [=](const QVariant
&) {
1614 connect(animation
, &QVariantAnimation::finished
, this, [=]() {
1615 m_rubberBandAnimations
.removeAll(animation
);
1619 m_rubberBandAnimations
<< animation
;
1621 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1622 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1623 m_skipAutoScrollForRubberBand
= false;
1629 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
&role
, qreal currentWidth
, qreal previousWidth
)
1632 Q_UNUSED(currentWidth
)
1633 Q_UNUSED(previousWidth
)
1635 m_headerWidget
->setAutomaticColumnResizing(false);
1636 applyColumnWidthsFromHeader();
1637 doLayout(NoAnimation
);
1640 void KItemListView::slotSidePaddingChanged(qreal width
)
1643 if (m_headerWidget
->automaticColumnResizing()) {
1644 applyAutomaticColumnWidths();
1646 applyColumnWidthsFromHeader();
1647 doLayout(NoAnimation
);
1650 void KItemListView::slotHeaderColumnMoved(const QByteArray
&role
, int currentIndex
, int previousIndex
)
1652 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1654 const QList
<QByteArray
> previous
= m_visibleRoles
;
1656 QList
<QByteArray
> current
= m_visibleRoles
;
1657 current
.removeAt(previousIndex
);
1658 current
.insert(currentIndex
, role
);
1660 setVisibleRoles(current
);
1662 Q_EMIT
visibleRolesChanged(current
, previous
);
1665 void KItemListView::triggerAutoScrolling()
1667 if (!m_autoScrollTimer
) {
1672 int visibleSize
= 0;
1673 if (scrollOrientation() == Qt::Vertical
) {
1674 pos
= m_mousePos
.y();
1675 visibleSize
= size().height();
1677 pos
= m_mousePos
.x();
1678 visibleSize
= size().width();
1681 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1682 m_autoScrollIncrement
= 0;
1685 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1686 if (m_autoScrollIncrement
== 0) {
1687 // The mouse position is not above an autoscroll margin (the autoscroll timer
1688 // will be restarted in mouseMoveEvent())
1689 m_autoScrollTimer
->stop();
1693 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1694 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1695 // if the direction of the rubberband is similar to the autoscroll direction. This
1696 // prevents that starting to create a rubberband within the autoscroll margins starts
1697 // an autoscrolling.
1699 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1700 const qreal diff
= (scrollOrientation() == Qt::Vertical
) ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1701 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1702 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1703 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1704 // been moved up although the autoscroll direction might be down)
1705 m_autoScrollTimer
->stop();
1710 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1711 // the autoscrolling may not get skipped anymore until a new rubberband is created
1712 m_skipAutoScrollForRubberBand
= false;
1714 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1715 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1716 setScrollOffset(newScrollOffset
);
1718 // Trigger the autoscroll timer which will periodically call
1719 // triggerAutoScrolling()
1720 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1723 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1725 KItemListWidget
*widget
= qobject_cast
<KItemListWidget
*>(sender());
1727 KItemListGroupHeader
*groupHeader
= m_visibleGroups
.value(widget
);
1728 Q_ASSERT(groupHeader
);
1729 updateGroupHeaderLayout(widget
);
1732 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
&role
, const QVariant
&value
)
1734 disconnectRoleEditingSignals(index
);
1736 m_editingRole
= false;
1737 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1740 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
&role
, const QVariant
&value
)
1742 disconnectRoleEditingSignals(index
);
1744 m_editingRole
= false;
1745 Q_EMIT
roleEditingFinished(index
, role
, value
);
1748 void KItemListView::setController(KItemListController
*controller
)
1750 if (m_controller
!= controller
) {
1751 KItemListController
*previous
= m_controller
;
1753 KItemListSelectionManager
*selectionManager
= previous
->selectionManager();
1754 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1755 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1758 m_controller
= controller
;
1761 KItemListSelectionManager
*selectionManager
= controller
->selectionManager();
1762 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1763 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1766 onControllerChanged(controller
, previous
);
1770 void KItemListView::setModel(KItemModelBase
*model
)
1772 if (m_model
== model
) {
1776 KItemModelBase
*previous
= m_model
;
1779 disconnect(m_model
, &KItemModelBase::itemsChanged
, this, &KItemListView::slotItemsChanged
);
1780 disconnect(m_model
, &KItemModelBase::itemsInserted
, this, &KItemListView::slotItemsInserted
);
1781 disconnect(m_model
, &KItemModelBase::itemsRemoved
, this, &KItemListView::slotItemsRemoved
);
1782 disconnect(m_model
, &KItemModelBase::itemsMoved
, this, &KItemListView::slotItemsMoved
);
1783 disconnect(m_model
, &KItemModelBase::groupsChanged
, this, &KItemListView::slotGroupsChanged
);
1784 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
, this, &KItemListView::slotGroupedSortingChanged
);
1785 disconnect(m_model
, &KItemModelBase::sortOrderChanged
, this, &KItemListView::slotSortOrderChanged
);
1786 disconnect(m_model
, &KItemModelBase::sortRoleChanged
, this, &KItemListView::slotSortRoleChanged
);
1788 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1792 m_layouter
->setModel(model
);
1793 m_grouped
= model
->groupedSorting();
1796 connect(m_model
, &KItemModelBase::itemsChanged
, this, &KItemListView::slotItemsChanged
);
1797 connect(m_model
, &KItemModelBase::itemsInserted
, this, &KItemListView::slotItemsInserted
);
1798 connect(m_model
, &KItemModelBase::itemsRemoved
, this, &KItemListView::slotItemsRemoved
);
1799 connect(m_model
, &KItemModelBase::itemsMoved
, this, &KItemListView::slotItemsMoved
);
1800 connect(m_model
, &KItemModelBase::groupsChanged
, this, &KItemListView::slotGroupsChanged
);
1801 connect(m_model
, &KItemModelBase::groupedSortingChanged
, this, &KItemListView::slotGroupedSortingChanged
);
1802 connect(m_model
, &KItemModelBase::sortOrderChanged
, this, &KItemListView::slotSortOrderChanged
);
1803 connect(m_model
, &KItemModelBase::sortRoleChanged
, this, &KItemListView::slotSortRoleChanged
);
1805 const int itemCount
= m_model
->count();
1806 if (itemCount
> 0) {
1807 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1811 onModelChanged(model
, previous
);
1814 KItemListRubberBand
*KItemListView::rubberBand() const
1816 return m_rubberBand
;
1819 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1821 if (m_activeTransactions
> 0) {
1822 if (hint
== NoAnimation
) {
1823 // As soon as at least one property change should be done without animation,
1824 // the whole transaction will be marked as not animated.
1825 m_endTransactionAnimationHint
= NoAnimation
;
1830 if (!m_model
|| m_model
->count() < 0) {
1834 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1835 if (firstVisibleIndex
< 0) {
1836 emitOffsetChanges();
1840 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1841 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1842 // is still shown if the maximum offset got decreased.
1843 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1844 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1845 if (scrollOffset() > maxOffsetToShowFullRange
) {
1846 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1847 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1850 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1852 int firstSibblingIndex
= -1;
1853 int lastSibblingIndex
= -1;
1854 const bool supportsExpanding
= supportsItemExpanding();
1856 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1858 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1859 // instances from invisible items are reused. If no reusable items are
1860 // found then new KItemListWidget instances get created.
1861 const bool animate
= (hint
== Animation
);
1862 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1863 bool applyNewPos
= true;
1865 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1866 const QPointF newPos
= itemBounds
.topLeft();
1867 KItemListWidget
*widget
= m_visibleItems
.value(i
);
1869 if (!reusableItems
.isEmpty()) {
1870 // Reuse a KItemListWidget instance from an invisible item
1871 const int oldIndex
= reusableItems
.takeLast();
1872 widget
= m_visibleItems
.value(oldIndex
);
1873 setWidgetIndex(widget
, i
);
1874 updateWidgetProperties(widget
, i
);
1875 initializeItemListWidget(widget
);
1877 // No reusable KItemListWidget instance is available, create a new one
1878 widget
= createWidget(i
);
1880 widget
->resize(itemBounds
.size());
1882 if (animate
&& changedCount
< 0) {
1883 // Items have been deleted.
1884 if (i
>= changedIndex
) {
1885 // The item is located behind the removed range. Move the
1886 // created item to the imaginary old position outside the
1887 // view. It will get animated to the new position later.
1888 const int previousIndex
= i
- changedCount
;
1889 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1890 if (itemRect
.isEmpty()) {
1891 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
) ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1892 widget
->setPos(invisibleOldPos
);
1894 widget
->setPos(itemRect
.topLeft());
1896 applyNewPos
= false;
1900 if (supportsExpanding
&& changedCount
== 0) {
1901 if (firstSibblingIndex
< 0) {
1902 firstSibblingIndex
= i
;
1904 lastSibblingIndex
= i
;
1909 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1910 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1911 applyNewPos
= false;
1914 const bool itemsRemoved
= (changedCount
< 0);
1915 const bool itemsInserted
= (changedCount
> 0);
1916 if (itemsRemoved
&& (i
>= changedIndex
)) {
1917 // The item is located after the removed items. Animate the moving of the position.
1918 applyNewPos
= !moveWidget(widget
, newPos
);
1919 } else if (itemsInserted
&& i
>= changedIndex
) {
1920 // The item is located after the first inserted item
1921 if (i
<= changedIndex
+ changedCount
- 1) {
1922 // The item is an inserted item. Animate the appearing of the item.
1923 // For performance reasons no animation is done when changedCount is equal
1924 // to all available items.
1925 if (changedCount
< m_model
->count()) {
1926 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1928 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1929 // The item was already there before, so animate the moving of the position.
1930 // No moving animation is done if the item is animated by a create animation: This
1931 // prevents a "move animation mess" when inserting several ranges in parallel.
1932 applyNewPos
= !moveWidget(widget
, newPos
);
1936 m_animation
->stop(widget
);
1940 widget
->setPos(newPos
);
1943 Q_ASSERT(widget
->index() == i
);
1944 widget
->setVisible(true);
1946 bool animateIconResizing
= animate
;
1948 if (widget
->size() != itemBounds
.size()) {
1949 // Resize the widget for the item to the changed size.
1951 // If a dynamic item size is used then no animation is done in the direction
1952 // of the dynamic size.
1953 if (m_itemSize
.width() <= 0) {
1954 // The width is dynamic, apply the new width without animation.
1955 widget
->resize(itemBounds
.width(), widget
->size().height());
1956 } else if (m_itemSize
.height() <= 0) {
1957 // The height is dynamic, apply the new height without animation.
1958 widget
->resize(widget
->size().width(), itemBounds
.height());
1960 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1962 widget
->resize(itemBounds
.size());
1965 animateIconResizing
= false;
1968 const int newIconSize
= widget
->styleOption().iconSize
;
1969 if (widget
->iconSize() != newIconSize
) {
1970 if (animateIconResizing
) {
1971 m_animation
->start(widget
, KItemListViewAnimation::IconResizeAnimation
, newIconSize
);
1973 widget
->setIconSize(newIconSize
);
1977 // Updating the cell-information must be done as last step: The decision whether the
1978 // moving-animation should be started at all is based on the previous cell-information.
1979 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1980 m_visibleCells
.insert(i
, cell
);
1983 // Delete invisible KItemListWidget instances that have not been reused
1984 for (int index
: std::as_const(reusableItems
)) {
1985 recycleWidget(m_visibleItems
.value(index
));
1988 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1989 Q_ASSERT(lastSibblingIndex
>= 0);
1990 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1994 // Update the layout of all visible group headers
1995 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1996 while (it
.hasNext()) {
1998 updateGroupHeaderLayout(it
.key());
2002 emitOffsetChanges();
2005 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
, int lastVisibleIndex
, LayoutAnimationHint hint
)
2007 // Determine all items that are completely invisible and might be
2008 // reused for items that just got (at least partly) visible. If the
2009 // animation hint is set to 'Animation' items that do e.g. an animated
2010 // moving of their position are not marked as invisible: This assures
2011 // that a scrolling inside the view can be done without breaking an animation.
2015 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2016 while (it
.hasNext()) {
2019 KItemListWidget
*widget
= it
.value();
2020 const int index
= widget
->index();
2021 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
2024 if (m_animation
->isStarted(widget
)) {
2025 if (hint
== NoAnimation
) {
2026 // Stopping the animation will call KItemListView::slotAnimationFinished()
2027 // and the widget will be recycled if necessary there.
2028 m_animation
->stop(widget
);
2031 widget
->setVisible(false);
2032 items
.append(index
);
2035 recycleGroupHeaderForWidget(widget
);
2044 bool KItemListView::moveWidget(KItemListWidget
*widget
, const QPointF
&newPos
)
2046 if (widget
->pos() == newPos
) {
2050 bool startMovingAnim
= false;
2052 if (m_itemSize
.isEmpty()) {
2053 // The items are not aligned in a grid but either as columns or rows.
2054 startMovingAnim
= true;
2056 // When having a grid the moving-animation should only be started, if it is done within
2057 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
2058 // Otherwise instead of a moving-animation a create-animation on the new position will be used
2059 // instead. This is done to prevent overlapping (and confusing) moving-animations.
2060 const int index
= widget
->index();
2061 const Cell cell
= m_visibleCells
.value(index
);
2062 if (cell
.column
>= 0 && cell
.row
>= 0) {
2063 if (scrollOrientation() == Qt::Vertical
) {
2064 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
2066 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
2071 if (startMovingAnim
) {
2072 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
2076 m_animation
->stop(widget
);
2077 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
2081 void KItemListView::emitOffsetChanges()
2083 const qreal newScrollOffset
= m_layouter
->scrollOffset();
2084 if (m_oldScrollOffset
!= newScrollOffset
) {
2085 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
2086 m_oldScrollOffset
= newScrollOffset
;
2089 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
2090 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
2091 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
2092 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
2095 const qreal newItemOffset
= m_layouter
->itemOffset();
2096 if (m_oldItemOffset
!= newItemOffset
) {
2097 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
2098 m_oldItemOffset
= newItemOffset
;
2101 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
2102 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
2103 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
2104 m_oldMaximumItemOffset
= newMaximumItemOffset
;
2108 KItemListWidget
*KItemListView::createWidget(int index
)
2110 KItemListWidget
*widget
= widgetCreator()->create(this);
2111 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
2113 m_visibleItems
.insert(index
, widget
);
2114 m_visibleCells
.insert(index
, Cell());
2115 updateWidgetProperties(widget
, index
);
2116 initializeItemListWidget(widget
);
2120 void KItemListView::recycleWidget(KItemListWidget
*widget
)
2123 recycleGroupHeaderForWidget(widget
);
2126 const int index
= widget
->index();
2127 m_visibleItems
.remove(index
);
2128 m_visibleCells
.remove(index
);
2130 widgetCreator()->recycle(widget
);
2133 void KItemListView::setWidgetIndex(KItemListWidget
*widget
, int index
)
2135 const int oldIndex
= widget
->index();
2136 m_visibleItems
.remove(oldIndex
);
2137 m_visibleCells
.remove(oldIndex
);
2139 m_visibleItems
.insert(index
, widget
);
2140 m_visibleCells
.insert(index
, Cell());
2142 widget
->setIndex(index
);
2145 void KItemListView::moveWidgetToIndex(KItemListWidget
*widget
, int index
)
2147 const int oldIndex
= widget
->index();
2148 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
2150 setWidgetIndex(widget
, index
);
2152 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2153 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2154 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) || (!vertical
&& oldCell
.column
== newCell
.column
);
2156 m_visibleCells
.insert(index
, newCell
);
2160 void KItemListView::setLayouterSize(const QSizeF
&size
, SizeType sizeType
)
2164 m_layouter
->setSize(size
);
2167 m_layouter
->setItemSize(size
);
2174 void KItemListView::updateWidgetProperties(KItemListWidget
*widget
, int index
)
2176 widget
->setVisibleRoles(m_visibleRoles
);
2177 updateWidgetColumnWidths(widget
);
2178 widget
->setStyleOption(m_styleOption
);
2180 const KItemListSelectionManager
*selectionManager
= m_controller
->selectionManager();
2182 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2183 // always the selected item. It is not necessary to highlight the current item then.
2184 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2185 widget
->setCurrent(index
== selectionManager
->currentItem());
2187 widget
->setSelected(selectionManager
->isSelected(index
));
2188 widget
->setHovered(false);
2189 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2190 widget
->setIndex(index
);
2191 widget
->setData(m_model
->data(index
));
2192 widget
->setSiblingsInformation(QBitArray());
2193 updateAlternateBackgroundForWidget(widget
);
2196 updateGroupHeaderForWidget(widget
);
2200 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
*widget
)
2202 Q_ASSERT(m_grouped
);
2204 const int index
= widget
->index();
2205 if (!m_layouter
->isFirstGroupItem(index
)) {
2206 // The widget does not represent the first item of a group
2207 // and hence requires no header
2208 recycleGroupHeaderForWidget(widget
);
2212 const QList
<QPair
<int, QVariant
>> groups
= model()->groups();
2213 if (groups
.isEmpty() || !groupHeaderCreator()) {
2217 KItemListGroupHeader
*groupHeader
= m_visibleGroups
.value(widget
);
2219 groupHeader
= groupHeaderCreator()->create(this);
2220 groupHeader
->setParentItem(widget
);
2221 m_visibleGroups
.insert(widget
, groupHeader
);
2222 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2224 Q_ASSERT(groupHeader
->parentItem() == widget
);
2226 const int groupIndex
= groupIndexForItem(index
);
2227 Q_ASSERT(groupIndex
>= 0);
2228 groupHeader
->setData(groups
.at(groupIndex
).second
);
2229 groupHeader
->setRole(model()->sortRole());
2230 groupHeader
->setStyleOption(m_styleOption
);
2231 groupHeader
->setScrollOrientation(scrollOrientation());
2232 groupHeader
->setItemIndex(index
);
2234 groupHeader
->show();
2237 void KItemListView::updateGroupHeaderLayout(KItemListWidget
*widget
)
2239 KItemListGroupHeader
*groupHeader
= m_visibleGroups
.value(widget
);
2240 Q_ASSERT(groupHeader
);
2242 const int index
= widget
->index();
2243 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2244 const QRectF itemRect
= m_layouter
->itemRect(index
);
2246 // The group-header is a child of the itemlist widget. Translate the
2247 // group header position to the relative position.
2248 if (scrollOrientation() == Qt::Vertical
) {
2249 // In the vertical scroll orientation the group header should always span
2250 // the whole width no matter which temporary position the parent widget
2251 // has. In this case the x-position and width will be adjusted manually.
2252 const qreal x
= -widget
->x() - itemOffset();
2253 const qreal width
= maximumItemOffset();
2254 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2255 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2257 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2258 groupHeader
->resize(groupHeaderRect
.size());
2262 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
*widget
)
2264 KItemListGroupHeader
*header
= m_visibleGroups
.value(widget
);
2266 header
->setParentItem(nullptr);
2267 groupHeaderCreator()->recycle(header
);
2268 m_visibleGroups
.remove(widget
);
2269 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2273 void KItemListView::updateVisibleGroupHeaders()
2275 Q_ASSERT(m_grouped
);
2276 m_layouter
->markAsDirty();
2278 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2279 while (it
.hasNext()) {
2281 updateGroupHeaderForWidget(it
.value());
2285 int KItemListView::groupIndexForItem(int index
) const
2287 Q_ASSERT(m_grouped
);
2289 const QList
<QPair
<int, QVariant
>> groups
= model()->groups();
2290 if (groups
.isEmpty()) {
2295 int max
= groups
.count() - 1;
2298 mid
= (min
+ max
) / 2;
2299 if (index
> groups
[mid
].first
) {
2304 } while (groups
[mid
].first
!= index
&& min
<= max
);
2307 while (groups
[mid
].first
> index
&& mid
> 0) {
2315 void KItemListView::updateAlternateBackgrounds()
2317 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2318 while (it
.hasNext()) {
2320 updateAlternateBackgroundForWidget(it
.value());
2324 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
*widget
)
2326 bool enabled
= useAlternateBackgrounds();
2328 const int index
= widget
->index();
2329 enabled
= (index
& 0x1) > 0;
2331 const int groupIndex
= groupIndexForItem(index
);
2332 if (groupIndex
>= 0) {
2333 const QList
<QPair
<int, QVariant
>> groups
= model()->groups();
2334 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2335 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2336 enabled
= (relativeIndex
& 0x1) > 0;
2340 widget
->setAlternateBackground(enabled
);
2343 bool KItemListView::useAlternateBackgrounds() const
2345 return m_alternateBackgrounds
&& m_itemSize
.isEmpty();
2348 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
&itemRanges
) const
2350 QElapsedTimer timer
;
2353 QHash
<QByteArray
, qreal
> widths
;
2355 // Calculate the minimum width for each column that is required
2356 // to show the headline unclipped.
2357 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2358 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2359 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2360 for (const QByteArray
&visibleRole
: std::as_const(m_visibleRoles
)) {
2361 const QString headerText
= m_model
->roleDescription(visibleRole
);
2362 const qreal headerWidth
= fontMetrics
.horizontalAdvance(headerText
) + gripMargin
+ headerMargin
* 2;
2363 widths
.insert(visibleRole
, headerWidth
);
2366 // Calculate the preferred column widths for each item and ignore values
2367 // smaller than the width for showing the headline unclipped.
2368 const KItemListWidgetCreatorBase
*creator
= widgetCreator();
2369 int calculatedItemCount
= 0;
2370 bool maxTimeExceeded
= false;
2371 for (const KItemRange
&itemRange
: itemRanges
) {
2372 const int startIndex
= itemRange
.index
;
2373 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2375 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2376 for (const QByteArray
&visibleRole
: std::as_const(m_visibleRoles
)) {
2377 qreal maxWidth
= widths
.value(visibleRole
, 0);
2378 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2379 maxWidth
= qMax(width
, maxWidth
);
2380 widths
.insert(visibleRole
, maxWidth
);
2383 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2384 // When having several thousands of items calculating the sizes can get
2385 // very expensive. We accept a possibly too small role-size in favour
2386 // of having no blocking user interface.
2387 maxTimeExceeded
= true;
2390 ++calculatedItemCount
;
2392 if (maxTimeExceeded
) {
2400 void KItemListView::applyColumnWidthsFromHeader()
2402 // Apply the new size to the layouter
2403 const qreal requiredWidth
= columnWidthsSum() + 2 * m_headerWidget
->sidePadding();
2404 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
), m_itemSize
.height());
2405 m_layouter
->setItemSize(dynamicItemSize
);
2407 // Update the role sizes for all visible widgets
2408 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2409 while (it
.hasNext()) {
2411 updateWidgetColumnWidths(it
.value());
2415 void KItemListView::updateWidgetColumnWidths(KItemListWidget
*widget
)
2417 for (const QByteArray
&role
: std::as_const(m_visibleRoles
)) {
2418 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2420 widget
->setSidePadding(m_headerWidget
->sidePadding());
2423 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
&itemRanges
)
2425 Q_ASSERT(m_itemSize
.isEmpty());
2426 const int itemCount
= m_model
->count();
2427 int rangesItemCount
= 0;
2428 for (const KItemRange
&range
: itemRanges
) {
2429 rangesItemCount
+= range
.count
;
2432 if (itemCount
== rangesItemCount
) {
2433 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2434 for (const QByteArray
&role
: std::as_const(m_visibleRoles
)) {
2435 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2438 // Only a sub range of the roles need to be determined.
2439 // The chances are good that the widths of the sub ranges
2440 // already fit into the available widths and hence no
2441 // expensive update might be required.
2442 bool changed
= false;
2444 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2445 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2446 while (it
.hasNext()) {
2448 const QByteArray
&role
= it
.key();
2449 const qreal updatedWidth
= it
.value();
2450 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2451 if (updatedWidth
> currentWidth
) {
2452 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2458 // All the updated sizes are smaller than the current sizes and no change
2459 // of the stretched roles-widths is required
2464 if (m_headerWidget
->automaticColumnResizing()) {
2465 applyAutomaticColumnWidths();
2469 void KItemListView::updatePreferredColumnWidths()
2472 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2476 void KItemListView::applyAutomaticColumnWidths()
2478 Q_ASSERT(m_itemSize
.isEmpty());
2479 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2480 if (m_visibleRoles
.isEmpty()) {
2484 // Calculate the maximum size of an item by considering the
2485 // visible role sizes and apply them to the layouter. If the
2486 // size does not use the available view-size the size of the
2487 // first role will get stretched.
2489 for (const QByteArray
&role
: std::as_const(m_visibleRoles
)) {
2490 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2491 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2494 const QByteArray firstRole
= m_visibleRoles
.first();
2495 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2496 QSizeF dynamicItemSize
= m_itemSize
;
2498 qreal requiredWidth
= columnWidthsSum() + 2 * m_headerWidget
->sidePadding(); // Adding the padding a second time so we have the same padding
2499 // symmetrically on both sides of the view. This improves UX, looks better and increases the chances of users figuring out that the padding
2500 // area can be used for deselecting and dropping files.
2501 const qreal availableWidth
= size().width();
2502 if (requiredWidth
< availableWidth
) {
2503 // Stretch the first column to use the whole remaining width
2504 firstColumnWidth
+= availableWidth
- requiredWidth
;
2505 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2506 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2507 // Shrink the first column to be able to show as much other
2508 // columns as possible
2509 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2511 // TODO: A proper calculation of the minimum width depends on the implementation
2512 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2514 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2515 if (shrinkedFirstColumnWidth
< minWidth
) {
2516 shrinkedFirstColumnWidth
= minWidth
;
2519 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2520 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2523 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2525 m_layouter
->setItemSize(dynamicItemSize
);
2527 // Update the role sizes for all visible widgets
2528 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2529 while (it
.hasNext()) {
2531 updateWidgetColumnWidths(it
.value());
2535 qreal
KItemListView::columnWidthsSum() const
2537 qreal widthsSum
= 0;
2538 for (const QByteArray
&role
: std::as_const(m_visibleRoles
)) {
2539 widthsSum
+= m_headerWidget
->columnWidth(role
);
2544 QRectF
KItemListView::headerBoundaries() const
2546 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2549 bool KItemListView::changesItemGridLayout(const QSizeF
&newGridSize
, const QSizeF
&newItemSize
, const QSizeF
&newItemMargin
) const
2551 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2555 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2556 const qreal itemWidth
= m_layouter
->itemSize().width();
2557 if (itemWidth
> 0) {
2558 const int newColumnCount
= itemsPerSize(newGridSize
.width(), newItemSize
.width(), newItemMargin
.width());
2559 if (m_model
->count() > newColumnCount
) {
2560 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(), itemWidth
, m_layouter
->itemMargin().width());
2561 return oldColumnCount
!= newColumnCount
;
2565 const qreal itemHeight
= m_layouter
->itemSize().height();
2566 if (itemHeight
> 0) {
2567 const int newRowCount
= itemsPerSize(newGridSize
.height(), newItemSize
.height(), newItemMargin
.height());
2568 if (m_model
->count() > newRowCount
) {
2569 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(), itemHeight
, m_layouter
->itemMargin().height());
2570 return oldRowCount
!= newRowCount
;
2578 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2580 if (m_itemSize
.isEmpty()) {
2581 // We have only columns or only rows, but no grid: An animation is usually
2582 // welcome when inserting or removing items.
2583 return !supportsItemExpanding();
2586 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2590 const int maximum
= (scrollOrientation() == Qt::Vertical
) ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2591 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2592 // Only animate if up to 2/3 of a row or column are inserted or removed
2593 return changedItemCount
<= maximum
* 2 / 3;
2596 bool KItemListView::scrollBarRequired(const QSizeF
&size
) const
2598 const QSizeF oldSize
= m_layouter
->size();
2600 m_layouter
->setSize(size
);
2601 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2602 m_layouter
->setSize(oldSize
);
2604 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height() : maxOffset
> size
.width();
2607 int KItemListView::showDropIndicator(const QPointF
&pos
)
2609 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2610 while (it
.hasNext()) {
2612 const KItemListWidget
*widget
= it
.value();
2614 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2615 const QRectF rect
= itemRect(widget
->index());
2616 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2617 if (m_model
->supportsDropping(widget
->index())) {
2618 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2619 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2620 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2625 const bool isAboveItem
= (mappedPos
.y() < rect
.height() / 2);
2626 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2628 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2629 if (m_dropIndicator
!= draggingInsertIndicator
) {
2630 m_dropIndicator
= draggingInsertIndicator
;
2634 int index
= widget
->index();
2642 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2643 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2646 void KItemListView::hideDropIndicator()
2648 if (!m_dropIndicator
.isNull()) {
2649 m_dropIndicator
= QRectF();
2654 void KItemListView::updateGroupHeaderHeight()
2656 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2657 qreal groupHeaderMargin
= 0;
2659 if (scrollOrientation() == Qt::Horizontal
) {
2660 // The vertical margin above and below the header should be
2661 // equal to the horizontal margin, not the vertical margin
2662 // from m_styleOption.
2663 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2664 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2665 } else if (m_itemSize
.isEmpty()) {
2666 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2667 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2669 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2670 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2672 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2673 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2675 updateVisibleGroupHeaders();
2678 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2680 if (!supportsItemExpanding() || !m_model
) {
2684 if (firstIndex
< 0 || lastIndex
< 0) {
2685 firstIndex
= m_layouter
->firstVisibleIndex();
2686 lastIndex
= m_layouter
->lastVisibleIndex();
2688 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() && lastIndex
>= m_layouter
->firstVisibleIndex());
2689 if (!isRangeVisible
) {
2694 int previousParents
= 0;
2695 QBitArray previousSiblings
;
2697 // The rootIndex describes the first index where the siblings get
2698 // calculated from. For the calculation the upper most parent item
2699 // is required. For performance reasons it is checked first whether
2700 // the visible items before or after the current range already
2701 // contain a siblings information which can be used as base.
2702 int rootIndex
= firstIndex
;
2704 KItemListWidget
*widget
= m_visibleItems
.value(firstIndex
- 1);
2706 // There is no visible widget before the range, check whether there
2707 // is one after the range:
2708 widget
= m_visibleItems
.value(lastIndex
+ 1);
2710 // The sibling information of the widget may only be used if
2711 // all items of the range have the same number of parents.
2712 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2713 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2714 if (m_model
->expandedParentsCount(i
) != parents
) {
2723 // Performance optimization: Use the sibling information of the visible
2724 // widget beside the given range.
2725 previousSiblings
= widget
->siblingsInformation();
2726 if (previousSiblings
.isEmpty()) {
2729 previousParents
= previousSiblings
.count() - 1;
2730 previousSiblings
.truncate(previousParents
);
2732 // Potentially slow path: Go back to the upper most parent of firstIndex
2733 // to be able to calculate the initial value for the siblings.
2734 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2739 Q_ASSERT(previousParents
>= 0);
2740 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2741 // Update the parent-siblings in case if the current item represents
2742 // a child or an upper parent.
2743 const int currentParents
= m_model
->expandedParentsCount(i
);
2744 Q_ASSERT(currentParents
>= 0);
2745 if (previousParents
< currentParents
) {
2746 previousParents
= currentParents
;
2747 previousSiblings
.resize(currentParents
);
2748 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2749 } else if (previousParents
> currentParents
) {
2750 previousParents
= currentParents
;
2751 previousSiblings
.truncate(currentParents
);
2754 if (i
>= firstIndex
) {
2755 // The index represents a visible item. Apply the parent-siblings
2756 // and update the sibling of the current item.
2757 KItemListWidget
*widget
= m_visibleItems
.value(i
);
2762 QBitArray siblings
= previousSiblings
;
2763 siblings
.resize(siblings
.count() + 1);
2764 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2766 widget
->setSiblingsInformation(siblings
);
2771 bool KItemListView::hasSiblingSuccessor(int index
) const
2773 bool hasSuccessor
= false;
2774 const int parentsCount
= m_model
->expandedParentsCount(index
);
2775 int successorIndex
= index
+ 1;
2777 // Search the next sibling
2778 const int itemCount
= m_model
->count();
2779 while (successorIndex
< itemCount
) {
2780 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2781 if (currentParentsCount
== parentsCount
) {
2782 hasSuccessor
= true;
2784 } else if (currentParentsCount
< parentsCount
) {
2790 if (m_grouped
&& hasSuccessor
) {
2791 // If the sibling is part of another group, don't mark it as
2792 // successor as the group header is between the sibling connections.
2793 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2794 if (m_layouter
->isFirstGroupItem(i
)) {
2795 hasSuccessor
= false;
2801 return hasSuccessor
;
2804 void KItemListView::disconnectRoleEditingSignals(int index
)
2806 KStandardItemListWidget
*widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2811 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2812 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2813 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2816 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2820 const int minSpeed
= 4;
2821 const int maxSpeed
= 128;
2822 const int speedLimiter
= 96;
2823 const int autoScrollBorder
= 64;
2825 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2826 // This assures that the autoscrolling speed grows gradually.
2827 const int incLimiter
= 1;
2829 if (pos
< autoScrollBorder
) {
2830 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2831 inc
= qMax(inc
, -maxSpeed
);
2832 inc
= qMax(inc
, oldInc
- incLimiter
);
2833 } else if (pos
> range
- autoScrollBorder
) {
2834 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2835 inc
= qMin(inc
, maxSpeed
);
2836 inc
= qMin(inc
, oldInc
+ incLimiter
);
2842 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2844 const qreal availableSize
= size
- itemMargin
;
2845 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2849 KItemListCreatorBase::~KItemListCreatorBase()
2851 qDeleteAll(m_recycleableWidgets
);
2852 qDeleteAll(m_createdWidgets
);
2855 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
*widget
)
2857 m_createdWidgets
.insert(widget
);
2860 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
*widget
)
2862 Q_ASSERT(m_createdWidgets
.contains(widget
));
2863 m_createdWidgets
.remove(widget
);
2865 if (m_recycleableWidgets
.count() < 100) {
2866 m_recycleableWidgets
.append(widget
);
2867 widget
->setVisible(false);
2873 QGraphicsWidget
*KItemListCreatorBase::popRecycleableWidget()
2875 if (m_recycleableWidgets
.isEmpty()) {
2879 QGraphicsWidget
*widget
= m_recycleableWidgets
.takeLast();
2880 m_createdWidgets
.insert(widget
);
2884 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2888 void KItemListWidgetCreatorBase::recycle(KItemListWidget
*widget
)
2890 widget
->setParentItem(nullptr);
2891 widget
->setOpacity(1.0);
2892 pushRecycleableWidget(widget
);
2895 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2899 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
*header
)
2901 header
->setOpacity(1.0);
2902 pushRecycleableWidget(header
);
2905 #include "moc_kitemlistview.cpp"