2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
4 * Based on the Itemviews NG project from Trolltech Labs
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kitemlistview.h"
11 #include "dolphindebug.h"
12 #include "kitemlistcontainer.h"
13 #include "kitemlistcontroller.h"
14 #include "kitemlistheader.h"
15 #include "kitemlistselectionmanager.h"
16 #include "kitemlistviewaccessible.h"
17 #include "kstandarditemlistwidget.h"
19 #include "private/kitemlistheaderwidget.h"
20 #include "private/kitemlistrubberband.h"
21 #include "private/kitemlistsizehintresolver.h"
22 #include "private/kitemlistviewlayouter.h"
24 #include <QElapsedTimer>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QGraphicsView>
27 #include <QPropertyAnimation>
28 #include <QStyleOptionRubberBand>
30 #include <QVariantAnimation>
34 // Time in ms until reaching the autoscroll margin triggers
35 // an initial autoscrolling
36 const int InitialAutoScrollDelay
= 700;
38 // Delay in ms for triggering the next autoscroll
39 const int RepeatingAutoScrollDelay
= 1000 / 60;
41 // Copied from the Kirigami.Units.shortDuration
42 const int RubberFadeSpeed
= 150;
44 const char* RubberPropertyName
= "_kitemviews_rubberBandPosition";
47 #ifndef QT_NO_ACCESSIBILITY
48 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
52 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
53 return new KItemListContainerAccessible(container
);
54 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
55 return new KItemListViewAccessible(view
);
62 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
63 QGraphicsWidget(parent
),
64 m_enabledSelectionToggles(false),
66 m_supportsItemExpanding(false),
68 m_activeTransactions(0),
69 m_endTransactionAnimationHint(Animation
),
71 m_controller(nullptr),
74 m_widgetCreator(nullptr),
75 m_groupHeaderCreator(nullptr),
80 m_sizeHintResolver(nullptr),
83 m_layoutTimer(nullptr),
85 m_oldMaximumScrollOffset(0),
87 m_oldMaximumItemOffset(0),
88 m_skipAutoScrollForRubberBand(false),
89 m_rubberBand(nullptr),
90 m_tapAndHoldIndicator(nullptr),
92 m_autoScrollIncrement(0),
93 m_autoScrollTimer(nullptr),
95 m_headerWidget(nullptr),
96 m_indicatorAnimation(nullptr),
99 setAcceptHoverEvents(true);
100 setAcceptTouchEvents(true);
102 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
104 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
106 m_animation
= new KItemListViewAnimation(this);
107 connect(m_animation
, &KItemListViewAnimation::finished
,
108 this, &KItemListView::slotAnimationFinished
);
110 m_layoutTimer
= new QTimer(this);
111 m_layoutTimer
->setInterval(300);
112 m_layoutTimer
->setSingleShot(true);
113 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
115 m_rubberBand
= new KItemListRubberBand(this);
116 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
118 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
119 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
120 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
122 m_indicatorAnimation
->setDuration(150);
123 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
124 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
125 m_indicatorAnimation
->start();
129 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
130 if (m_tapAndHoldIndicator
->isActive()) {
135 m_headerWidget
= new KItemListHeaderWidget(this);
136 m_headerWidget
->setVisible(false);
138 m_header
= new KItemListHeader(this);
140 #ifndef QT_NO_ACCESSIBILITY
141 QAccessible::installFactory(accessibleInterfaceFactory
);
146 KItemListView::~KItemListView()
148 // The group headers are children of the widgets created by
149 // widgetCreator(). So it is mandatory to delete the group headers
151 delete m_groupHeaderCreator
;
152 m_groupHeaderCreator
= nullptr;
154 delete m_widgetCreator
;
155 m_widgetCreator
= nullptr;
157 delete m_sizeHintResolver
;
158 m_sizeHintResolver
= nullptr;
161 void KItemListView::setScrollOffset(qreal offset
)
167 const qreal previousOffset
= m_layouter
->scrollOffset();
168 if (offset
== previousOffset
) {
172 m_layouter
->setScrollOffset(offset
);
173 m_animation
->setScrollOffset(offset
);
175 // Don't check whether the m_layoutTimer is active: Changing the
176 // scroll offset must always trigger a synchronous layout, otherwise
177 // the smooth-scrolling might get jerky.
178 doLayout(NoAnimation
);
179 onScrollOffsetChanged(offset
, previousOffset
);
182 qreal
KItemListView::scrollOffset() const
184 return m_layouter
->scrollOffset();
187 qreal
KItemListView::maximumScrollOffset() const
189 return m_layouter
->maximumScrollOffset();
192 void KItemListView::setItemOffset(qreal offset
)
194 if (m_layouter
->itemOffset() == offset
) {
198 m_layouter
->setItemOffset(offset
);
199 if (m_headerWidget
->isVisible()) {
200 m_headerWidget
->setOffset(offset
);
203 // Don't check whether the m_layoutTimer is active: Changing the
204 // item offset must always trigger a synchronous layout, otherwise
205 // the smooth-scrolling might get jerky.
206 doLayout(NoAnimation
);
209 qreal
KItemListView::itemOffset() const
211 return m_layouter
->itemOffset();
214 qreal
KItemListView::maximumItemOffset() const
216 return m_layouter
->maximumItemOffset();
219 int KItemListView::maximumVisibleItems() const
221 return m_layouter
->maximumVisibleItems();
224 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
226 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
227 m_visibleRoles
= roles
;
228 onVisibleRolesChanged(roles
, previousRoles
);
230 m_sizeHintResolver
->clearCache();
231 m_layouter
->markAsDirty();
233 if (m_itemSize
.isEmpty()) {
234 m_headerWidget
->setColumns(roles
);
235 updatePreferredColumnWidths();
236 if (!m_headerWidget
->automaticColumnResizing()) {
237 // The column-width of new roles are still 0. Apply the preferred
238 // column-width as default with.
239 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
240 if (m_headerWidget
->columnWidth(role
) == 0) {
241 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
242 m_headerWidget
->setColumnWidth(role
, width
);
246 applyColumnWidthsFromHeader();
250 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
251 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
252 (roles
.count() <= 1 && previousRoles
.count() > 1));
254 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
255 while (it
.hasNext()) {
257 KItemListWidget
* widget
= it
.value();
258 widget
->setVisibleRoles(roles
);
259 if (alternateBackgroundsChanged
) {
260 updateAlternateBackgroundForWidget(widget
);
264 doLayout(NoAnimation
);
267 QList
<QByteArray
> KItemListView::visibleRoles() const
269 return m_visibleRoles
;
272 void KItemListView::setAutoScroll(bool enabled
)
274 if (enabled
&& !m_autoScrollTimer
) {
275 m_autoScrollTimer
= new QTimer(this);
276 m_autoScrollTimer
->setSingleShot(true);
277 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
278 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
279 } else if (!enabled
&& m_autoScrollTimer
) {
280 delete m_autoScrollTimer
;
281 m_autoScrollTimer
= nullptr;
285 bool KItemListView::autoScroll() const
287 return m_autoScrollTimer
!= nullptr;
290 void KItemListView::setEnabledSelectionToggles(bool enabled
)
292 if (m_enabledSelectionToggles
!= enabled
) {
293 m_enabledSelectionToggles
= enabled
;
295 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
296 while (it
.hasNext()) {
298 it
.value()->setEnabledSelectionToggle(enabled
);
303 bool KItemListView::enabledSelectionToggles() const
305 return m_enabledSelectionToggles
;
308 KItemListController
* KItemListView::controller() const
313 KItemModelBase
* KItemListView::model() const
318 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
320 delete m_widgetCreator
;
321 m_widgetCreator
= widgetCreator
;
324 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
326 if (!m_widgetCreator
) {
327 m_widgetCreator
= defaultWidgetCreator();
329 return m_widgetCreator
;
332 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
334 delete m_groupHeaderCreator
;
335 m_groupHeaderCreator
= groupHeaderCreator
;
338 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
340 if (!m_groupHeaderCreator
) {
341 m_groupHeaderCreator
= defaultGroupHeaderCreator();
343 return m_groupHeaderCreator
;
346 QSizeF
KItemListView::itemSize() const
351 const KItemListStyleOption
& KItemListView::styleOption() const
353 return m_styleOption
;
356 void KItemListView::setGeometry(const QRectF
& rect
)
358 QGraphicsWidget::setGeometry(rect
);
364 const QSizeF newSize
= rect
.size();
365 if (m_itemSize
.isEmpty()) {
366 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
367 if (m_headerWidget
->automaticColumnResizing()) {
368 applyAutomaticColumnWidths();
370 const qreal requiredWidth
= columnWidthsSum();
371 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
372 m_itemSize
.height());
373 m_layouter
->setItemSize(dynamicItemSize
);
377 m_layouter
->setSize(newSize
);
378 // We don't animate the moving of the items here because
379 // it would look like the items are slow to find their position.
380 doLayout(NoAnimation
);
383 qreal
KItemListView::verticalPageStep() const
385 qreal headerHeight
= 0;
386 if (m_headerWidget
->isVisible()) {
387 headerHeight
= m_headerWidget
->size().height();
389 return size().height() - headerHeight
;
392 int KItemListView::itemAt(const QPointF
& pos
) const
394 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
395 while (it
.hasNext()) {
398 const KItemListWidget
* widget
= it
.value();
399 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
400 if (widget
->contains(mappedPos
)) {
408 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
410 if (!m_enabledSelectionToggles
) {
414 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
416 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
417 if (!selectionToggleRect
.isEmpty()) {
418 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
419 return selectionToggleRect
.contains(mappedPos
);
425 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
427 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
429 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
430 if (!expansionToggleRect
.isEmpty()) {
431 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
432 return expansionToggleRect
.contains(mappedPos
);
438 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
440 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
442 const QRectF
&textRect
= widget
->textRect();
443 if (!textRect
.isEmpty()) {
444 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
445 return textRect
.contains(mappedPos
);
451 int KItemListView::firstVisibleIndex() const
453 return m_layouter
->firstVisibleIndex();
456 int KItemListView::lastVisibleIndex() const
458 return m_layouter
->lastVisibleIndex();
461 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
463 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
466 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
468 if (m_supportsItemExpanding
!= supportsExpanding
) {
469 m_supportsItemExpanding
= supportsExpanding
;
470 updateSiblingsInformation();
471 onSupportsItemExpandingChanged(supportsExpanding
);
475 bool KItemListView::supportsItemExpanding() const
477 return m_supportsItemExpanding
;
480 QRectF
KItemListView::itemRect(int index
) const
482 return m_layouter
->itemRect(index
);
485 QRectF
KItemListView::itemContextRect(int index
) const
489 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
491 contextRect
= widget
->iconRect() | widget
->textRect();
492 contextRect
.translate(itemRect(index
).topLeft());
498 void KItemListView::scrollToItem(int index
)
500 QRectF viewGeometry
= geometry();
501 if (m_headerWidget
->isVisible()) {
502 const qreal headerHeight
= m_headerWidget
->size().height();
503 viewGeometry
.adjust(0, headerHeight
, 0, 0);
505 QRectF currentRect
= itemRect(index
);
507 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
508 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
509 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
511 if (!viewGeometry
.contains(currentRect
)) {
512 qreal newOffset
= scrollOffset();
513 if (scrollOrientation() == Qt::Vertical
) {
514 if (currentRect
.top() < viewGeometry
.top()) {
515 newOffset
+= currentRect
.top() - viewGeometry
.top();
516 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
517 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
520 if (currentRect
.left() < viewGeometry
.left()) {
521 newOffset
+= currentRect
.left() - viewGeometry
.left();
522 } else if (currentRect
.right() > viewGeometry
.right()) {
523 newOffset
+= currentRect
.right() - viewGeometry
.right();
527 if (newOffset
!= scrollOffset()) {
528 Q_EMIT
scrollTo(newOffset
);
533 Q_EMIT
scrollingStopped();
536 void KItemListView::beginTransaction()
538 ++m_activeTransactions
;
539 if (m_activeTransactions
== 1) {
540 onTransactionBegin();
544 void KItemListView::endTransaction()
546 --m_activeTransactions
;
547 if (m_activeTransactions
< 0) {
548 m_activeTransactions
= 0;
549 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
552 if (m_activeTransactions
== 0) {
554 doLayout(m_endTransactionAnimationHint
);
555 m_endTransactionAnimationHint
= Animation
;
559 bool KItemListView::isTransactionActive() const
561 return m_activeTransactions
> 0;
564 void KItemListView::setHeaderVisible(bool visible
)
566 if (visible
&& !m_headerWidget
->isVisible()) {
567 QStyleOptionHeader option
;
568 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
571 m_headerWidget
->setPos(0, 0);
572 m_headerWidget
->resize(size().width(), headerSize
.height());
573 m_headerWidget
->setModel(m_model
);
574 m_headerWidget
->setColumns(m_visibleRoles
);
575 m_headerWidget
->setZValue(1);
577 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
578 this, &KItemListView::slotHeaderColumnWidthChanged
);
579 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
580 this, &KItemListView::slotHeaderColumnMoved
);
581 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
582 this, &KItemListView::sortOrderChanged
);
583 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
584 this, &KItemListView::sortRoleChanged
);
586 m_layouter
->setHeaderHeight(headerSize
.height());
587 m_headerWidget
->setVisible(true);
588 } else if (!visible
&& m_headerWidget
->isVisible()) {
589 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
590 this, &KItemListView::slotHeaderColumnWidthChanged
);
591 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
592 this, &KItemListView::slotHeaderColumnMoved
);
593 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
594 this, &KItemListView::sortOrderChanged
);
595 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
596 this, &KItemListView::sortRoleChanged
);
598 m_layouter
->setHeaderHeight(0);
599 m_headerWidget
->setVisible(false);
603 bool KItemListView::isHeaderVisible() const
605 return m_headerWidget
->isVisible();
608 KItemListHeader
* KItemListView::header() const
613 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
617 if (indexes
.count() == 1) {
618 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
619 QGraphicsView
* graphicsView
= scene()->views()[0];
620 if (item
&& graphicsView
) {
621 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
624 // TODO: Not implemented yet. Probably extend the interface
625 // from KItemListWidget::createDragPixmap() to return a pixmap
626 // that can be used for multiple indexes.
632 void KItemListView::editRole(int index
, const QByteArray
& role
)
634 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
635 if (!widget
|| m_editingRole
) {
639 m_editingRole
= true;
640 widget
->setEditedRole(role
);
642 connect(widget
, &KItemListWidget::roleEditingCanceled
,
643 this, &KItemListView::slotRoleEditingCanceled
);
644 connect(widget
, &KItemListWidget::roleEditingFinished
,
645 this, &KItemListView::slotRoleEditingFinished
);
647 connect(this, &KItemListView::scrollOffsetChanged
,
648 widget
, &KStandardItemListWidget::finishRoleEditing
);
651 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
653 QGraphicsWidget::paint(painter
, option
, widget
);
655 for (auto animation
: qAsConst(m_rubberBandAnimations
)) {
656 QRectF rubberBandRect
= animation
->property(RubberPropertyName
).toRectF();
658 const QPointF topLeft
= rubberBandRect
.topLeft();
659 if (scrollOrientation() == Qt::Vertical
) {
660 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
662 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
665 QStyleOptionRubberBand opt
;
666 initStyleOption(&opt
);
667 opt
.shape
= QRubberBand::Rectangle
;
669 opt
.rect
= rubberBandRect
.toRect();
673 painter
->setOpacity(animation
->currentValue().toReal());
674 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
679 if (m_rubberBand
->isActive()) {
680 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
681 m_rubberBand
->endPosition()).normalized();
683 const QPointF topLeft
= rubberBandRect
.topLeft();
684 if (scrollOrientation() == Qt::Vertical
) {
685 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
687 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
690 QStyleOptionRubberBand opt
;
691 initStyleOption(&opt
);
692 opt
.shape
= QRubberBand::Rectangle
;
694 opt
.rect
= rubberBandRect
.toRect();
695 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
698 if (m_tapAndHoldIndicator
->isActive()) {
699 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
700 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
701 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
702 QStyleOptionRubberBand opt
;
703 initStyleOption(&opt
);
704 opt
.shape
= QRubberBand::Rectangle
;
706 opt
.rect
= rubberBandRect
.toRect();
707 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
710 if (!m_dropIndicator
.isEmpty()) {
711 const QRectF r
= m_dropIndicator
.toRect();
713 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
714 painter
->setPen(color
);
716 // TODO: The following implementation works only for a vertical scroll-orientation
717 // and assumes a height of the m_draggingInsertIndicator of 1.
718 Q_ASSERT(r
.height() == 1);
719 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
722 painter
->setPen(color
);
723 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
727 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
729 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
730 if (!scene()->views().isEmpty()) {
731 m_styleOption
.palette
= scene()->views().at(0)->palette();
734 return QGraphicsItem::itemChange(change
, value
);
737 void KItemListView::setItemSize(const QSizeF
& size
)
739 const QSizeF previousSize
= m_itemSize
;
740 if (size
== previousSize
) {
744 // Skip animations when the number of rows or columns
745 // are changed in the grid layout. Although the animation
746 // engine can handle this usecase, it looks obtrusive.
747 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
749 m_layouter
->itemMargin());
751 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
752 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
753 (!m_itemSize
.isEmpty() && size
.isEmpty()));
757 if (alternateBackgroundsChanged
) {
758 // For an empty item size alternate backgrounds are drawn if more than
759 // one role is shown. Assure that the backgrounds for visible items are
760 // updated when changing the size in this context.
761 updateAlternateBackgrounds();
764 if (size
.isEmpty()) {
765 if (m_headerWidget
->automaticColumnResizing()) {
766 updatePreferredColumnWidths();
768 // Only apply the changed height and respect the header widths
770 const qreal currentWidth
= m_layouter
->itemSize().width();
771 const QSizeF
newSize(currentWidth
, size
.height());
772 m_layouter
->setItemSize(newSize
);
775 m_layouter
->setItemSize(size
);
778 m_sizeHintResolver
->clearCache();
779 doLayout(animate
? Animation
: NoAnimation
);
780 onItemSizeChanged(size
, previousSize
);
783 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
785 if (m_styleOption
== option
) {
789 const KItemListStyleOption previousOption
= m_styleOption
;
790 m_styleOption
= option
;
793 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
794 if (margin
!= m_layouter
->itemMargin()) {
795 // Skip animations when the number of rows or columns
796 // are changed in the grid layout. Although the animation
797 // engine can handle this usecase, it looks obtrusive.
798 animate
= !changesItemGridLayout(m_layouter
->size(),
799 m_layouter
->itemSize(),
801 m_layouter
->setItemMargin(margin
);
805 updateGroupHeaderHeight();
809 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
810 // Animating a change of the maximum text size just results in expensive
811 // temporary eliding and clipping operations and does not look good visually.
815 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
816 while (it
.hasNext()) {
818 it
.value()->setStyleOption(option
);
821 m_sizeHintResolver
->clearCache();
822 m_layouter
->markAsDirty();
823 doLayout(animate
? Animation
: NoAnimation
);
825 if (m_itemSize
.isEmpty()) {
826 updatePreferredColumnWidths();
829 onStyleOptionChanged(option
, previousOption
);
832 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
834 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
835 if (orientation
== previousOrientation
) {
839 m_layouter
->setScrollOrientation(orientation
);
840 m_animation
->setScrollOrientation(orientation
);
841 m_sizeHintResolver
->clearCache();
844 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
845 while (it
.hasNext()) {
847 it
.value()->setScrollOrientation(orientation
);
849 updateGroupHeaderHeight();
853 doLayout(NoAnimation
);
855 onScrollOrientationChanged(orientation
, previousOrientation
);
856 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
859 Qt::Orientation
KItemListView::scrollOrientation() const
861 return m_layouter
->scrollOrientation();
864 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
869 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
874 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
879 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
881 Q_UNUSED(changedRoles
)
885 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
891 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
897 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
903 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
909 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
915 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
921 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
927 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
929 Q_UNUSED(supportsExpanding
)
932 void KItemListView::onTransactionBegin()
936 void KItemListView::onTransactionEnd()
940 bool KItemListView::event(QEvent
* event
)
942 switch (event
->type()) {
943 case QEvent::PaletteChange
:
947 case QEvent::FontChange
:
952 // Forward all other events to the controller and handle them there
953 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
959 return QGraphicsWidget::event(event
);
962 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
964 m_mousePos
= transform().map(event
->pos());
968 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
970 QGraphicsWidget::mouseMoveEvent(event
);
972 m_mousePos
= transform().map(event
->pos());
973 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
974 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
978 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
980 event
->setAccepted(true);
984 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
986 QGraphicsWidget::dragMoveEvent(event
);
988 m_mousePos
= transform().map(event
->pos());
989 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
990 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
994 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
996 QGraphicsWidget::dragLeaveEvent(event
);
997 setAutoScroll(false);
1000 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
1002 QGraphicsWidget::dropEvent(event
);
1003 setAutoScroll(false);
1006 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
1008 return m_visibleItems
.values();
1011 void KItemListView::updateFont()
1013 if (scene() && !scene()->views().isEmpty()) {
1014 KItemListStyleOption option
= styleOption();
1015 option
.font
= scene()->views().first()->font();
1016 option
.fontMetrics
= QFontMetrics(option
.font
);
1018 setStyleOption(option
);
1022 void KItemListView::updatePalette()
1024 if (scene() && !scene()->views().isEmpty()) {
1025 KItemListStyleOption option
= styleOption();
1026 option
.palette
= scene()->views().first()->palette();
1028 setStyleOption(option
);
1032 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1034 if (m_itemSize
.isEmpty()) {
1035 updatePreferredColumnWidths(itemRanges
);
1038 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1039 if (hasMultipleRanges
) {
1043 m_layouter
->markAsDirty();
1045 m_sizeHintResolver
->itemsInserted(itemRanges
);
1047 int previouslyInsertedCount
= 0;
1048 for (const KItemRange
& range
: itemRanges
) {
1049 // range.index is related to the model before anything has been inserted.
1050 // As in each loop the current item-range gets inserted the index must
1051 // be increased by the already previously inserted items.
1052 const int index
= range
.index
+ previouslyInsertedCount
;
1053 const int count
= range
.count
;
1054 if (index
< 0 || count
<= 0) {
1055 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1058 previouslyInsertedCount
+= count
;
1060 // Determine which visible items must be moved
1061 QList
<int> itemsToMove
;
1062 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1063 while (it
.hasNext()) {
1065 const int visibleItemIndex
= it
.key();
1066 if (visibleItemIndex
>= index
) {
1067 itemsToMove
.append(visibleItemIndex
);
1071 // Update the indexes of all KItemListWidget instances that are located
1072 // after the inserted items. It is important to adjust the indexes in the order
1073 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1074 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1075 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1076 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1078 const int newIndex
= widget
->index() + count
;
1079 if (hasMultipleRanges
) {
1080 setWidgetIndex(widget
, newIndex
);
1082 // Try to animate the moving of the item
1083 moveWidgetToIndex(widget
, newIndex
);
1087 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1088 // Check whether a scrollbar is required to show the inserted items. In this case
1089 // the size of the layouter will be decreased before calling doLayout(): This prevents
1090 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1091 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1092 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1093 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1094 if (decreaseLayouterSize
) {
1095 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1097 int scrollbarSpacing
= 0;
1098 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1099 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1102 QSizeF layouterSize
= m_layouter
->size();
1103 if (verticalScrollOrientation
) {
1104 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1106 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1108 m_layouter
->setSize(layouterSize
);
1112 if (!hasMultipleRanges
) {
1113 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1114 updateSiblingsInformation();
1119 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1122 if (hasMultipleRanges
) {
1123 m_endTransactionAnimationHint
= NoAnimation
;
1126 updateSiblingsInformation();
1129 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1130 // In case if items of the same group have been inserted before an item that
1131 // currently represents the first item of the group, the group header of
1132 // this item must be removed.
1133 updateVisibleGroupHeaders();
1136 if (useAlternateBackgrounds()) {
1137 updateAlternateBackgrounds();
1141 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1143 if (m_itemSize
.isEmpty()) {
1144 // Don't pass the item-range: The preferred column-widths of
1145 // all items must be adjusted when removing items.
1146 updatePreferredColumnWidths();
1149 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1150 if (hasMultipleRanges
) {
1154 m_layouter
->markAsDirty();
1156 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1158 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1159 const KItemRange
& range
= itemRanges
[i
];
1160 const int index
= range
.index
;
1161 const int count
= range
.count
;
1162 if (index
< 0 || count
<= 0) {
1163 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1167 const int firstRemovedIndex
= index
;
1168 const int lastRemovedIndex
= index
+ count
- 1;
1170 // Remember which items have to be moved because they are behind the removed range.
1171 QVector
<int> itemsToMove
;
1173 // Remove all KItemListWidget instances that got deleted
1174 // Iterate over a const copy because the container is mutated within the loop
1175 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1176 const auto visibleItems
= m_visibleItems
;
1177 for (KItemListWidget
* widget
: visibleItems
) {
1178 const int i
= widget
->index();
1179 if (i
< firstRemovedIndex
) {
1181 } else if (i
> lastRemovedIndex
) {
1182 itemsToMove
.append(i
);
1186 m_animation
->stop(widget
);
1187 // Stopping the animation might lead to recycling the widget if
1188 // it is invisible (see slotAnimationFinished()).
1189 // Check again whether it is still visible:
1190 if (!m_visibleItems
.contains(i
)) {
1194 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1195 // Remove the widget without animation
1196 recycleWidget(widget
);
1198 // Animate the removing of the items. Special case: When removing an item there
1199 // is no valid model index available anymore. For the
1200 // remove-animation the item gets removed from m_visibleItems but the widget
1201 // will stay alive until the animation has been finished and will
1202 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1203 m_visibleItems
.remove(i
);
1204 widget
->setIndex(-1);
1205 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1209 // Update the indexes of all KItemListWidget instances that are located
1210 // after the deleted items. It is important to update them in ascending
1211 // order to prevent overlaps when setting the new index.
1212 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1213 for (int i
: qAsConst(itemsToMove
)) {
1214 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1216 const int newIndex
= i
- count
;
1217 if (hasMultipleRanges
) {
1218 setWidgetIndex(widget
, newIndex
);
1220 // Try to animate the moving of the item
1221 moveWidgetToIndex(widget
, newIndex
);
1225 if (!hasMultipleRanges
) {
1226 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1227 // assumes an updated geometry. If items are removed during an active transaction,
1228 // the transaction will be temporary deactivated so that doLayout() triggers a
1229 // geometry update if necessary.
1230 const int activeTransactions
= m_activeTransactions
;
1231 m_activeTransactions
= 0;
1232 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1233 m_activeTransactions
= activeTransactions
;
1234 updateSiblingsInformation();
1239 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1242 if (hasMultipleRanges
) {
1243 m_endTransactionAnimationHint
= NoAnimation
;
1245 updateSiblingsInformation();
1248 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1249 // In case if the first item of a group has been removed, the group header
1250 // must be applied to the next visible item.
1251 updateVisibleGroupHeaders();
1254 if (useAlternateBackgrounds()) {
1255 updateAlternateBackgrounds();
1259 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1261 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1262 m_layouter
->markAsDirty();
1265 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1268 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1269 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1271 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1272 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1274 updateWidgetProperties(widget
, index
);
1275 initializeItemListWidget(widget
);
1279 doLayout(NoAnimation
);
1280 updateSiblingsInformation();
1283 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1284 const QSet
<QByteArray
>& roles
)
1286 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1287 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1288 updatePreferredColumnWidths(itemRanges
);
1291 for (const KItemRange
& itemRange
: itemRanges
) {
1292 const int index
= itemRange
.index
;
1293 const int count
= itemRange
.count
;
1295 if (updateSizeHints
) {
1296 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1297 m_layouter
->markAsDirty();
1299 if (!m_layoutTimer
->isActive()) {
1300 m_layoutTimer
->start();
1304 // Apply the changed roles to the visible item-widgets
1305 const int lastIndex
= index
+ count
- 1;
1306 for (int i
= index
; i
<= lastIndex
; ++i
) {
1307 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1309 widget
->setData(m_model
->data(i
), roles
);
1313 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1314 // The sort-role has been changed which might result
1315 // in modified group headers
1316 updateVisibleGroupHeaders();
1317 doLayout(NoAnimation
);
1320 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1321 ev
.setFirstRow(itemRange
.index
);
1322 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1323 QAccessible::updateAccessibility(&ev
);
1327 void KItemListView::slotGroupsChanged()
1329 updateVisibleGroupHeaders();
1330 doLayout(NoAnimation
);
1331 updateSiblingsInformation();
1334 void KItemListView::slotGroupedSortingChanged(bool current
)
1336 m_grouped
= current
;
1337 m_layouter
->markAsDirty();
1340 updateGroupHeaderHeight();
1342 // Clear all visible headers. Note that the QHashIterator takes a copy of
1343 // m_visibleGroups. Therefore, it remains valid even if items are removed
1344 // from m_visibleGroups in recycleGroupHeaderForWidget().
1345 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1346 while (it
.hasNext()) {
1348 recycleGroupHeaderForWidget(it
.key());
1350 Q_ASSERT(m_visibleGroups
.isEmpty());
1353 if (useAlternateBackgrounds()) {
1354 // Changing the group mode requires to update the alternate backgrounds
1355 // as with the enabled group mode the altering is done on base of the first
1357 updateAlternateBackgrounds();
1359 updateSiblingsInformation();
1360 doLayout(NoAnimation
);
1363 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1368 updateVisibleGroupHeaders();
1369 doLayout(NoAnimation
);
1373 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1378 updateVisibleGroupHeaders();
1379 doLayout(NoAnimation
);
1383 void KItemListView::slotCurrentChanged(int current
, int previous
)
1387 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1388 // always the selected item. It is not necessary to highlight the current item then.
1389 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1390 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1391 if (previousWidget
) {
1392 previousWidget
->setCurrent(false);
1395 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1396 if (currentWidget
) {
1397 currentWidget
->setCurrent(true);
1401 QAccessibleEvent
ev(this, QAccessible::Focus
);
1402 ev
.setChild(current
);
1403 QAccessible::updateAccessibility(&ev
);
1406 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1410 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1411 while (it
.hasNext()) {
1413 const int index
= it
.key();
1414 KItemListWidget
* widget
= it
.value();
1415 widget
->setSelected(current
.contains(index
));
1419 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1420 KItemListViewAnimation::AnimationType type
)
1422 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1423 Q_ASSERT(itemListWidget
);
1426 case KItemListViewAnimation::DeleteAnimation
: {
1427 // As we recycle the widget in this case it is important to assure that no
1428 // other animation has been started. This is a convention in KItemListView and
1429 // not a requirement defined by KItemListViewAnimation.
1430 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1432 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1433 // by m_visibleWidgets and must be deleted manually after the animation has
1435 recycleGroupHeaderForWidget(itemListWidget
);
1436 widgetCreator()->recycle(itemListWidget
);
1440 case KItemListViewAnimation::CreateAnimation
:
1441 case KItemListViewAnimation::MovingAnimation
:
1442 case KItemListViewAnimation::ResizeAnimation
: {
1443 const int index
= itemListWidget
->index();
1444 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1445 (index
> m_layouter
->lastVisibleIndex());
1446 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1447 recycleWidget(itemListWidget
);
1456 void KItemListView::slotLayoutTimerFinished()
1458 m_layouter
->setSize(geometry().size());
1459 doLayout(Animation
);
1462 void KItemListView::slotRubberBandPosChanged()
1467 void KItemListView::slotRubberBandActivationChanged(bool active
)
1470 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1471 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1472 m_skipAutoScrollForRubberBand
= true;
1474 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
1475 m_rubberBand
->endPosition()).normalized();
1477 auto animation
= new QVariantAnimation(this);
1478 animation
->setStartValue(1.0);
1479 animation
->setEndValue(0.0);
1480 animation
->setDuration(RubberFadeSpeed
);
1481 animation
->setProperty(RubberPropertyName
, rubberBandRect
);
1484 curve
.setType(QEasingCurve::BezierSpline
);
1485 curve
.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1486 animation
->setEasingCurve(curve
);
1488 connect(animation
, &QVariantAnimation::valueChanged
, this, [=](const QVariant
&) {
1491 connect(animation
, &QVariantAnimation::finished
, this, [=]() {
1492 m_rubberBandAnimations
.removeAll(animation
);
1496 m_rubberBandAnimations
<< animation
;
1498 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1499 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1500 m_skipAutoScrollForRubberBand
= false;
1506 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1508 qreal previousWidth
)
1511 Q_UNUSED(currentWidth
)
1512 Q_UNUSED(previousWidth
)
1514 m_headerWidget
->setAutomaticColumnResizing(false);
1515 applyColumnWidthsFromHeader();
1516 doLayout(NoAnimation
);
1519 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1523 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1525 const QList
<QByteArray
> previous
= m_visibleRoles
;
1527 QList
<QByteArray
> current
= m_visibleRoles
;
1528 current
.removeAt(previousIndex
);
1529 current
.insert(currentIndex
, role
);
1531 setVisibleRoles(current
);
1533 Q_EMIT
visibleRolesChanged(current
, previous
);
1536 void KItemListView::triggerAutoScrolling()
1538 if (!m_autoScrollTimer
) {
1543 int visibleSize
= 0;
1544 if (scrollOrientation() == Qt::Vertical
) {
1545 pos
= m_mousePos
.y();
1546 visibleSize
= size().height();
1548 pos
= m_mousePos
.x();
1549 visibleSize
= size().width();
1552 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1553 m_autoScrollIncrement
= 0;
1556 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1557 if (m_autoScrollIncrement
== 0) {
1558 // The mouse position is not above an autoscroll margin (the autoscroll timer
1559 // will be restarted in mouseMoveEvent())
1560 m_autoScrollTimer
->stop();
1564 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1565 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1566 // if the direction of the rubberband is similar to the autoscroll direction. This
1567 // prevents that starting to create a rubberband within the autoscroll margins starts
1568 // an autoscrolling.
1570 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1571 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1572 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1573 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1574 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1575 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1576 // been moved up although the autoscroll direction might be down)
1577 m_autoScrollTimer
->stop();
1582 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1583 // the autoscrolling may not get skipped anymore until a new rubberband is created
1584 m_skipAutoScrollForRubberBand
= false;
1586 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1587 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1588 setScrollOffset(newScrollOffset
);
1590 // Trigger the autoscroll timer which will periodically call
1591 // triggerAutoScrolling()
1592 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1595 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1597 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1599 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1600 Q_ASSERT(groupHeader
);
1601 updateGroupHeaderLayout(widget
);
1604 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1606 disconnectRoleEditingSignals(index
);
1608 m_editingRole
= false;
1609 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1612 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1614 disconnectRoleEditingSignals(index
);
1616 m_editingRole
= false;
1617 Q_EMIT
roleEditingFinished(index
, role
, value
);
1620 void KItemListView::setController(KItemListController
* controller
)
1622 if (m_controller
!= controller
) {
1623 KItemListController
* previous
= m_controller
;
1625 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1626 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1627 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1630 m_controller
= controller
;
1633 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1634 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1635 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1638 onControllerChanged(controller
, previous
);
1642 void KItemListView::setModel(KItemModelBase
* model
)
1644 if (m_model
== model
) {
1648 KItemModelBase
* previous
= m_model
;
1651 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1652 this, &KItemListView::slotItemsChanged
);
1653 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1654 this, &KItemListView::slotItemsInserted
);
1655 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1656 this, &KItemListView::slotItemsRemoved
);
1657 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1658 this, &KItemListView::slotItemsMoved
);
1659 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1660 this, &KItemListView::slotGroupsChanged
);
1661 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1662 this, &KItemListView::slotGroupedSortingChanged
);
1663 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1664 this, &KItemListView::slotSortOrderChanged
);
1665 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1666 this, &KItemListView::slotSortRoleChanged
);
1668 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1672 m_layouter
->setModel(model
);
1673 m_grouped
= model
->groupedSorting();
1676 connect(m_model
, &KItemModelBase::itemsChanged
,
1677 this, &KItemListView::slotItemsChanged
);
1678 connect(m_model
, &KItemModelBase::itemsInserted
,
1679 this, &KItemListView::slotItemsInserted
);
1680 connect(m_model
, &KItemModelBase::itemsRemoved
,
1681 this, &KItemListView::slotItemsRemoved
);
1682 connect(m_model
, &KItemModelBase::itemsMoved
,
1683 this, &KItemListView::slotItemsMoved
);
1684 connect(m_model
, &KItemModelBase::groupsChanged
,
1685 this, &KItemListView::slotGroupsChanged
);
1686 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1687 this, &KItemListView::slotGroupedSortingChanged
);
1688 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1689 this, &KItemListView::slotSortOrderChanged
);
1690 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1691 this, &KItemListView::slotSortRoleChanged
);
1693 const int itemCount
= m_model
->count();
1694 if (itemCount
> 0) {
1695 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1699 onModelChanged(model
, previous
);
1702 KItemListRubberBand
* KItemListView::rubberBand() const
1704 return m_rubberBand
;
1707 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1709 if (m_layoutTimer
->isActive()) {
1710 m_layoutTimer
->stop();
1713 if (m_activeTransactions
> 0) {
1714 if (hint
== NoAnimation
) {
1715 // As soon as at least one property change should be done without animation,
1716 // the whole transaction will be marked as not animated.
1717 m_endTransactionAnimationHint
= NoAnimation
;
1722 if (!m_model
|| m_model
->count() < 0) {
1726 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1727 if (firstVisibleIndex
< 0) {
1728 emitOffsetChanges();
1732 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1733 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1734 // is still shown if the maximum offset got decreased.
1735 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1736 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1737 if (scrollOffset() > maxOffsetToShowFullRange
) {
1738 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1739 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1742 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1744 int firstSibblingIndex
= -1;
1745 int lastSibblingIndex
= -1;
1746 const bool supportsExpanding
= supportsItemExpanding();
1748 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1750 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1751 // instances from invisible items are reused. If no reusable items are
1752 // found then new KItemListWidget instances get created.
1753 const bool animate
= (hint
== Animation
);
1754 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1755 bool applyNewPos
= true;
1757 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1758 const QPointF newPos
= itemBounds
.topLeft();
1759 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1761 if (!reusableItems
.isEmpty()) {
1762 // Reuse a KItemListWidget instance from an invisible item
1763 const int oldIndex
= reusableItems
.takeLast();
1764 widget
= m_visibleItems
.value(oldIndex
);
1765 setWidgetIndex(widget
, i
);
1766 updateWidgetProperties(widget
, i
);
1767 initializeItemListWidget(widget
);
1769 // No reusable KItemListWidget instance is available, create a new one
1770 widget
= createWidget(i
);
1772 widget
->resize(itemBounds
.size());
1774 if (animate
&& changedCount
< 0) {
1775 // Items have been deleted.
1776 if (i
>= changedIndex
) {
1777 // The item is located behind the removed range. Move the
1778 // created item to the imaginary old position outside the
1779 // view. It will get animated to the new position later.
1780 const int previousIndex
= i
- changedCount
;
1781 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1782 if (itemRect
.isEmpty()) {
1783 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1784 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1785 widget
->setPos(invisibleOldPos
);
1787 widget
->setPos(itemRect
.topLeft());
1789 applyNewPos
= false;
1793 if (supportsExpanding
&& changedCount
== 0) {
1794 if (firstSibblingIndex
< 0) {
1795 firstSibblingIndex
= i
;
1797 lastSibblingIndex
= i
;
1802 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1803 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1804 applyNewPos
= false;
1807 const bool itemsRemoved
= (changedCount
< 0);
1808 const bool itemsInserted
= (changedCount
> 0);
1809 if (itemsRemoved
&& (i
>= changedIndex
)) {
1810 // The item is located after the removed items. Animate the moving of the position.
1811 applyNewPos
= !moveWidget(widget
, newPos
);
1812 } else if (itemsInserted
&& i
>= changedIndex
) {
1813 // The item is located after the first inserted item
1814 if (i
<= changedIndex
+ changedCount
- 1) {
1815 // The item is an inserted item. Animate the appearing of the item.
1816 // For performance reasons no animation is done when changedCount is equal
1817 // to all available items.
1818 if (changedCount
< m_model
->count()) {
1819 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1821 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1822 // The item was already there before, so animate the moving of the position.
1823 // No moving animation is done if the item is animated by a create animation: This
1824 // prevents a "move animation mess" when inserting several ranges in parallel.
1825 applyNewPos
= !moveWidget(widget
, newPos
);
1829 m_animation
->stop(widget
);
1833 widget
->setPos(newPos
);
1836 Q_ASSERT(widget
->index() == i
);
1837 widget
->setVisible(true);
1839 if (widget
->size() != itemBounds
.size()) {
1840 // Resize the widget for the item to the changed size.
1842 // If a dynamic item size is used then no animation is done in the direction
1843 // of the dynamic size.
1844 if (m_itemSize
.width() <= 0) {
1845 // The width is dynamic, apply the new width without animation.
1846 widget
->resize(itemBounds
.width(), widget
->size().height());
1847 } else if (m_itemSize
.height() <= 0) {
1848 // The height is dynamic, apply the new height without animation.
1849 widget
->resize(widget
->size().width(), itemBounds
.height());
1851 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1853 widget
->resize(itemBounds
.size());
1857 // Updating the cell-information must be done as last step: The decision whether the
1858 // moving-animation should be started at all is based on the previous cell-information.
1859 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1860 m_visibleCells
.insert(i
, cell
);
1863 // Delete invisible KItemListWidget instances that have not been reused
1864 for (int index
: qAsConst(reusableItems
)) {
1865 recycleWidget(m_visibleItems
.value(index
));
1868 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1869 Q_ASSERT(lastSibblingIndex
>= 0);
1870 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1874 // Update the layout of all visible group headers
1875 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1876 while (it
.hasNext()) {
1878 updateGroupHeaderLayout(it
.key());
1882 emitOffsetChanges();
1885 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1886 int lastVisibleIndex
,
1887 LayoutAnimationHint hint
)
1889 // Determine all items that are completely invisible and might be
1890 // reused for items that just got (at least partly) visible. If the
1891 // animation hint is set to 'Animation' items that do e.g. an animated
1892 // moving of their position are not marked as invisible: This assures
1893 // that a scrolling inside the view can be done without breaking an animation.
1897 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1898 while (it
.hasNext()) {
1901 KItemListWidget
* widget
= it
.value();
1902 const int index
= widget
->index();
1903 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1906 if (m_animation
->isStarted(widget
)) {
1907 if (hint
== NoAnimation
) {
1908 // Stopping the animation will call KItemListView::slotAnimationFinished()
1909 // and the widget will be recycled if necessary there.
1910 m_animation
->stop(widget
);
1913 widget
->setVisible(false);
1914 items
.append(index
);
1917 recycleGroupHeaderForWidget(widget
);
1926 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1928 if (widget
->pos() == newPos
) {
1932 bool startMovingAnim
= false;
1934 if (m_itemSize
.isEmpty()) {
1935 // The items are not aligned in a grid but either as columns or rows.
1936 startMovingAnim
= true;
1938 // When having a grid the moving-animation should only be started, if it is done within
1939 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1940 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1941 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1942 const int index
= widget
->index();
1943 const Cell cell
= m_visibleCells
.value(index
);
1944 if (cell
.column
>= 0 && cell
.row
>= 0) {
1945 if (scrollOrientation() == Qt::Vertical
) {
1946 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1948 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1953 if (startMovingAnim
) {
1954 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1958 m_animation
->stop(widget
);
1959 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1963 void KItemListView::emitOffsetChanges()
1965 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1966 if (m_oldScrollOffset
!= newScrollOffset
) {
1967 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1968 m_oldScrollOffset
= newScrollOffset
;
1971 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1972 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1973 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1974 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1977 const qreal newItemOffset
= m_layouter
->itemOffset();
1978 if (m_oldItemOffset
!= newItemOffset
) {
1979 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1980 m_oldItemOffset
= newItemOffset
;
1983 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1984 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1985 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1986 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1990 KItemListWidget
* KItemListView::createWidget(int index
)
1992 KItemListWidget
* widget
= widgetCreator()->create(this);
1993 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1995 m_visibleItems
.insert(index
, widget
);
1996 m_visibleCells
.insert(index
, Cell());
1997 updateWidgetProperties(widget
, index
);
1998 initializeItemListWidget(widget
);
2002 void KItemListView::recycleWidget(KItemListWidget
* widget
)
2005 recycleGroupHeaderForWidget(widget
);
2008 const int index
= widget
->index();
2009 m_visibleItems
.remove(index
);
2010 m_visibleCells
.remove(index
);
2012 widgetCreator()->recycle(widget
);
2015 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
2017 const int oldIndex
= widget
->index();
2018 m_visibleItems
.remove(oldIndex
);
2019 m_visibleCells
.remove(oldIndex
);
2021 m_visibleItems
.insert(index
, widget
);
2022 m_visibleCells
.insert(index
, Cell());
2024 widget
->setIndex(index
);
2027 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
2029 const int oldIndex
= widget
->index();
2030 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
2032 setWidgetIndex(widget
, index
);
2034 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2035 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2036 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
2037 (!vertical
&& oldCell
.column
== newCell
.column
);
2039 m_visibleCells
.insert(index
, newCell
);
2043 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2046 case LayouterSize
: m_layouter
->setSize(size
); break;
2047 case ItemSize
: m_layouter
->setItemSize(size
); break;
2052 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2054 widget
->setVisibleRoles(m_visibleRoles
);
2055 updateWidgetColumnWidths(widget
);
2056 widget
->setStyleOption(m_styleOption
);
2058 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2060 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2061 // always the selected item. It is not necessary to highlight the current item then.
2062 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2063 widget
->setCurrent(index
== selectionManager
->currentItem());
2065 widget
->setSelected(selectionManager
->isSelected(index
));
2066 widget
->setHovered(false);
2067 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2068 widget
->setIndex(index
);
2069 widget
->setData(m_model
->data(index
));
2070 widget
->setSiblingsInformation(QBitArray());
2071 updateAlternateBackgroundForWidget(widget
);
2074 updateGroupHeaderForWidget(widget
);
2078 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2080 Q_ASSERT(m_grouped
);
2082 const int index
= widget
->index();
2083 if (!m_layouter
->isFirstGroupItem(index
)) {
2084 // The widget does not represent the first item of a group
2085 // and hence requires no header
2086 recycleGroupHeaderForWidget(widget
);
2090 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2091 if (groups
.isEmpty() || !groupHeaderCreator()) {
2095 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2097 groupHeader
= groupHeaderCreator()->create(this);
2098 groupHeader
->setParentItem(widget
);
2099 m_visibleGroups
.insert(widget
, groupHeader
);
2100 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2102 Q_ASSERT(groupHeader
->parentItem() == widget
);
2104 const int groupIndex
= groupIndexForItem(index
);
2105 Q_ASSERT(groupIndex
>= 0);
2106 groupHeader
->setData(groups
.at(groupIndex
).second
);
2107 groupHeader
->setRole(model()->sortRole());
2108 groupHeader
->setStyleOption(m_styleOption
);
2109 groupHeader
->setScrollOrientation(scrollOrientation());
2110 groupHeader
->setItemIndex(index
);
2112 groupHeader
->show();
2115 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2117 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2118 Q_ASSERT(groupHeader
);
2120 const int index
= widget
->index();
2121 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2122 const QRectF itemRect
= m_layouter
->itemRect(index
);
2124 // The group-header is a child of the itemlist widget. Translate the
2125 // group header position to the relative position.
2126 if (scrollOrientation() == Qt::Vertical
) {
2127 // In the vertical scroll orientation the group header should always span
2128 // the whole width no matter which temporary position the parent widget
2129 // has. In this case the x-position and width will be adjusted manually.
2130 const qreal x
= -widget
->x() - itemOffset();
2131 const qreal width
= maximumItemOffset();
2132 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2133 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2135 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2136 groupHeader
->resize(groupHeaderRect
.size());
2140 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2142 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2144 header
->setParentItem(nullptr);
2145 groupHeaderCreator()->recycle(header
);
2146 m_visibleGroups
.remove(widget
);
2147 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2151 void KItemListView::updateVisibleGroupHeaders()
2153 Q_ASSERT(m_grouped
);
2154 m_layouter
->markAsDirty();
2156 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2157 while (it
.hasNext()) {
2159 updateGroupHeaderForWidget(it
.value());
2163 int KItemListView::groupIndexForItem(int index
) const
2165 Q_ASSERT(m_grouped
);
2167 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2168 if (groups
.isEmpty()) {
2173 int max
= groups
.count() - 1;
2176 mid
= (min
+ max
) / 2;
2177 if (index
> groups
[mid
].first
) {
2182 } while (groups
[mid
].first
!= index
&& min
<= max
);
2185 while (groups
[mid
].first
> index
&& mid
> 0) {
2193 void KItemListView::updateAlternateBackgrounds()
2195 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2196 while (it
.hasNext()) {
2198 updateAlternateBackgroundForWidget(it
.value());
2202 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2204 bool enabled
= useAlternateBackgrounds();
2206 const int index
= widget
->index();
2207 enabled
= (index
& 0x1) > 0;
2209 const int groupIndex
= groupIndexForItem(index
);
2210 if (groupIndex
>= 0) {
2211 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2212 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2213 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2214 enabled
= (relativeIndex
& 0x1) > 0;
2218 widget
->setAlternateBackground(enabled
);
2221 bool KItemListView::useAlternateBackgrounds() const
2223 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2226 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2228 QElapsedTimer timer
;
2231 QHash
<QByteArray
, qreal
> widths
;
2233 // Calculate the minimum width for each column that is required
2234 // to show the headline unclipped.
2235 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2236 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2237 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2238 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2239 const QString headerText
= m_model
->roleDescription(visibleRole
);
2240 const qreal headerWidth
= fontMetrics
.horizontalAdvance(headerText
) + gripMargin
+ headerMargin
* 2;
2241 widths
.insert(visibleRole
, headerWidth
);
2244 // Calculate the preferred column widths for each item and ignore values
2245 // smaller than the width for showing the headline unclipped.
2246 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2247 int calculatedItemCount
= 0;
2248 bool maxTimeExceeded
= false;
2249 for (const KItemRange
& itemRange
: itemRanges
) {
2250 const int startIndex
= itemRange
.index
;
2251 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2253 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2254 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2255 qreal maxWidth
= widths
.value(visibleRole
, 0);
2256 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2257 maxWidth
= qMax(width
, maxWidth
);
2258 widths
.insert(visibleRole
, maxWidth
);
2261 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2262 // When having several thousands of items calculating the sizes can get
2263 // very expensive. We accept a possibly too small role-size in favour
2264 // of having no blocking user interface.
2265 maxTimeExceeded
= true;
2268 ++calculatedItemCount
;
2270 if (maxTimeExceeded
) {
2278 void KItemListView::applyColumnWidthsFromHeader()
2280 // Apply the new size to the layouter
2281 const qreal requiredWidth
= columnWidthsSum();
2282 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2283 m_itemSize
.height());
2284 m_layouter
->setItemSize(dynamicItemSize
);
2286 // Update the role sizes for all visible widgets
2287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2288 while (it
.hasNext()) {
2290 updateWidgetColumnWidths(it
.value());
2294 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2296 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2297 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2301 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2303 Q_ASSERT(m_itemSize
.isEmpty());
2304 const int itemCount
= m_model
->count();
2305 int rangesItemCount
= 0;
2306 for (const KItemRange
& range
: itemRanges
) {
2307 rangesItemCount
+= range
.count
;
2310 if (itemCount
== rangesItemCount
) {
2311 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2312 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2313 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2316 // Only a sub range of the roles need to be determined.
2317 // The chances are good that the widths of the sub ranges
2318 // already fit into the available widths and hence no
2319 // expensive update might be required.
2320 bool changed
= false;
2322 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2323 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2324 while (it
.hasNext()) {
2326 const QByteArray
& role
= it
.key();
2327 const qreal updatedWidth
= it
.value();
2328 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2329 if (updatedWidth
> currentWidth
) {
2330 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2336 // All the updated sizes are smaller than the current sizes and no change
2337 // of the stretched roles-widths is required
2342 if (m_headerWidget
->automaticColumnResizing()) {
2343 applyAutomaticColumnWidths();
2347 void KItemListView::updatePreferredColumnWidths()
2350 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2354 void KItemListView::applyAutomaticColumnWidths()
2356 Q_ASSERT(m_itemSize
.isEmpty());
2357 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2358 if (m_visibleRoles
.isEmpty()) {
2362 // Calculate the maximum size of an item by considering the
2363 // visible role sizes and apply them to the layouter. If the
2364 // size does not use the available view-size the size of the
2365 // first role will get stretched.
2367 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2368 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2369 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2372 const QByteArray firstRole
= m_visibleRoles
.first();
2373 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2374 QSizeF dynamicItemSize
= m_itemSize
;
2376 qreal requiredWidth
= columnWidthsSum();
2377 const qreal availableWidth
= size().width();
2378 if (requiredWidth
< availableWidth
) {
2379 // Stretch the first column to use the whole remaining width
2380 firstColumnWidth
+= availableWidth
- requiredWidth
;
2381 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2382 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2383 // Shrink the first column to be able to show as much other
2384 // columns as possible
2385 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2387 // TODO: A proper calculation of the minimum width depends on the implementation
2388 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2390 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2391 if (shrinkedFirstColumnWidth
< minWidth
) {
2392 shrinkedFirstColumnWidth
= minWidth
;
2395 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2396 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2399 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2401 m_layouter
->setItemSize(dynamicItemSize
);
2403 // Update the role sizes for all visible widgets
2404 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2405 while (it
.hasNext()) {
2407 updateWidgetColumnWidths(it
.value());
2411 qreal
KItemListView::columnWidthsSum() const
2413 qreal widthsSum
= 0;
2414 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2415 widthsSum
+= m_headerWidget
->columnWidth(role
);
2420 QRectF
KItemListView::headerBoundaries() const
2422 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2425 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2426 const QSizeF
& newItemSize
,
2427 const QSizeF
& newItemMargin
) const
2429 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2433 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2434 const qreal itemWidth
= m_layouter
->itemSize().width();
2435 if (itemWidth
> 0) {
2436 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2437 newItemSize
.width(),
2438 newItemMargin
.width());
2439 if (m_model
->count() > newColumnCount
) {
2440 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2442 m_layouter
->itemMargin().width());
2443 return oldColumnCount
!= newColumnCount
;
2447 const qreal itemHeight
= m_layouter
->itemSize().height();
2448 if (itemHeight
> 0) {
2449 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2450 newItemSize
.height(),
2451 newItemMargin
.height());
2452 if (m_model
->count() > newRowCount
) {
2453 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2455 m_layouter
->itemMargin().height());
2456 return oldRowCount
!= newRowCount
;
2464 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2466 if (m_itemSize
.isEmpty()) {
2467 // We have only columns or only rows, but no grid: An animation is usually
2468 // welcome when inserting or removing items.
2469 return !supportsItemExpanding();
2472 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2476 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2477 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2478 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2479 // Only animate if up to 2/3 of a row or column are inserted or removed
2480 return changedItemCount
<= maximum
* 2 / 3;
2484 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2486 const QSizeF oldSize
= m_layouter
->size();
2488 m_layouter
->setSize(size
);
2489 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2490 m_layouter
->setSize(oldSize
);
2492 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2493 : maxOffset
> size
.width();
2496 int KItemListView::showDropIndicator(const QPointF
& pos
)
2498 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2499 while (it
.hasNext()) {
2501 const KItemListWidget
* widget
= it
.value();
2503 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2504 const QRectF rect
= itemRect(widget
->index());
2505 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2506 if (m_model
->supportsDropping(widget
->index())) {
2507 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2508 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2509 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2514 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2515 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2517 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2518 if (m_dropIndicator
!= draggingInsertIndicator
) {
2519 m_dropIndicator
= draggingInsertIndicator
;
2523 int index
= widget
->index();
2531 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2532 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2535 void KItemListView::hideDropIndicator()
2537 if (!m_dropIndicator
.isNull()) {
2538 m_dropIndicator
= QRectF();
2543 void KItemListView::updateGroupHeaderHeight()
2545 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2546 qreal groupHeaderMargin
= 0;
2548 if (scrollOrientation() == Qt::Horizontal
) {
2549 // The vertical margin above and below the header should be
2550 // equal to the horizontal margin, not the vertical margin
2551 // from m_styleOption.
2552 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2553 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2554 } else if (m_itemSize
.isEmpty()){
2555 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2556 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2558 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2559 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2561 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2562 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2564 updateVisibleGroupHeaders();
2567 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2569 if (!supportsItemExpanding() || !m_model
) {
2573 if (firstIndex
< 0 || lastIndex
< 0) {
2574 firstIndex
= m_layouter
->firstVisibleIndex();
2575 lastIndex
= m_layouter
->lastVisibleIndex();
2577 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2578 lastIndex
>= m_layouter
->firstVisibleIndex());
2579 if (!isRangeVisible
) {
2584 int previousParents
= 0;
2585 QBitArray previousSiblings
;
2587 // The rootIndex describes the first index where the siblings get
2588 // calculated from. For the calculation the upper most parent item
2589 // is required. For performance reasons it is checked first whether
2590 // the visible items before or after the current range already
2591 // contain a siblings information which can be used as base.
2592 int rootIndex
= firstIndex
;
2594 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2596 // There is no visible widget before the range, check whether there
2597 // is one after the range:
2598 widget
= m_visibleItems
.value(lastIndex
+ 1);
2600 // The sibling information of the widget may only be used if
2601 // all items of the range have the same number of parents.
2602 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2603 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2604 if (m_model
->expandedParentsCount(i
) != parents
) {
2613 // Performance optimization: Use the sibling information of the visible
2614 // widget beside the given range.
2615 previousSiblings
= widget
->siblingsInformation();
2616 if (previousSiblings
.isEmpty()) {
2619 previousParents
= previousSiblings
.count() - 1;
2620 previousSiblings
.truncate(previousParents
);
2622 // Potentially slow path: Go back to the upper most parent of firstIndex
2623 // to be able to calculate the initial value for the siblings.
2624 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2629 Q_ASSERT(previousParents
>= 0);
2630 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2631 // Update the parent-siblings in case if the current item represents
2632 // a child or an upper parent.
2633 const int currentParents
= m_model
->expandedParentsCount(i
);
2634 Q_ASSERT(currentParents
>= 0);
2635 if (previousParents
< currentParents
) {
2636 previousParents
= currentParents
;
2637 previousSiblings
.resize(currentParents
);
2638 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2639 } else if (previousParents
> currentParents
) {
2640 previousParents
= currentParents
;
2641 previousSiblings
.truncate(currentParents
);
2644 if (i
>= firstIndex
) {
2645 // The index represents a visible item. Apply the parent-siblings
2646 // and update the sibling of the current item.
2647 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2652 QBitArray siblings
= previousSiblings
;
2653 siblings
.resize(siblings
.count() + 1);
2654 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2656 widget
->setSiblingsInformation(siblings
);
2661 bool KItemListView::hasSiblingSuccessor(int index
) const
2663 bool hasSuccessor
= false;
2664 const int parentsCount
= m_model
->expandedParentsCount(index
);
2665 int successorIndex
= index
+ 1;
2667 // Search the next sibling
2668 const int itemCount
= m_model
->count();
2669 while (successorIndex
< itemCount
) {
2670 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2671 if (currentParentsCount
== parentsCount
) {
2672 hasSuccessor
= true;
2674 } else if (currentParentsCount
< parentsCount
) {
2680 if (m_grouped
&& hasSuccessor
) {
2681 // If the sibling is part of another group, don't mark it as
2682 // successor as the group header is between the sibling connections.
2683 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2684 if (m_layouter
->isFirstGroupItem(i
)) {
2685 hasSuccessor
= false;
2691 return hasSuccessor
;
2694 void KItemListView::disconnectRoleEditingSignals(int index
)
2696 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2701 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2702 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2703 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2706 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2710 const int minSpeed
= 4;
2711 const int maxSpeed
= 128;
2712 const int speedLimiter
= 96;
2713 const int autoScrollBorder
= 64;
2715 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2716 // This assures that the autoscrolling speed grows gradually.
2717 const int incLimiter
= 1;
2719 if (pos
< autoScrollBorder
) {
2720 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2721 inc
= qMax(inc
, -maxSpeed
);
2722 inc
= qMax(inc
, oldInc
- incLimiter
);
2723 } else if (pos
> range
- autoScrollBorder
) {
2724 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2725 inc
= qMin(inc
, maxSpeed
);
2726 inc
= qMin(inc
, oldInc
+ incLimiter
);
2732 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2734 const qreal availableSize
= size
- itemMargin
;
2735 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2741 KItemListCreatorBase::~KItemListCreatorBase()
2743 qDeleteAll(m_recycleableWidgets
);
2744 qDeleteAll(m_createdWidgets
);
2747 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2749 m_createdWidgets
.insert(widget
);
2752 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2754 Q_ASSERT(m_createdWidgets
.contains(widget
));
2755 m_createdWidgets
.remove(widget
);
2757 if (m_recycleableWidgets
.count() < 100) {
2758 m_recycleableWidgets
.append(widget
);
2759 widget
->setVisible(false);
2765 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2767 if (m_recycleableWidgets
.isEmpty()) {
2771 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2772 m_createdWidgets
.insert(widget
);
2776 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2780 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2782 widget
->setParentItem(nullptr);
2783 widget
->setOpacity(1.0);
2784 pushRecycleableWidget(widget
);
2787 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2791 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2793 header
->setOpacity(1.0);
2794 pushRecycleableWidget(header
);