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),
84 m_oldMaximumScrollOffset(0),
86 m_oldMaximumItemOffset(0),
87 m_skipAutoScrollForRubberBand(false),
88 m_rubberBand(nullptr),
89 m_tapAndHoldIndicator(nullptr),
91 m_autoScrollIncrement(0),
92 m_autoScrollTimer(nullptr),
94 m_headerWidget(nullptr),
95 m_indicatorAnimation(nullptr),
98 setAcceptHoverEvents(true);
99 setAcceptTouchEvents(true);
101 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
103 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
105 m_animation
= new KItemListViewAnimation(this);
106 connect(m_animation
, &KItemListViewAnimation::finished
,
107 this, &KItemListView::slotAnimationFinished
);
109 m_rubberBand
= new KItemListRubberBand(this);
110 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
112 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
113 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
114 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
116 m_indicatorAnimation
->setDuration(150);
117 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
118 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
119 m_indicatorAnimation
->start();
123 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
124 if (m_tapAndHoldIndicator
->isActive()) {
129 m_headerWidget
= new KItemListHeaderWidget(this);
130 m_headerWidget
->setVisible(false);
132 m_header
= new KItemListHeader(this);
134 #ifndef QT_NO_ACCESSIBILITY
135 QAccessible::installFactory(accessibleInterfaceFactory
);
140 KItemListView::~KItemListView()
142 // The group headers are children of the widgets created by
143 // widgetCreator(). So it is mandatory to delete the group headers
145 delete m_groupHeaderCreator
;
146 m_groupHeaderCreator
= nullptr;
148 delete m_widgetCreator
;
149 m_widgetCreator
= nullptr;
151 delete m_sizeHintResolver
;
152 m_sizeHintResolver
= nullptr;
155 void KItemListView::setScrollOffset(qreal offset
)
161 const qreal previousOffset
= m_layouter
->scrollOffset();
162 if (offset
== previousOffset
) {
166 m_layouter
->setScrollOffset(offset
);
167 m_animation
->setScrollOffset(offset
);
169 // Don't check whether the m_layoutTimer is active: Changing the
170 // scroll offset must always trigger a synchronous layout, otherwise
171 // the smooth-scrolling might get jerky.
172 doLayout(NoAnimation
);
173 onScrollOffsetChanged(offset
, previousOffset
);
176 qreal
KItemListView::scrollOffset() const
178 return m_layouter
->scrollOffset();
181 qreal
KItemListView::maximumScrollOffset() const
183 return m_layouter
->maximumScrollOffset();
186 void KItemListView::setItemOffset(qreal offset
)
188 if (m_layouter
->itemOffset() == offset
) {
192 m_layouter
->setItemOffset(offset
);
193 if (m_headerWidget
->isVisible()) {
194 m_headerWidget
->setOffset(offset
);
197 // Don't check whether the m_layoutTimer is active: Changing the
198 // item offset must always trigger a synchronous layout, otherwise
199 // the smooth-scrolling might get jerky.
200 doLayout(NoAnimation
);
203 qreal
KItemListView::itemOffset() const
205 return m_layouter
->itemOffset();
208 qreal
KItemListView::maximumItemOffset() const
210 return m_layouter
->maximumItemOffset();
213 int KItemListView::maximumVisibleItems() const
215 return m_layouter
->maximumVisibleItems();
218 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
220 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
221 m_visibleRoles
= roles
;
222 onVisibleRolesChanged(roles
, previousRoles
);
224 m_sizeHintResolver
->clearCache();
225 m_layouter
->markAsDirty();
227 if (m_itemSize
.isEmpty()) {
228 m_headerWidget
->setColumns(roles
);
229 updatePreferredColumnWidths();
230 if (!m_headerWidget
->automaticColumnResizing()) {
231 // The column-width of new roles are still 0. Apply the preferred
232 // column-width as default with.
233 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
234 if (m_headerWidget
->columnWidth(role
) == 0) {
235 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
236 m_headerWidget
->setColumnWidth(role
, width
);
240 applyColumnWidthsFromHeader();
244 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
245 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
246 (roles
.count() <= 1 && previousRoles
.count() > 1));
248 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
249 while (it
.hasNext()) {
251 KItemListWidget
* widget
= it
.value();
252 widget
->setVisibleRoles(roles
);
253 if (alternateBackgroundsChanged
) {
254 updateAlternateBackgroundForWidget(widget
);
258 doLayout(NoAnimation
);
261 QList
<QByteArray
> KItemListView::visibleRoles() const
263 return m_visibleRoles
;
266 void KItemListView::setAutoScroll(bool enabled
)
268 if (enabled
&& !m_autoScrollTimer
) {
269 m_autoScrollTimer
= new QTimer(this);
270 m_autoScrollTimer
->setSingleShot(true);
271 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
272 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
273 } else if (!enabled
&& m_autoScrollTimer
) {
274 delete m_autoScrollTimer
;
275 m_autoScrollTimer
= nullptr;
279 bool KItemListView::autoScroll() const
281 return m_autoScrollTimer
!= nullptr;
284 void KItemListView::setEnabledSelectionToggles(bool enabled
)
286 if (m_enabledSelectionToggles
!= enabled
) {
287 m_enabledSelectionToggles
= enabled
;
289 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
290 while (it
.hasNext()) {
292 it
.value()->setEnabledSelectionToggle(enabled
);
297 bool KItemListView::enabledSelectionToggles() const
299 return m_enabledSelectionToggles
;
302 KItemListController
* KItemListView::controller() const
307 KItemModelBase
* KItemListView::model() const
312 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
314 delete m_widgetCreator
;
315 m_widgetCreator
= widgetCreator
;
318 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
320 if (!m_widgetCreator
) {
321 m_widgetCreator
= defaultWidgetCreator();
323 return m_widgetCreator
;
326 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
328 delete m_groupHeaderCreator
;
329 m_groupHeaderCreator
= groupHeaderCreator
;
332 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
334 if (!m_groupHeaderCreator
) {
335 m_groupHeaderCreator
= defaultGroupHeaderCreator();
337 return m_groupHeaderCreator
;
340 QSizeF
KItemListView::itemSize() const
345 const KItemListStyleOption
& KItemListView::styleOption() const
347 return m_styleOption
;
350 void KItemListView::setGeometry(const QRectF
& rect
)
352 QGraphicsWidget::setGeometry(rect
);
358 const QSizeF newSize
= rect
.size();
359 if (m_itemSize
.isEmpty()) {
360 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
361 if (m_headerWidget
->automaticColumnResizing()) {
362 applyAutomaticColumnWidths();
364 const qreal requiredWidth
= columnWidthsSum();
365 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
366 m_itemSize
.height());
367 m_layouter
->setItemSize(dynamicItemSize
);
371 m_layouter
->setSize(newSize
);
372 // We don't animate the moving of the items here because
373 // it would look like the items are slow to find their position.
374 doLayout(NoAnimation
);
377 qreal
KItemListView::verticalPageStep() const
379 qreal headerHeight
= 0;
380 if (m_headerWidget
->isVisible()) {
381 headerHeight
= m_headerWidget
->size().height();
383 return size().height() - headerHeight
;
386 std::optional
<int> KItemListView::itemAt(const QPointF
& pos
) const
388 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
389 while (it
.hasNext()) {
392 const KItemListWidget
* widget
= it
.value();
393 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
394 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
402 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
404 if (!m_enabledSelectionToggles
) {
408 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
410 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
411 if (!selectionToggleRect
.isEmpty()) {
412 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
413 return selectionToggleRect
.contains(mappedPos
);
419 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
421 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
423 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
424 if (!expansionToggleRect
.isEmpty()) {
425 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
426 return expansionToggleRect
.contains(mappedPos
);
432 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
434 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
436 const QRectF
&textRect
= widget
->textRect();
437 if (!textRect
.isEmpty()) {
438 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
439 return textRect
.contains(mappedPos
);
445 int KItemListView::firstVisibleIndex() const
447 return m_layouter
->firstVisibleIndex();
450 int KItemListView::lastVisibleIndex() const
452 return m_layouter
->lastVisibleIndex();
455 void KItemListView::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
) const
457 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
460 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
462 if (m_supportsItemExpanding
!= supportsExpanding
) {
463 m_supportsItemExpanding
= supportsExpanding
;
464 updateSiblingsInformation();
465 onSupportsItemExpandingChanged(supportsExpanding
);
469 bool KItemListView::supportsItemExpanding() const
471 return m_supportsItemExpanding
;
474 void KItemListView::setHighlightEntireRow(bool highlightEntireRow
)
476 if (m_highlightEntireRow
!= highlightEntireRow
) {
477 m_highlightEntireRow
= highlightEntireRow
;
478 onHighlightEntireRowChanged(highlightEntireRow
);
482 bool KItemListView::highlightEntireRow() const
484 return m_highlightEntireRow
;
487 void KItemListView::setAlternateBackgrounds(bool alternate
)
489 if (m_alternateBackgrounds
!= alternate
) {
490 m_alternateBackgrounds
= alternate
;
491 updateAlternateBackgrounds();
495 bool KItemListView::alternateBackgrounds() const
497 return m_alternateBackgrounds
;
500 QRectF
KItemListView::itemRect(int index
) const
502 return m_layouter
->itemRect(index
);
505 QRectF
KItemListView::itemContextRect(int index
) const
509 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
511 contextRect
= widget
->iconRect() | widget
->textRect();
512 contextRect
.translate(itemRect(index
).topLeft());
518 bool KItemListView::isElided(int index
) const
520 return m_sizeHintResolver
->isElided(index
);
523 void KItemListView::scrollToItem(int index
)
525 QRectF viewGeometry
= geometry();
526 if (m_headerWidget
->isVisible()) {
527 const qreal headerHeight
= m_headerWidget
->size().height();
528 viewGeometry
.adjust(0, headerHeight
, 0, 0);
530 QRectF currentRect
= itemRect(index
);
532 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
533 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
534 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
536 if (!viewGeometry
.contains(currentRect
)) {
537 qreal newOffset
= scrollOffset();
538 if (scrollOrientation() == Qt::Vertical
) {
539 if (currentRect
.top() < viewGeometry
.top()) {
540 newOffset
+= currentRect
.top() - viewGeometry
.top();
541 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
542 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
545 if (currentRect
.left() < viewGeometry
.left()) {
546 newOffset
+= currentRect
.left() - viewGeometry
.left();
547 } else if (currentRect
.right() > viewGeometry
.right()) {
548 newOffset
+= currentRect
.right() - viewGeometry
.right();
552 if (newOffset
!= scrollOffset()) {
553 Q_EMIT
scrollTo(newOffset
);
558 Q_EMIT
scrollingStopped();
561 void KItemListView::beginTransaction()
563 ++m_activeTransactions
;
564 if (m_activeTransactions
== 1) {
565 onTransactionBegin();
569 void KItemListView::endTransaction()
571 --m_activeTransactions
;
572 if (m_activeTransactions
< 0) {
573 m_activeTransactions
= 0;
574 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
577 if (m_activeTransactions
== 0) {
579 doLayout(m_endTransactionAnimationHint
);
580 m_endTransactionAnimationHint
= Animation
;
584 bool KItemListView::isTransactionActive() const
586 return m_activeTransactions
> 0;
589 void KItemListView::setHeaderVisible(bool visible
)
591 if (visible
&& !m_headerWidget
->isVisible()) {
592 QStyleOptionHeader option
;
593 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
596 m_headerWidget
->setPos(0, 0);
597 m_headerWidget
->resize(size().width(), headerSize
.height());
598 m_headerWidget
->setModel(m_model
);
599 m_headerWidget
->setColumns(m_visibleRoles
);
600 m_headerWidget
->setZValue(1);
602 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
603 this, &KItemListView::slotHeaderColumnWidthChanged
);
604 connect(m_headerWidget
, &KItemListHeaderWidget::leadingPaddingChanged
,
605 this, &KItemListView::slotLeadingPaddingChanged
);
606 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
607 this, &KItemListView::slotHeaderColumnMoved
);
608 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
609 this, &KItemListView::sortOrderChanged
);
610 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
611 this, &KItemListView::sortRoleChanged
);
613 m_layouter
->setHeaderHeight(headerSize
.height());
614 m_headerWidget
->setVisible(true);
615 } else if (!visible
&& m_headerWidget
->isVisible()) {
616 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
617 this, &KItemListView::slotHeaderColumnWidthChanged
);
618 disconnect(m_headerWidget
, &KItemListHeaderWidget::leadingPaddingChanged
,
619 this, &KItemListView::slotLeadingPaddingChanged
);
620 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
621 this, &KItemListView::slotHeaderColumnMoved
);
622 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
623 this, &KItemListView::sortOrderChanged
);
624 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
625 this, &KItemListView::sortRoleChanged
);
627 m_layouter
->setHeaderHeight(0);
628 m_headerWidget
->setVisible(false);
632 bool KItemListView::isHeaderVisible() const
634 return m_headerWidget
->isVisible();
637 KItemListHeader
* KItemListView::header() const
642 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
646 if (indexes
.count() == 1) {
647 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
648 QGraphicsView
* graphicsView
= scene()->views()[0];
649 if (item
&& graphicsView
) {
650 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
653 // TODO: Not implemented yet. Probably extend the interface
654 // from KItemListWidget::createDragPixmap() to return a pixmap
655 // that can be used for multiple indexes.
661 void KItemListView::editRole(int index
, const QByteArray
& role
)
663 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
664 if (!widget
|| m_editingRole
) {
668 m_editingRole
= true;
669 widget
->setEditedRole(role
);
671 connect(widget
, &KItemListWidget::roleEditingCanceled
,
672 this, &KItemListView::slotRoleEditingCanceled
);
673 connect(widget
, &KItemListWidget::roleEditingFinished
,
674 this, &KItemListView::slotRoleEditingFinished
);
676 connect(this, &KItemListView::scrollOffsetChanged
,
677 widget
, &KStandardItemListWidget::finishRoleEditing
);
680 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
682 QGraphicsWidget::paint(painter
, option
, widget
);
684 for (auto animation
: qAsConst(m_rubberBandAnimations
)) {
685 QRectF rubberBandRect
= animation
->property(RubberPropertyName
).toRectF();
687 const QPointF topLeft
= rubberBandRect
.topLeft();
688 if (scrollOrientation() == Qt::Vertical
) {
689 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
691 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
694 QStyleOptionRubberBand opt
;
695 initStyleOption(&opt
);
696 opt
.shape
= QRubberBand::Rectangle
;
698 opt
.rect
= rubberBandRect
.toRect();
702 painter
->setOpacity(animation
->currentValue().toReal());
703 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
708 if (m_rubberBand
->isActive()) {
709 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
710 m_rubberBand
->endPosition()).normalized();
712 const QPointF topLeft
= rubberBandRect
.topLeft();
713 if (scrollOrientation() == Qt::Vertical
) {
714 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
716 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
719 QStyleOptionRubberBand opt
;
720 initStyleOption(&opt
);
721 opt
.shape
= QRubberBand::Rectangle
;
723 opt
.rect
= rubberBandRect
.toRect();
724 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
727 if (m_tapAndHoldIndicator
->isActive()) {
728 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
729 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
730 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
731 QStyleOptionRubberBand opt
;
732 initStyleOption(&opt
);
733 opt
.shape
= QRubberBand::Rectangle
;
735 opt
.rect
= rubberBandRect
.toRect();
736 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
739 if (!m_dropIndicator
.isEmpty()) {
740 const QRectF r
= m_dropIndicator
.toRect();
742 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
743 painter
->setPen(color
);
745 // TODO: The following implementation works only for a vertical scroll-orientation
746 // and assumes a height of the m_draggingInsertIndicator of 1.
747 Q_ASSERT(r
.height() == 1);
748 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
751 painter
->setPen(color
);
752 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
756 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
758 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
759 if (!scene()->views().isEmpty()) {
760 m_styleOption
.palette
= scene()->views().at(0)->palette();
763 return QGraphicsItem::itemChange(change
, value
);
766 void KItemListView::setItemSize(const QSizeF
& size
)
768 const QSizeF previousSize
= m_itemSize
;
769 if (size
== previousSize
) {
773 // Skip animations when the number of rows or columns
774 // are changed in the grid layout. Although the animation
775 // engine can handle this usecase, it looks obtrusive.
776 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
778 m_layouter
->itemMargin());
780 const bool alternateBackgroundsChanged
= m_alternateBackgrounds
&&
781 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
782 (!m_itemSize
.isEmpty() && size
.isEmpty()));
786 if (alternateBackgroundsChanged
) {
787 // For an empty item size alternate backgrounds are drawn if more than
788 // one role is shown. Assure that the backgrounds for visible items are
789 // updated when changing the size in this context.
790 updateAlternateBackgrounds();
793 if (size
.isEmpty()) {
794 if (m_headerWidget
->automaticColumnResizing()) {
795 updatePreferredColumnWidths();
797 // Only apply the changed height and respect the header widths
799 const qreal currentWidth
= m_layouter
->itemSize().width();
800 const QSizeF
newSize(currentWidth
, size
.height());
801 m_layouter
->setItemSize(newSize
);
804 m_layouter
->setItemSize(size
);
807 m_sizeHintResolver
->clearCache();
808 doLayout(animate
? Animation
: NoAnimation
);
809 onItemSizeChanged(size
, previousSize
);
812 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
814 if (m_styleOption
== option
) {
818 const KItemListStyleOption previousOption
= m_styleOption
;
819 m_styleOption
= option
;
822 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
823 if (margin
!= m_layouter
->itemMargin()) {
824 // Skip animations when the number of rows or columns
825 // are changed in the grid layout. Although the animation
826 // engine can handle this usecase, it looks obtrusive.
827 animate
= !changesItemGridLayout(m_layouter
->size(),
828 m_layouter
->itemSize(),
830 m_layouter
->setItemMargin(margin
);
834 updateGroupHeaderHeight();
838 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
839 // Animating a change of the maximum text size just results in expensive
840 // temporary eliding and clipping operations and does not look good visually.
844 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
845 while (it
.hasNext()) {
847 it
.value()->setStyleOption(option
);
850 m_sizeHintResolver
->clearCache();
851 m_layouter
->markAsDirty();
852 doLayout(animate
? Animation
: NoAnimation
);
854 if (m_itemSize
.isEmpty()) {
855 updatePreferredColumnWidths();
858 onStyleOptionChanged(option
, previousOption
);
861 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
863 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
864 if (orientation
== previousOrientation
) {
868 m_layouter
->setScrollOrientation(orientation
);
869 m_animation
->setScrollOrientation(orientation
);
870 m_sizeHintResolver
->clearCache();
873 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
874 while (it
.hasNext()) {
876 it
.value()->setScrollOrientation(orientation
);
878 updateGroupHeaderHeight();
882 doLayout(NoAnimation
);
884 onScrollOrientationChanged(orientation
, previousOrientation
);
885 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
888 Qt::Orientation
KItemListView::scrollOrientation() const
890 return m_layouter
->scrollOrientation();
893 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
898 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
903 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
908 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
910 Q_UNUSED(changedRoles
)
914 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
920 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
926 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
932 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
938 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
944 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
950 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
956 void KItemListView::onHighlightEntireRowChanged(bool highlightEntireRow
)
958 Q_UNUSED(highlightEntireRow
)
961 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
963 Q_UNUSED(supportsExpanding
)
966 void KItemListView::onTransactionBegin()
970 void KItemListView::onTransactionEnd()
974 bool KItemListView::event(QEvent
* event
)
976 switch (event
->type()) {
977 case QEvent::PaletteChange
:
981 case QEvent::FontChange
:
986 // Forward all other events to the controller and handle them there
987 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
993 return QGraphicsWidget::event(event
);
996 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
998 m_mousePos
= transform().map(event
->pos());
1002 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
1004 QGraphicsWidget::mouseMoveEvent(event
);
1006 m_mousePos
= transform().map(event
->pos());
1007 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1008 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1012 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
1014 event
->setAccepted(true);
1015 setAutoScroll(true);
1018 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
1020 QGraphicsWidget::dragMoveEvent(event
);
1022 m_mousePos
= transform().map(event
->pos());
1023 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
1024 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
1028 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
1030 QGraphicsWidget::dragLeaveEvent(event
);
1031 setAutoScroll(false);
1034 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
1036 QGraphicsWidget::dropEvent(event
);
1037 setAutoScroll(false);
1040 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
1042 return m_visibleItems
.values();
1045 void KItemListView::updateFont()
1047 if (scene() && !scene()->views().isEmpty()) {
1048 KItemListStyleOption option
= styleOption();
1049 option
.font
= scene()->views().first()->font();
1050 option
.fontMetrics
= QFontMetrics(option
.font
);
1052 setStyleOption(option
);
1056 void KItemListView::updatePalette()
1058 if (scene() && !scene()->views().isEmpty()) {
1059 KItemListStyleOption option
= styleOption();
1060 option
.palette
= scene()->views().first()->palette();
1062 setStyleOption(option
);
1066 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1068 if (m_itemSize
.isEmpty()) {
1069 updatePreferredColumnWidths(itemRanges
);
1072 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1073 if (hasMultipleRanges
) {
1077 m_layouter
->markAsDirty();
1079 m_sizeHintResolver
->itemsInserted(itemRanges
);
1081 int previouslyInsertedCount
= 0;
1082 for (const KItemRange
& range
: itemRanges
) {
1083 // range.index is related to the model before anything has been inserted.
1084 // As in each loop the current item-range gets inserted the index must
1085 // be increased by the already previously inserted items.
1086 const int index
= range
.index
+ previouslyInsertedCount
;
1087 const int count
= range
.count
;
1088 if (index
< 0 || count
<= 0) {
1089 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1092 previouslyInsertedCount
+= count
;
1094 // Determine which visible items must be moved
1095 QList
<int> itemsToMove
;
1096 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1097 while (it
.hasNext()) {
1099 const int visibleItemIndex
= it
.key();
1100 if (visibleItemIndex
>= index
) {
1101 itemsToMove
.append(visibleItemIndex
);
1105 // Update the indexes of all KItemListWidget instances that are located
1106 // after the inserted items. It is important to adjust the indexes in the order
1107 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1108 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1109 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1110 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1112 const int newIndex
= widget
->index() + count
;
1113 if (hasMultipleRanges
) {
1114 setWidgetIndex(widget
, newIndex
);
1116 // Try to animate the moving of the item
1117 moveWidgetToIndex(widget
, newIndex
);
1121 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1122 // Check whether a scrollbar is required to show the inserted items. In this case
1123 // the size of the layouter will be decreased before calling doLayout(): This prevents
1124 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1125 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1126 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1127 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1128 if (decreaseLayouterSize
) {
1129 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1131 int scrollbarSpacing
= 0;
1132 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1133 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1136 QSizeF layouterSize
= m_layouter
->size();
1137 if (verticalScrollOrientation
) {
1138 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1140 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1142 m_layouter
->setSize(layouterSize
);
1146 if (!hasMultipleRanges
) {
1147 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1148 updateSiblingsInformation();
1153 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1156 if (hasMultipleRanges
) {
1157 m_endTransactionAnimationHint
= NoAnimation
;
1160 updateSiblingsInformation();
1163 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1164 // In case if items of the same group have been inserted before an item that
1165 // currently represents the first item of the group, the group header of
1166 // this item must be removed.
1167 updateVisibleGroupHeaders();
1170 if (useAlternateBackgrounds()) {
1171 updateAlternateBackgrounds();
1175 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1177 if (m_itemSize
.isEmpty()) {
1178 // Don't pass the item-range: The preferred column-widths of
1179 // all items must be adjusted when removing items.
1180 updatePreferredColumnWidths();
1183 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1184 if (hasMultipleRanges
) {
1188 m_layouter
->markAsDirty();
1190 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1192 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1193 const KItemRange
& range
= itemRanges
[i
];
1194 const int index
= range
.index
;
1195 const int count
= range
.count
;
1196 if (index
< 0 || count
<= 0) {
1197 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1201 const int firstRemovedIndex
= index
;
1202 const int lastRemovedIndex
= index
+ count
- 1;
1204 // Remember which items have to be moved because they are behind the removed range.
1205 QVector
<int> itemsToMove
;
1207 // Remove all KItemListWidget instances that got deleted
1208 // Iterate over a const copy because the container is mutated within the loop
1209 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1210 const auto visibleItems
= m_visibleItems
;
1211 for (KItemListWidget
* widget
: visibleItems
) {
1212 const int i
= widget
->index();
1213 if (i
< firstRemovedIndex
) {
1215 } else if (i
> lastRemovedIndex
) {
1216 itemsToMove
.append(i
);
1220 m_animation
->stop(widget
);
1221 // Stopping the animation might lead to recycling the widget if
1222 // it is invisible (see slotAnimationFinished()).
1223 // Check again whether it is still visible:
1224 if (!m_visibleItems
.contains(i
)) {
1228 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1229 // Remove the widget without animation
1230 recycleWidget(widget
);
1232 // Animate the removing of the items. Special case: When removing an item there
1233 // is no valid model index available anymore. For the
1234 // remove-animation the item gets removed from m_visibleItems but the widget
1235 // will stay alive until the animation has been finished and will
1236 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1237 m_visibleItems
.remove(i
);
1238 widget
->setIndex(-1);
1239 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1243 // Update the indexes of all KItemListWidget instances that are located
1244 // after the deleted items. It is important to update them in ascending
1245 // order to prevent overlaps when setting the new index.
1246 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1247 for (int i
: qAsConst(itemsToMove
)) {
1248 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1250 const int newIndex
= i
- count
;
1251 if (hasMultipleRanges
) {
1252 setWidgetIndex(widget
, newIndex
);
1254 // Try to animate the moving of the item
1255 moveWidgetToIndex(widget
, newIndex
);
1259 if (!hasMultipleRanges
) {
1260 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1261 // assumes an updated geometry. If items are removed during an active transaction,
1262 // the transaction will be temporary deactivated so that doLayout() triggers a
1263 // geometry update if necessary.
1264 const int activeTransactions
= m_activeTransactions
;
1265 m_activeTransactions
= 0;
1266 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1267 m_activeTransactions
= activeTransactions
;
1268 updateSiblingsInformation();
1273 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1276 if (hasMultipleRanges
) {
1277 m_endTransactionAnimationHint
= NoAnimation
;
1279 updateSiblingsInformation();
1282 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1283 // In case if the first item of a group has been removed, the group header
1284 // must be applied to the next visible item.
1285 updateVisibleGroupHeaders();
1288 if (useAlternateBackgrounds()) {
1289 updateAlternateBackgrounds();
1293 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1295 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1296 m_layouter
->markAsDirty();
1299 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1302 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1303 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1305 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1306 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1308 updateWidgetProperties(widget
, index
);
1309 initializeItemListWidget(widget
);
1313 doLayout(NoAnimation
);
1314 updateSiblingsInformation();
1317 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1318 const QSet
<QByteArray
>& roles
)
1320 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1321 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1322 updatePreferredColumnWidths(itemRanges
);
1325 for (const KItemRange
& itemRange
: itemRanges
) {
1326 const int index
= itemRange
.index
;
1327 const int count
= itemRange
.count
;
1329 if (updateSizeHints
) {
1330 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1331 m_layouter
->markAsDirty();
1334 // Apply the changed roles to the visible item-widgets
1335 const int lastIndex
= index
+ count
- 1;
1336 for (int i
= index
; i
<= lastIndex
; ++i
) {
1337 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1339 widget
->setData(m_model
->data(i
), roles
);
1343 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1344 // The sort-role has been changed which might result
1345 // in modified group headers
1346 updateVisibleGroupHeaders();
1347 doLayout(NoAnimation
);
1350 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1351 ev
.setFirstRow(itemRange
.index
);
1352 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1353 QAccessible::updateAccessibility(&ev
);
1356 doLayout(NoAnimation
);
1359 void KItemListView::slotGroupsChanged()
1361 updateVisibleGroupHeaders();
1362 doLayout(NoAnimation
);
1363 updateSiblingsInformation();
1366 void KItemListView::slotGroupedSortingChanged(bool current
)
1368 m_grouped
= current
;
1369 m_layouter
->markAsDirty();
1372 updateGroupHeaderHeight();
1374 // Clear all visible headers. Note that the QHashIterator takes a copy of
1375 // m_visibleGroups. Therefore, it remains valid even if items are removed
1376 // from m_visibleGroups in recycleGroupHeaderForWidget().
1377 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1378 while (it
.hasNext()) {
1380 recycleGroupHeaderForWidget(it
.key());
1382 Q_ASSERT(m_visibleGroups
.isEmpty());
1385 if (useAlternateBackgrounds()) {
1386 // Changing the group mode requires to update the alternate backgrounds
1387 // as with the enabled group mode the altering is done on base of the first
1389 updateAlternateBackgrounds();
1391 updateSiblingsInformation();
1392 doLayout(NoAnimation
);
1395 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1400 updateVisibleGroupHeaders();
1401 doLayout(NoAnimation
);
1405 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1410 updateVisibleGroupHeaders();
1411 doLayout(NoAnimation
);
1415 void KItemListView::slotCurrentChanged(int current
, int previous
)
1419 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1420 // always the selected item. It is not necessary to highlight the current item then.
1421 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1422 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1423 if (previousWidget
) {
1424 previousWidget
->setCurrent(false);
1427 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1428 if (currentWidget
) {
1429 currentWidget
->setCurrent(true);
1433 QAccessibleEvent
ev(this, QAccessible::Focus
);
1434 ev
.setChild(current
);
1435 QAccessible::updateAccessibility(&ev
);
1438 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1442 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1443 while (it
.hasNext()) {
1445 const int index
= it
.key();
1446 KItemListWidget
* widget
= it
.value();
1447 widget
->setSelected(current
.contains(index
));
1451 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1452 KItemListViewAnimation::AnimationType type
)
1454 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1455 Q_ASSERT(itemListWidget
);
1457 if (type
== KItemListViewAnimation::DeleteAnimation
) {
1458 // As we recycle the widget in this case it is important to assure that no
1459 // other animation has been started. This is a convention in KItemListView and
1460 // not a requirement defined by KItemListViewAnimation.
1461 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1463 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1464 // by m_visibleWidgets and must be deleted manually after the animation has
1466 recycleGroupHeaderForWidget(itemListWidget
);
1467 widgetCreator()->recycle(itemListWidget
);
1469 const int index
= itemListWidget
->index();
1470 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1471 (index
> m_layouter
->lastVisibleIndex());
1472 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1473 recycleWidget(itemListWidget
);
1478 void KItemListView::slotRubberBandPosChanged()
1483 void KItemListView::slotRubberBandActivationChanged(bool active
)
1486 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1487 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1488 m_skipAutoScrollForRubberBand
= true;
1490 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
1491 m_rubberBand
->endPosition()).normalized();
1493 auto animation
= new QVariantAnimation(this);
1494 animation
->setStartValue(1.0);
1495 animation
->setEndValue(0.0);
1496 animation
->setDuration(RubberFadeSpeed
);
1497 animation
->setProperty(RubberPropertyName
, rubberBandRect
);
1500 curve
.setType(QEasingCurve::BezierSpline
);
1501 curve
.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1502 animation
->setEasingCurve(curve
);
1504 connect(animation
, &QVariantAnimation::valueChanged
, this, [=](const QVariant
&) {
1507 connect(animation
, &QVariantAnimation::finished
, this, [=]() {
1508 m_rubberBandAnimations
.removeAll(animation
);
1512 m_rubberBandAnimations
<< animation
;
1514 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1515 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1516 m_skipAutoScrollForRubberBand
= false;
1522 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1524 qreal previousWidth
)
1527 Q_UNUSED(currentWidth
)
1528 Q_UNUSED(previousWidth
)
1530 m_headerWidget
->setAutomaticColumnResizing(false);
1531 applyColumnWidthsFromHeader();
1532 doLayout(NoAnimation
);
1535 void KItemListView::slotLeadingPaddingChanged(qreal width
)
1538 if (m_headerWidget
->automaticColumnResizing()) {
1539 applyAutomaticColumnWidths();
1541 applyColumnWidthsFromHeader();
1542 doLayout(NoAnimation
);
1545 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1549 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1551 const QList
<QByteArray
> previous
= m_visibleRoles
;
1553 QList
<QByteArray
> current
= m_visibleRoles
;
1554 current
.removeAt(previousIndex
);
1555 current
.insert(currentIndex
, role
);
1557 setVisibleRoles(current
);
1559 Q_EMIT
visibleRolesChanged(current
, previous
);
1562 void KItemListView::triggerAutoScrolling()
1564 if (!m_autoScrollTimer
) {
1569 int visibleSize
= 0;
1570 if (scrollOrientation() == Qt::Vertical
) {
1571 pos
= m_mousePos
.y();
1572 visibleSize
= size().height();
1574 pos
= m_mousePos
.x();
1575 visibleSize
= size().width();
1578 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1579 m_autoScrollIncrement
= 0;
1582 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1583 if (m_autoScrollIncrement
== 0) {
1584 // The mouse position is not above an autoscroll margin (the autoscroll timer
1585 // will be restarted in mouseMoveEvent())
1586 m_autoScrollTimer
->stop();
1590 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1591 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1592 // if the direction of the rubberband is similar to the autoscroll direction. This
1593 // prevents that starting to create a rubberband within the autoscroll margins starts
1594 // an autoscrolling.
1596 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1597 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1598 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1599 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1600 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1601 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1602 // been moved up although the autoscroll direction might be down)
1603 m_autoScrollTimer
->stop();
1608 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1609 // the autoscrolling may not get skipped anymore until a new rubberband is created
1610 m_skipAutoScrollForRubberBand
= false;
1612 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1613 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1614 setScrollOffset(newScrollOffset
);
1616 // Trigger the autoscroll timer which will periodically call
1617 // triggerAutoScrolling()
1618 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1621 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1623 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1625 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1626 Q_ASSERT(groupHeader
);
1627 updateGroupHeaderLayout(widget
);
1630 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1632 disconnectRoleEditingSignals(index
);
1634 m_editingRole
= false;
1635 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1638 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1640 disconnectRoleEditingSignals(index
);
1642 m_editingRole
= false;
1643 Q_EMIT
roleEditingFinished(index
, role
, value
);
1646 void KItemListView::setController(KItemListController
* controller
)
1648 if (m_controller
!= controller
) {
1649 KItemListController
* previous
= m_controller
;
1651 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1652 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1653 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1656 m_controller
= controller
;
1659 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1660 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1661 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1664 onControllerChanged(controller
, previous
);
1668 void KItemListView::setModel(KItemModelBase
* model
)
1670 if (m_model
== model
) {
1674 KItemModelBase
* previous
= m_model
;
1677 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1678 this, &KItemListView::slotItemsChanged
);
1679 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1680 this, &KItemListView::slotItemsInserted
);
1681 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1682 this, &KItemListView::slotItemsRemoved
);
1683 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1684 this, &KItemListView::slotItemsMoved
);
1685 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1686 this, &KItemListView::slotGroupsChanged
);
1687 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1688 this, &KItemListView::slotGroupedSortingChanged
);
1689 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1690 this, &KItemListView::slotSortOrderChanged
);
1691 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1692 this, &KItemListView::slotSortRoleChanged
);
1694 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1698 m_layouter
->setModel(model
);
1699 m_grouped
= model
->groupedSorting();
1702 connect(m_model
, &KItemModelBase::itemsChanged
,
1703 this, &KItemListView::slotItemsChanged
);
1704 connect(m_model
, &KItemModelBase::itemsInserted
,
1705 this, &KItemListView::slotItemsInserted
);
1706 connect(m_model
, &KItemModelBase::itemsRemoved
,
1707 this, &KItemListView::slotItemsRemoved
);
1708 connect(m_model
, &KItemModelBase::itemsMoved
,
1709 this, &KItemListView::slotItemsMoved
);
1710 connect(m_model
, &KItemModelBase::groupsChanged
,
1711 this, &KItemListView::slotGroupsChanged
);
1712 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1713 this, &KItemListView::slotGroupedSortingChanged
);
1714 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1715 this, &KItemListView::slotSortOrderChanged
);
1716 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1717 this, &KItemListView::slotSortRoleChanged
);
1719 const int itemCount
= m_model
->count();
1720 if (itemCount
> 0) {
1721 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1725 onModelChanged(model
, previous
);
1728 KItemListRubberBand
* KItemListView::rubberBand() const
1730 return m_rubberBand
;
1733 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1735 if (m_activeTransactions
> 0) {
1736 if (hint
== NoAnimation
) {
1737 // As soon as at least one property change should be done without animation,
1738 // the whole transaction will be marked as not animated.
1739 m_endTransactionAnimationHint
= NoAnimation
;
1744 if (!m_model
|| m_model
->count() < 0) {
1748 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1749 if (firstVisibleIndex
< 0) {
1750 emitOffsetChanges();
1754 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1755 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1756 // is still shown if the maximum offset got decreased.
1757 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1758 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1759 if (scrollOffset() > maxOffsetToShowFullRange
) {
1760 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1761 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1764 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1766 int firstSibblingIndex
= -1;
1767 int lastSibblingIndex
= -1;
1768 const bool supportsExpanding
= supportsItemExpanding();
1770 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1772 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1773 // instances from invisible items are reused. If no reusable items are
1774 // found then new KItemListWidget instances get created.
1775 const bool animate
= (hint
== Animation
);
1776 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1777 bool applyNewPos
= true;
1779 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1780 const QPointF newPos
= itemBounds
.topLeft();
1781 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1783 if (!reusableItems
.isEmpty()) {
1784 // Reuse a KItemListWidget instance from an invisible item
1785 const int oldIndex
= reusableItems
.takeLast();
1786 widget
= m_visibleItems
.value(oldIndex
);
1787 setWidgetIndex(widget
, i
);
1788 updateWidgetProperties(widget
, i
);
1789 initializeItemListWidget(widget
);
1791 // No reusable KItemListWidget instance is available, create a new one
1792 widget
= createWidget(i
);
1794 widget
->resize(itemBounds
.size());
1796 if (animate
&& changedCount
< 0) {
1797 // Items have been deleted.
1798 if (i
>= changedIndex
) {
1799 // The item is located behind the removed range. Move the
1800 // created item to the imaginary old position outside the
1801 // view. It will get animated to the new position later.
1802 const int previousIndex
= i
- changedCount
;
1803 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1804 if (itemRect
.isEmpty()) {
1805 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1806 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1807 widget
->setPos(invisibleOldPos
);
1809 widget
->setPos(itemRect
.topLeft());
1811 applyNewPos
= false;
1815 if (supportsExpanding
&& changedCount
== 0) {
1816 if (firstSibblingIndex
< 0) {
1817 firstSibblingIndex
= i
;
1819 lastSibblingIndex
= i
;
1824 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1825 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1826 applyNewPos
= false;
1829 const bool itemsRemoved
= (changedCount
< 0);
1830 const bool itemsInserted
= (changedCount
> 0);
1831 if (itemsRemoved
&& (i
>= changedIndex
)) {
1832 // The item is located after the removed items. Animate the moving of the position.
1833 applyNewPos
= !moveWidget(widget
, newPos
);
1834 } else if (itemsInserted
&& i
>= changedIndex
) {
1835 // The item is located after the first inserted item
1836 if (i
<= changedIndex
+ changedCount
- 1) {
1837 // The item is an inserted item. Animate the appearing of the item.
1838 // For performance reasons no animation is done when changedCount is equal
1839 // to all available items.
1840 if (changedCount
< m_model
->count()) {
1841 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1843 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1844 // The item was already there before, so animate the moving of the position.
1845 // No moving animation is done if the item is animated by a create animation: This
1846 // prevents a "move animation mess" when inserting several ranges in parallel.
1847 applyNewPos
= !moveWidget(widget
, newPos
);
1851 m_animation
->stop(widget
);
1855 widget
->setPos(newPos
);
1858 Q_ASSERT(widget
->index() == i
);
1859 widget
->setVisible(true);
1861 bool animateIconResizing
= animate
;
1863 if (widget
->size() != itemBounds
.size()) {
1864 // Resize the widget for the item to the changed size.
1866 // If a dynamic item size is used then no animation is done in the direction
1867 // of the dynamic size.
1868 if (m_itemSize
.width() <= 0) {
1869 // The width is dynamic, apply the new width without animation.
1870 widget
->resize(itemBounds
.width(), widget
->size().height());
1871 } else if (m_itemSize
.height() <= 0) {
1872 // The height is dynamic, apply the new height without animation.
1873 widget
->resize(widget
->size().width(), itemBounds
.height());
1875 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1877 widget
->resize(itemBounds
.size());
1880 animateIconResizing
= false;
1883 const int newIconSize
= widget
->styleOption().iconSize
;
1884 if (widget
->iconSize() != newIconSize
) {
1885 if (animateIconResizing
) {
1886 m_animation
->start(widget
, KItemListViewAnimation::IconResizeAnimation
, newIconSize
);
1888 widget
->setIconSize(newIconSize
);
1892 // Updating the cell-information must be done as last step: The decision whether the
1893 // moving-animation should be started at all is based on the previous cell-information.
1894 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1895 m_visibleCells
.insert(i
, cell
);
1898 // Delete invisible KItemListWidget instances that have not been reused
1899 for (int index
: qAsConst(reusableItems
)) {
1900 recycleWidget(m_visibleItems
.value(index
));
1903 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1904 Q_ASSERT(lastSibblingIndex
>= 0);
1905 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1909 // Update the layout of all visible group headers
1910 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1911 while (it
.hasNext()) {
1913 updateGroupHeaderLayout(it
.key());
1917 emitOffsetChanges();
1920 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1921 int lastVisibleIndex
,
1922 LayoutAnimationHint hint
)
1924 // Determine all items that are completely invisible and might be
1925 // reused for items that just got (at least partly) visible. If the
1926 // animation hint is set to 'Animation' items that do e.g. an animated
1927 // moving of their position are not marked as invisible: This assures
1928 // that a scrolling inside the view can be done without breaking an animation.
1932 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1933 while (it
.hasNext()) {
1936 KItemListWidget
* widget
= it
.value();
1937 const int index
= widget
->index();
1938 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1941 if (m_animation
->isStarted(widget
)) {
1942 if (hint
== NoAnimation
) {
1943 // Stopping the animation will call KItemListView::slotAnimationFinished()
1944 // and the widget will be recycled if necessary there.
1945 m_animation
->stop(widget
);
1948 widget
->setVisible(false);
1949 items
.append(index
);
1952 recycleGroupHeaderForWidget(widget
);
1961 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1963 if (widget
->pos() == newPos
) {
1967 bool startMovingAnim
= false;
1969 if (m_itemSize
.isEmpty()) {
1970 // The items are not aligned in a grid but either as columns or rows.
1971 startMovingAnim
= true;
1973 // When having a grid the moving-animation should only be started, if it is done within
1974 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1975 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1976 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1977 const int index
= widget
->index();
1978 const Cell cell
= m_visibleCells
.value(index
);
1979 if (cell
.column
>= 0 && cell
.row
>= 0) {
1980 if (scrollOrientation() == Qt::Vertical
) {
1981 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1983 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1988 if (startMovingAnim
) {
1989 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1993 m_animation
->stop(widget
);
1994 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1998 void KItemListView::emitOffsetChanges()
2000 const qreal newScrollOffset
= m_layouter
->scrollOffset();
2001 if (m_oldScrollOffset
!= newScrollOffset
) {
2002 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
2003 m_oldScrollOffset
= newScrollOffset
;
2006 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
2007 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
2008 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
2009 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
2012 const qreal newItemOffset
= m_layouter
->itemOffset();
2013 if (m_oldItemOffset
!= newItemOffset
) {
2014 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
2015 m_oldItemOffset
= newItemOffset
;
2018 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
2019 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
2020 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
2021 m_oldMaximumItemOffset
= newMaximumItemOffset
;
2025 KItemListWidget
* KItemListView::createWidget(int index
)
2027 KItemListWidget
* widget
= widgetCreator()->create(this);
2028 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
2030 m_visibleItems
.insert(index
, widget
);
2031 m_visibleCells
.insert(index
, Cell());
2032 updateWidgetProperties(widget
, index
);
2033 initializeItemListWidget(widget
);
2037 void KItemListView::recycleWidget(KItemListWidget
* widget
)
2040 recycleGroupHeaderForWidget(widget
);
2043 const int index
= widget
->index();
2044 m_visibleItems
.remove(index
);
2045 m_visibleCells
.remove(index
);
2047 widgetCreator()->recycle(widget
);
2050 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
2052 const int oldIndex
= widget
->index();
2053 m_visibleItems
.remove(oldIndex
);
2054 m_visibleCells
.remove(oldIndex
);
2056 m_visibleItems
.insert(index
, widget
);
2057 m_visibleCells
.insert(index
, Cell());
2059 widget
->setIndex(index
);
2062 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
2064 const int oldIndex
= widget
->index();
2065 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
2067 setWidgetIndex(widget
, index
);
2069 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2070 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2071 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
2072 (!vertical
&& oldCell
.column
== newCell
.column
);
2074 m_visibleCells
.insert(index
, newCell
);
2078 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2081 case LayouterSize
: m_layouter
->setSize(size
); break;
2082 case ItemSize
: m_layouter
->setItemSize(size
); break;
2087 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2089 widget
->setVisibleRoles(m_visibleRoles
);
2090 updateWidgetColumnWidths(widget
);
2091 widget
->setStyleOption(m_styleOption
);
2093 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2095 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2096 // always the selected item. It is not necessary to highlight the current item then.
2097 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2098 widget
->setCurrent(index
== selectionManager
->currentItem());
2100 widget
->setSelected(selectionManager
->isSelected(index
));
2101 widget
->setHovered(false);
2102 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2103 widget
->setIndex(index
);
2104 widget
->setData(m_model
->data(index
));
2105 widget
->setSiblingsInformation(QBitArray());
2106 updateAlternateBackgroundForWidget(widget
);
2109 updateGroupHeaderForWidget(widget
);
2113 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2115 Q_ASSERT(m_grouped
);
2117 const int index
= widget
->index();
2118 if (!m_layouter
->isFirstGroupItem(index
)) {
2119 // The widget does not represent the first item of a group
2120 // and hence requires no header
2121 recycleGroupHeaderForWidget(widget
);
2125 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2126 if (groups
.isEmpty() || !groupHeaderCreator()) {
2130 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2132 groupHeader
= groupHeaderCreator()->create(this);
2133 groupHeader
->setParentItem(widget
);
2134 m_visibleGroups
.insert(widget
, groupHeader
);
2135 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2137 Q_ASSERT(groupHeader
->parentItem() == widget
);
2139 const int groupIndex
= groupIndexForItem(index
);
2140 Q_ASSERT(groupIndex
>= 0);
2141 groupHeader
->setData(groups
.at(groupIndex
).second
);
2142 groupHeader
->setRole(model()->sortRole());
2143 groupHeader
->setStyleOption(m_styleOption
);
2144 groupHeader
->setScrollOrientation(scrollOrientation());
2145 groupHeader
->setItemIndex(index
);
2147 groupHeader
->show();
2150 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2152 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2153 Q_ASSERT(groupHeader
);
2155 const int index
= widget
->index();
2156 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2157 const QRectF itemRect
= m_layouter
->itemRect(index
);
2159 // The group-header is a child of the itemlist widget. Translate the
2160 // group header position to the relative position.
2161 if (scrollOrientation() == Qt::Vertical
) {
2162 // In the vertical scroll orientation the group header should always span
2163 // the whole width no matter which temporary position the parent widget
2164 // has. In this case the x-position and width will be adjusted manually.
2165 const qreal x
= -widget
->x() - itemOffset();
2166 const qreal width
= maximumItemOffset();
2167 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2168 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2170 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2171 groupHeader
->resize(groupHeaderRect
.size());
2175 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2177 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2179 header
->setParentItem(nullptr);
2180 groupHeaderCreator()->recycle(header
);
2181 m_visibleGroups
.remove(widget
);
2182 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2186 void KItemListView::updateVisibleGroupHeaders()
2188 Q_ASSERT(m_grouped
);
2189 m_layouter
->markAsDirty();
2191 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2192 while (it
.hasNext()) {
2194 updateGroupHeaderForWidget(it
.value());
2198 int KItemListView::groupIndexForItem(int index
) const
2200 Q_ASSERT(m_grouped
);
2202 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2203 if (groups
.isEmpty()) {
2208 int max
= groups
.count() - 1;
2211 mid
= (min
+ max
) / 2;
2212 if (index
> groups
[mid
].first
) {
2217 } while (groups
[mid
].first
!= index
&& min
<= max
);
2220 while (groups
[mid
].first
> index
&& mid
> 0) {
2228 void KItemListView::updateAlternateBackgrounds()
2230 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2231 while (it
.hasNext()) {
2233 updateAlternateBackgroundForWidget(it
.value());
2237 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2239 bool enabled
= useAlternateBackgrounds();
2241 const int index
= widget
->index();
2242 enabled
= (index
& 0x1) > 0;
2244 const int groupIndex
= groupIndexForItem(index
);
2245 if (groupIndex
>= 0) {
2246 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2247 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2248 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2249 enabled
= (relativeIndex
& 0x1) > 0;
2253 widget
->setAlternateBackground(enabled
);
2256 bool KItemListView::useAlternateBackgrounds() const
2258 return m_alternateBackgrounds
&& m_itemSize
.isEmpty();
2261 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2263 QElapsedTimer timer
;
2266 QHash
<QByteArray
, qreal
> widths
;
2268 // Calculate the minimum width for each column that is required
2269 // to show the headline unclipped.
2270 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2271 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2272 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2273 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2274 const QString headerText
= m_model
->roleDescription(visibleRole
);
2275 const qreal headerWidth
= fontMetrics
.horizontalAdvance(headerText
) + gripMargin
+ headerMargin
* 2;
2276 widths
.insert(visibleRole
, headerWidth
);
2279 // Calculate the preferred column widths for each item and ignore values
2280 // smaller than the width for showing the headline unclipped.
2281 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2282 int calculatedItemCount
= 0;
2283 bool maxTimeExceeded
= false;
2284 for (const KItemRange
& itemRange
: itemRanges
) {
2285 const int startIndex
= itemRange
.index
;
2286 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2288 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2289 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2290 qreal maxWidth
= widths
.value(visibleRole
, 0);
2291 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2292 maxWidth
= qMax(width
, maxWidth
);
2293 widths
.insert(visibleRole
, maxWidth
);
2296 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2297 // When having several thousands of items calculating the sizes can get
2298 // very expensive. We accept a possibly too small role-size in favour
2299 // of having no blocking user interface.
2300 maxTimeExceeded
= true;
2303 ++calculatedItemCount
;
2305 if (maxTimeExceeded
) {
2313 void KItemListView::applyColumnWidthsFromHeader()
2315 // Apply the new size to the layouter
2316 const qreal requiredWidth
= columnWidthsSum() + m_headerWidget
->leadingPadding();
2317 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2318 m_itemSize
.height());
2319 m_layouter
->setItemSize(dynamicItemSize
);
2321 // Update the role sizes for all visible widgets
2322 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2323 while (it
.hasNext()) {
2325 updateWidgetColumnWidths(it
.value());
2329 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2331 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2332 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2334 widget
->setLeadingPadding(m_headerWidget
->leadingPadding());
2337 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2339 Q_ASSERT(m_itemSize
.isEmpty());
2340 const int itemCount
= m_model
->count();
2341 int rangesItemCount
= 0;
2342 for (const KItemRange
& range
: itemRanges
) {
2343 rangesItemCount
+= range
.count
;
2346 if (itemCount
== rangesItemCount
) {
2347 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2348 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2349 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2352 // Only a sub range of the roles need to be determined.
2353 // The chances are good that the widths of the sub ranges
2354 // already fit into the available widths and hence no
2355 // expensive update might be required.
2356 bool changed
= false;
2358 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2359 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2360 while (it
.hasNext()) {
2362 const QByteArray
& role
= it
.key();
2363 const qreal updatedWidth
= it
.value();
2364 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2365 if (updatedWidth
> currentWidth
) {
2366 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2372 // All the updated sizes are smaller than the current sizes and no change
2373 // of the stretched roles-widths is required
2378 if (m_headerWidget
->automaticColumnResizing()) {
2379 applyAutomaticColumnWidths();
2383 void KItemListView::updatePreferredColumnWidths()
2386 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2390 void KItemListView::applyAutomaticColumnWidths()
2392 Q_ASSERT(m_itemSize
.isEmpty());
2393 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2394 if (m_visibleRoles
.isEmpty()) {
2398 // Calculate the maximum size of an item by considering the
2399 // visible role sizes and apply them to the layouter. If the
2400 // size does not use the available view-size the size of the
2401 // first role will get stretched.
2403 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2404 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2405 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2408 const QByteArray firstRole
= m_visibleRoles
.first();
2409 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2410 QSizeF dynamicItemSize
= m_itemSize
;
2412 qreal requiredWidth
= columnWidthsSum() + m_headerWidget
->leadingPadding()
2413 + m_headerWidget
->leadingPadding(); // Adding the padding a second time so we have the same padding symmetrically on both sides of the view.
2414 // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files.
2415 const qreal availableWidth
= size().width();
2416 if (requiredWidth
< availableWidth
) {
2417 // Stretch the first column to use the whole remaining width
2418 firstColumnWidth
+= availableWidth
- requiredWidth
;
2419 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2420 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2421 // Shrink the first column to be able to show as much other
2422 // columns as possible
2423 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2425 // TODO: A proper calculation of the minimum width depends on the implementation
2426 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2428 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2429 if (shrinkedFirstColumnWidth
< minWidth
) {
2430 shrinkedFirstColumnWidth
= minWidth
;
2433 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2434 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2437 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2439 m_layouter
->setItemSize(dynamicItemSize
);
2441 // Update the role sizes for all visible widgets
2442 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2443 while (it
.hasNext()) {
2445 updateWidgetColumnWidths(it
.value());
2449 qreal
KItemListView::columnWidthsSum() const
2451 qreal widthsSum
= 0;
2452 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2453 widthsSum
+= m_headerWidget
->columnWidth(role
);
2458 QRectF
KItemListView::headerBoundaries() const
2460 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2463 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2464 const QSizeF
& newItemSize
,
2465 const QSizeF
& newItemMargin
) const
2467 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2471 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2472 const qreal itemWidth
= m_layouter
->itemSize().width();
2473 if (itemWidth
> 0) {
2474 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2475 newItemSize
.width(),
2476 newItemMargin
.width());
2477 if (m_model
->count() > newColumnCount
) {
2478 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2480 m_layouter
->itemMargin().width());
2481 return oldColumnCount
!= newColumnCount
;
2485 const qreal itemHeight
= m_layouter
->itemSize().height();
2486 if (itemHeight
> 0) {
2487 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2488 newItemSize
.height(),
2489 newItemMargin
.height());
2490 if (m_model
->count() > newRowCount
) {
2491 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2493 m_layouter
->itemMargin().height());
2494 return oldRowCount
!= newRowCount
;
2502 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2504 if (m_itemSize
.isEmpty()) {
2505 // We have only columns or only rows, but no grid: An animation is usually
2506 // welcome when inserting or removing items.
2507 return !supportsItemExpanding();
2510 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2514 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2515 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2516 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2517 // Only animate if up to 2/3 of a row or column are inserted or removed
2518 return changedItemCount
<= maximum
* 2 / 3;
2522 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2524 const QSizeF oldSize
= m_layouter
->size();
2526 m_layouter
->setSize(size
);
2527 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2528 m_layouter
->setSize(oldSize
);
2530 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2531 : maxOffset
> size
.width();
2534 int KItemListView::showDropIndicator(const QPointF
& pos
)
2536 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2537 while (it
.hasNext()) {
2539 const KItemListWidget
* widget
= it
.value();
2541 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2542 const QRectF rect
= itemRect(widget
->index());
2543 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2544 if (m_model
->supportsDropping(widget
->index())) {
2545 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2546 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2547 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2552 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2553 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2555 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2556 if (m_dropIndicator
!= draggingInsertIndicator
) {
2557 m_dropIndicator
= draggingInsertIndicator
;
2561 int index
= widget
->index();
2569 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2570 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2573 void KItemListView::hideDropIndicator()
2575 if (!m_dropIndicator
.isNull()) {
2576 m_dropIndicator
= QRectF();
2581 void KItemListView::updateGroupHeaderHeight()
2583 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2584 qreal groupHeaderMargin
= 0;
2586 if (scrollOrientation() == Qt::Horizontal
) {
2587 // The vertical margin above and below the header should be
2588 // equal to the horizontal margin, not the vertical margin
2589 // from m_styleOption.
2590 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2591 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2592 } else if (m_itemSize
.isEmpty()){
2593 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2594 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2596 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2597 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2599 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2600 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2602 updateVisibleGroupHeaders();
2605 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2607 if (!supportsItemExpanding() || !m_model
) {
2611 if (firstIndex
< 0 || lastIndex
< 0) {
2612 firstIndex
= m_layouter
->firstVisibleIndex();
2613 lastIndex
= m_layouter
->lastVisibleIndex();
2615 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2616 lastIndex
>= m_layouter
->firstVisibleIndex());
2617 if (!isRangeVisible
) {
2622 int previousParents
= 0;
2623 QBitArray previousSiblings
;
2625 // The rootIndex describes the first index where the siblings get
2626 // calculated from. For the calculation the upper most parent item
2627 // is required. For performance reasons it is checked first whether
2628 // the visible items before or after the current range already
2629 // contain a siblings information which can be used as base.
2630 int rootIndex
= firstIndex
;
2632 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2634 // There is no visible widget before the range, check whether there
2635 // is one after the range:
2636 widget
= m_visibleItems
.value(lastIndex
+ 1);
2638 // The sibling information of the widget may only be used if
2639 // all items of the range have the same number of parents.
2640 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2641 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2642 if (m_model
->expandedParentsCount(i
) != parents
) {
2651 // Performance optimization: Use the sibling information of the visible
2652 // widget beside the given range.
2653 previousSiblings
= widget
->siblingsInformation();
2654 if (previousSiblings
.isEmpty()) {
2657 previousParents
= previousSiblings
.count() - 1;
2658 previousSiblings
.truncate(previousParents
);
2660 // Potentially slow path: Go back to the upper most parent of firstIndex
2661 // to be able to calculate the initial value for the siblings.
2662 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2667 Q_ASSERT(previousParents
>= 0);
2668 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2669 // Update the parent-siblings in case if the current item represents
2670 // a child or an upper parent.
2671 const int currentParents
= m_model
->expandedParentsCount(i
);
2672 Q_ASSERT(currentParents
>= 0);
2673 if (previousParents
< currentParents
) {
2674 previousParents
= currentParents
;
2675 previousSiblings
.resize(currentParents
);
2676 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2677 } else if (previousParents
> currentParents
) {
2678 previousParents
= currentParents
;
2679 previousSiblings
.truncate(currentParents
);
2682 if (i
>= firstIndex
) {
2683 // The index represents a visible item. Apply the parent-siblings
2684 // and update the sibling of the current item.
2685 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2690 QBitArray siblings
= previousSiblings
;
2691 siblings
.resize(siblings
.count() + 1);
2692 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2694 widget
->setSiblingsInformation(siblings
);
2699 bool KItemListView::hasSiblingSuccessor(int index
) const
2701 bool hasSuccessor
= false;
2702 const int parentsCount
= m_model
->expandedParentsCount(index
);
2703 int successorIndex
= index
+ 1;
2705 // Search the next sibling
2706 const int itemCount
= m_model
->count();
2707 while (successorIndex
< itemCount
) {
2708 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2709 if (currentParentsCount
== parentsCount
) {
2710 hasSuccessor
= true;
2712 } else if (currentParentsCount
< parentsCount
) {
2718 if (m_grouped
&& hasSuccessor
) {
2719 // If the sibling is part of another group, don't mark it as
2720 // successor as the group header is between the sibling connections.
2721 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2722 if (m_layouter
->isFirstGroupItem(i
)) {
2723 hasSuccessor
= false;
2729 return hasSuccessor
;
2732 void KItemListView::disconnectRoleEditingSignals(int index
)
2734 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2739 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2740 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2741 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2744 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2748 const int minSpeed
= 4;
2749 const int maxSpeed
= 128;
2750 const int speedLimiter
= 96;
2751 const int autoScrollBorder
= 64;
2753 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2754 // This assures that the autoscrolling speed grows gradually.
2755 const int incLimiter
= 1;
2757 if (pos
< autoScrollBorder
) {
2758 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2759 inc
= qMax(inc
, -maxSpeed
);
2760 inc
= qMax(inc
, oldInc
- incLimiter
);
2761 } else if (pos
> range
- autoScrollBorder
) {
2762 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2763 inc
= qMin(inc
, maxSpeed
);
2764 inc
= qMin(inc
, oldInc
+ incLimiter
);
2770 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2772 const qreal availableSize
= size
- itemMargin
;
2773 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2779 KItemListCreatorBase::~KItemListCreatorBase()
2781 qDeleteAll(m_recycleableWidgets
);
2782 qDeleteAll(m_createdWidgets
);
2785 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2787 m_createdWidgets
.insert(widget
);
2790 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2792 Q_ASSERT(m_createdWidgets
.contains(widget
));
2793 m_createdWidgets
.remove(widget
);
2795 if (m_recycleableWidgets
.count() < 100) {
2796 m_recycleableWidgets
.append(widget
);
2797 widget
->setVisible(false);
2803 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2805 if (m_recycleableWidgets
.isEmpty()) {
2809 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2810 m_createdWidgets
.insert(widget
);
2814 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2818 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2820 widget
->setParentItem(nullptr);
2821 widget
->setOpacity(1.0);
2822 pushRecycleableWidget(widget
);
2825 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2829 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2831 header
->setOpacity(1.0);
2832 pushRecycleableWidget(header
);