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>
33 // Time in ms until reaching the autoscroll margin triggers
34 // an initial autoscrolling
35 const int InitialAutoScrollDelay
= 700;
37 // Delay in ms for triggering the next autoscroll
38 const int RepeatingAutoScrollDelay
= 1000 / 60;
41 #ifndef QT_NO_ACCESSIBILITY
42 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
46 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
47 return new KItemListContainerAccessible(container
);
48 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
49 return new KItemListViewAccessible(view
);
56 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
57 QGraphicsWidget(parent
),
58 m_enabledSelectionToggles(false),
60 m_supportsItemExpanding(false),
62 m_activeTransactions(0),
63 m_endTransactionAnimationHint(Animation
),
65 m_controller(nullptr),
68 m_widgetCreator(nullptr),
69 m_groupHeaderCreator(nullptr),
74 m_sizeHintResolver(nullptr),
77 m_layoutTimer(nullptr),
79 m_oldMaximumScrollOffset(0),
81 m_oldMaximumItemOffset(0),
82 m_skipAutoScrollForRubberBand(false),
83 m_rubberBand(nullptr),
84 m_tapAndHoldIndicator(nullptr),
86 m_autoScrollIncrement(0),
87 m_autoScrollTimer(nullptr),
89 m_headerWidget(nullptr),
90 m_indicatorAnimation(nullptr),
93 setAcceptHoverEvents(true);
94 setAcceptTouchEvents(true);
96 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
98 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
100 m_animation
= new KItemListViewAnimation(this);
101 connect(m_animation
, &KItemListViewAnimation::finished
,
102 this, &KItemListView::slotAnimationFinished
);
104 m_layoutTimer
= new QTimer(this);
105 m_layoutTimer
->setInterval(300);
106 m_layoutTimer
->setSingleShot(true);
107 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
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
);
370 // Triggering a synchronous layout is fine from a performance point of view,
371 // as with dynamic item sizes no moving animation must be done.
372 m_layouter
->setSize(newSize
);
373 doLayout(NoAnimation
);
375 const bool animate
= !changesItemGridLayout(newSize
,
376 m_layouter
->itemSize(),
377 m_layouter
->itemMargin());
378 m_layouter
->setSize(newSize
);
381 // Trigger an asynchronous relayout with m_layoutTimer to prevent
382 // performance bottlenecks. If the timer is exceeded, an animated layout
383 // will be triggered.
384 if (!m_layoutTimer
->isActive()) {
385 m_layoutTimer
->start();
388 m_layoutTimer
->stop();
389 doLayout(NoAnimation
);
394 qreal
KItemListView::verticalPageStep() const
396 qreal headerHeight
= 0;
397 if (m_headerWidget
->isVisible()) {
398 headerHeight
= m_headerWidget
->size().height();
400 return size().height() - headerHeight
;
403 int KItemListView::itemAt(const QPointF
& pos
) const
405 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
406 while (it
.hasNext()) {
409 const KItemListWidget
* widget
= it
.value();
410 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
411 if (widget
->contains(mappedPos
)) {
419 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
421 if (!m_enabledSelectionToggles
) {
425 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
427 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
428 if (!selectionToggleRect
.isEmpty()) {
429 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
430 return selectionToggleRect
.contains(mappedPos
);
436 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
438 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
440 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
441 if (!expansionToggleRect
.isEmpty()) {
442 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
443 return expansionToggleRect
.contains(mappedPos
);
449 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
451 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
453 const QRectF
&textRect
= widget
->textRect();
454 if (!textRect
.isEmpty()) {
455 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
456 return textRect
.contains(mappedPos
);
462 int KItemListView::firstVisibleIndex() const
464 return m_layouter
->firstVisibleIndex();
467 int KItemListView::lastVisibleIndex() const
469 return m_layouter
->lastVisibleIndex();
472 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
474 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
477 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
479 if (m_supportsItemExpanding
!= supportsExpanding
) {
480 m_supportsItemExpanding
= supportsExpanding
;
481 updateSiblingsInformation();
482 onSupportsItemExpandingChanged(supportsExpanding
);
486 bool KItemListView::supportsItemExpanding() const
488 return m_supportsItemExpanding
;
491 QRectF
KItemListView::itemRect(int index
) const
493 return m_layouter
->itemRect(index
);
496 QRectF
KItemListView::itemContextRect(int index
) const
500 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
502 contextRect
= widget
->iconRect() | widget
->textRect();
503 contextRect
.translate(itemRect(index
).topLeft());
509 void KItemListView::scrollToItem(int index
)
511 QRectF viewGeometry
= geometry();
512 if (m_headerWidget
->isVisible()) {
513 const qreal headerHeight
= m_headerWidget
->size().height();
514 viewGeometry
.adjust(0, headerHeight
, 0, 0);
516 QRectF currentRect
= itemRect(index
);
518 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
519 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
520 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
522 if (!viewGeometry
.contains(currentRect
)) {
523 qreal newOffset
= scrollOffset();
524 if (scrollOrientation() == Qt::Vertical
) {
525 if (currentRect
.top() < viewGeometry
.top()) {
526 newOffset
+= currentRect
.top() - viewGeometry
.top();
527 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
528 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
531 if (currentRect
.left() < viewGeometry
.left()) {
532 newOffset
+= currentRect
.left() - viewGeometry
.left();
533 } else if (currentRect
.right() > viewGeometry
.right()) {
534 newOffset
+= currentRect
.right() - viewGeometry
.right();
538 if (newOffset
!= scrollOffset()) {
539 Q_EMIT
scrollTo(newOffset
);
544 void KItemListView::beginTransaction()
546 ++m_activeTransactions
;
547 if (m_activeTransactions
== 1) {
548 onTransactionBegin();
552 void KItemListView::endTransaction()
554 --m_activeTransactions
;
555 if (m_activeTransactions
< 0) {
556 m_activeTransactions
= 0;
557 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
560 if (m_activeTransactions
== 0) {
562 doLayout(m_endTransactionAnimationHint
);
563 m_endTransactionAnimationHint
= Animation
;
567 bool KItemListView::isTransactionActive() const
569 return m_activeTransactions
> 0;
572 void KItemListView::setHeaderVisible(bool visible
)
574 if (visible
&& !m_headerWidget
->isVisible()) {
575 QStyleOptionHeader option
;
576 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
579 m_headerWidget
->setPos(0, 0);
580 m_headerWidget
->resize(size().width(), headerSize
.height());
581 m_headerWidget
->setModel(m_model
);
582 m_headerWidget
->setColumns(m_visibleRoles
);
583 m_headerWidget
->setZValue(1);
585 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
586 this, &KItemListView::slotHeaderColumnWidthChanged
);
587 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
588 this, &KItemListView::slotHeaderColumnMoved
);
589 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
590 this, &KItemListView::sortOrderChanged
);
591 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
592 this, &KItemListView::sortRoleChanged
);
594 m_layouter
->setHeaderHeight(headerSize
.height());
595 m_headerWidget
->setVisible(true);
596 } else if (!visible
&& m_headerWidget
->isVisible()) {
597 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
598 this, &KItemListView::slotHeaderColumnWidthChanged
);
599 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
600 this, &KItemListView::slotHeaderColumnMoved
);
601 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
602 this, &KItemListView::sortOrderChanged
);
603 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
604 this, &KItemListView::sortRoleChanged
);
606 m_layouter
->setHeaderHeight(0);
607 m_headerWidget
->setVisible(false);
611 bool KItemListView::isHeaderVisible() const
613 return m_headerWidget
->isVisible();
616 KItemListHeader
* KItemListView::header() const
621 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
625 if (indexes
.count() == 1) {
626 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
627 QGraphicsView
* graphicsView
= scene()->views()[0];
628 if (item
&& graphicsView
) {
629 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
632 // TODO: Not implemented yet. Probably extend the interface
633 // from KItemListWidget::createDragPixmap() to return a pixmap
634 // that can be used for multiple indexes.
640 void KItemListView::editRole(int index
, const QByteArray
& role
)
642 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
643 if (!widget
|| m_editingRole
) {
647 m_editingRole
= true;
648 widget
->setEditedRole(role
);
650 connect(widget
, &KItemListWidget::roleEditingCanceled
,
651 this, &KItemListView::slotRoleEditingCanceled
);
652 connect(widget
, &KItemListWidget::roleEditingFinished
,
653 this, &KItemListView::slotRoleEditingFinished
);
655 connect(this, &KItemListView::scrollOffsetChanged
,
656 widget
, &KStandardItemListWidget::finishRoleEditing
);
659 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
661 QGraphicsWidget::paint(painter
, option
, widget
);
663 if (m_rubberBand
->isActive()) {
664 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
665 m_rubberBand
->endPosition()).normalized();
667 const QPointF topLeft
= rubberBandRect
.topLeft();
668 if (scrollOrientation() == Qt::Vertical
) {
669 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
671 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
674 QStyleOptionRubberBand opt
;
675 initStyleOption(&opt
);
676 opt
.shape
= QRubberBand::Rectangle
;
678 opt
.rect
= rubberBandRect
.toRect();
679 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
682 if (m_tapAndHoldIndicator
->isActive()) {
683 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
684 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
685 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
686 QStyleOptionRubberBand opt
;
687 initStyleOption(&opt
);
688 opt
.shape
= QRubberBand::Rectangle
;
690 opt
.rect
= rubberBandRect
.toRect();
691 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
694 if (!m_dropIndicator
.isEmpty()) {
695 const QRectF r
= m_dropIndicator
.toRect();
697 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
698 painter
->setPen(color
);
700 // TODO: The following implementation works only for a vertical scroll-orientation
701 // and assumes a height of the m_draggingInsertIndicator of 1.
702 Q_ASSERT(r
.height() == 1);
703 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
706 painter
->setPen(color
);
707 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
711 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
713 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
714 if (!scene()->views().isEmpty()) {
715 m_styleOption
.palette
= scene()->views().at(0)->palette();
718 return QGraphicsItem::itemChange(change
, value
);
721 void KItemListView::setItemSize(const QSizeF
& size
)
723 const QSizeF previousSize
= m_itemSize
;
724 if (size
== previousSize
) {
728 // Skip animations when the number of rows or columns
729 // are changed in the grid layout. Although the animation
730 // engine can handle this usecase, it looks obtrusive.
731 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
733 m_layouter
->itemMargin());
735 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
736 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
737 (!m_itemSize
.isEmpty() && size
.isEmpty()));
741 if (alternateBackgroundsChanged
) {
742 // For an empty item size alternate backgrounds are drawn if more than
743 // one role is shown. Assure that the backgrounds for visible items are
744 // updated when changing the size in this context.
745 updateAlternateBackgrounds();
748 if (size
.isEmpty()) {
749 if (m_headerWidget
->automaticColumnResizing()) {
750 updatePreferredColumnWidths();
752 // Only apply the changed height and respect the header widths
754 const qreal currentWidth
= m_layouter
->itemSize().width();
755 const QSizeF
newSize(currentWidth
, size
.height());
756 m_layouter
->setItemSize(newSize
);
759 m_layouter
->setItemSize(size
);
762 m_sizeHintResolver
->clearCache();
763 doLayout(animate
? Animation
: NoAnimation
);
764 onItemSizeChanged(size
, previousSize
);
767 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
769 if (m_styleOption
== option
) {
773 const KItemListStyleOption previousOption
= m_styleOption
;
774 m_styleOption
= option
;
777 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
778 if (margin
!= m_layouter
->itemMargin()) {
779 // Skip animations when the number of rows or columns
780 // are changed in the grid layout. Although the animation
781 // engine can handle this usecase, it looks obtrusive.
782 animate
= !changesItemGridLayout(m_layouter
->size(),
783 m_layouter
->itemSize(),
785 m_layouter
->setItemMargin(margin
);
789 updateGroupHeaderHeight();
793 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
794 // Animating a change of the maximum text size just results in expensive
795 // temporary eliding and clipping operations and does not look good visually.
799 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
800 while (it
.hasNext()) {
802 it
.value()->setStyleOption(option
);
805 m_sizeHintResolver
->clearCache();
806 m_layouter
->markAsDirty();
807 doLayout(animate
? Animation
: NoAnimation
);
809 if (m_itemSize
.isEmpty()) {
810 updatePreferredColumnWidths();
813 onStyleOptionChanged(option
, previousOption
);
816 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
818 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
819 if (orientation
== previousOrientation
) {
823 m_layouter
->setScrollOrientation(orientation
);
824 m_animation
->setScrollOrientation(orientation
);
825 m_sizeHintResolver
->clearCache();
828 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
829 while (it
.hasNext()) {
831 it
.value()->setScrollOrientation(orientation
);
833 updateGroupHeaderHeight();
837 doLayout(NoAnimation
);
839 onScrollOrientationChanged(orientation
, previousOrientation
);
840 Q_EMIT
scrollOrientationChanged(orientation
, previousOrientation
);
843 Qt::Orientation
KItemListView::scrollOrientation() const
845 return m_layouter
->scrollOrientation();
848 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
853 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
858 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
863 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
865 Q_UNUSED(changedRoles
)
869 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
875 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
881 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
887 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
893 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
899 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
905 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
911 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
913 Q_UNUSED(supportsExpanding
)
916 void KItemListView::onTransactionBegin()
920 void KItemListView::onTransactionEnd()
924 bool KItemListView::event(QEvent
* event
)
926 switch (event
->type()) {
927 case QEvent::PaletteChange
:
931 case QEvent::FontChange
:
936 // Forward all other events to the controller and handle them there
937 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
943 return QGraphicsWidget::event(event
);
946 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
948 m_mousePos
= transform().map(event
->pos());
952 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
954 QGraphicsWidget::mouseMoveEvent(event
);
956 m_mousePos
= transform().map(event
->pos());
957 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
958 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
962 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
964 event
->setAccepted(true);
968 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
970 QGraphicsWidget::dragMoveEvent(event
);
972 m_mousePos
= transform().map(event
->pos());
973 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
974 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
978 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
980 QGraphicsWidget::dragLeaveEvent(event
);
981 setAutoScroll(false);
984 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
986 QGraphicsWidget::dropEvent(event
);
987 setAutoScroll(false);
990 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
992 return m_visibleItems
.values();
995 void KItemListView::updateFont()
997 if (scene() && !scene()->views().isEmpty()) {
998 KItemListStyleOption option
= styleOption();
999 option
.font
= scene()->views().first()->font();
1000 option
.fontMetrics
= QFontMetrics(option
.font
);
1002 setStyleOption(option
);
1006 void KItemListView::updatePalette()
1008 if (scene() && !scene()->views().isEmpty()) {
1009 KItemListStyleOption option
= styleOption();
1010 option
.palette
= scene()->views().first()->palette();
1012 setStyleOption(option
);
1016 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1018 if (m_itemSize
.isEmpty()) {
1019 updatePreferredColumnWidths(itemRanges
);
1022 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1023 if (hasMultipleRanges
) {
1027 m_layouter
->markAsDirty();
1029 m_sizeHintResolver
->itemsInserted(itemRanges
);
1031 int previouslyInsertedCount
= 0;
1032 for (const KItemRange
& range
: itemRanges
) {
1033 // range.index is related to the model before anything has been inserted.
1034 // As in each loop the current item-range gets inserted the index must
1035 // be increased by the already previously inserted items.
1036 const int index
= range
.index
+ previouslyInsertedCount
;
1037 const int count
= range
.count
;
1038 if (index
< 0 || count
<= 0) {
1039 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1042 previouslyInsertedCount
+= count
;
1044 // Determine which visible items must be moved
1045 QList
<int> itemsToMove
;
1046 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1047 while (it
.hasNext()) {
1049 const int visibleItemIndex
= it
.key();
1050 if (visibleItemIndex
>= index
) {
1051 itemsToMove
.append(visibleItemIndex
);
1055 // Update the indexes of all KItemListWidget instances that are located
1056 // after the inserted items. It is important to adjust the indexes in the order
1057 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1058 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1059 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1060 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1062 const int newIndex
= widget
->index() + count
;
1063 if (hasMultipleRanges
) {
1064 setWidgetIndex(widget
, newIndex
);
1066 // Try to animate the moving of the item
1067 moveWidgetToIndex(widget
, newIndex
);
1071 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1072 // Check whether a scrollbar is required to show the inserted items. In this case
1073 // the size of the layouter will be decreased before calling doLayout(): This prevents
1074 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1075 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1076 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1077 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1078 if (decreaseLayouterSize
) {
1079 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1081 int scrollbarSpacing
= 0;
1082 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1083 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1086 QSizeF layouterSize
= m_layouter
->size();
1087 if (verticalScrollOrientation
) {
1088 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1090 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1092 m_layouter
->setSize(layouterSize
);
1096 if (!hasMultipleRanges
) {
1097 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1098 updateSiblingsInformation();
1103 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1106 if (hasMultipleRanges
) {
1107 m_endTransactionAnimationHint
= NoAnimation
;
1110 updateSiblingsInformation();
1113 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1114 // In case if items of the same group have been inserted before an item that
1115 // currently represents the first item of the group, the group header of
1116 // this item must be removed.
1117 updateVisibleGroupHeaders();
1120 if (useAlternateBackgrounds()) {
1121 updateAlternateBackgrounds();
1125 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1127 if (m_itemSize
.isEmpty()) {
1128 // Don't pass the item-range: The preferred column-widths of
1129 // all items must be adjusted when removing items.
1130 updatePreferredColumnWidths();
1133 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1134 if (hasMultipleRanges
) {
1138 m_layouter
->markAsDirty();
1140 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1142 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1143 const KItemRange
& range
= itemRanges
[i
];
1144 const int index
= range
.index
;
1145 const int count
= range
.count
;
1146 if (index
< 0 || count
<= 0) {
1147 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1151 const int firstRemovedIndex
= index
;
1152 const int lastRemovedIndex
= index
+ count
- 1;
1154 // Remember which items have to be moved because they are behind the removed range.
1155 QVector
<int> itemsToMove
;
1157 // Remove all KItemListWidget instances that got deleted
1158 QMutableHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1159 while (it
.hasNext()) {
1161 KItemListWidget
* widget
= it
.value();
1162 const int i
= widget
->index();
1163 if (i
< firstRemovedIndex
) {
1165 } else if (i
> lastRemovedIndex
) {
1166 itemsToMove
.append(i
);
1170 m_animation
->stop(widget
);
1171 // Stopping the animation might lead to recycling the widget if
1172 // it is invisible (see slotAnimationFinished()).
1173 // Check again whether it is still visible:
1174 if (!m_visibleItems
.contains(i
)) {
1178 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1179 // Remove the widget without animation
1180 recycleWidget(widget
);
1182 // Animate the removing of the items. Special case: When removing an item there
1183 // is no valid model index available anymore. For the
1184 // remove-animation the item gets removed from m_visibleItems but the widget
1185 // will stay alive until the animation has been finished and will
1186 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1187 m_visibleItems
.remove(i
);
1188 widget
->setIndex(-1);
1189 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1193 // Update the indexes of all KItemListWidget instances that are located
1194 // after the deleted items. It is important to update them in ascending
1195 // order to prevent overlaps when setting the new index.
1196 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1197 for (int i
: qAsConst(itemsToMove
)) {
1198 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1200 const int newIndex
= i
- count
;
1201 if (hasMultipleRanges
) {
1202 setWidgetIndex(widget
, newIndex
);
1204 // Try to animate the moving of the item
1205 moveWidgetToIndex(widget
, newIndex
);
1209 if (!hasMultipleRanges
) {
1210 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1211 // assumes an updated geometry. If items are removed during an active transaction,
1212 // the transaction will be temporary deactivated so that doLayout() triggers a
1213 // geometry update if necessary.
1214 const int activeTransactions
= m_activeTransactions
;
1215 m_activeTransactions
= 0;
1216 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1217 m_activeTransactions
= activeTransactions
;
1218 updateSiblingsInformation();
1223 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1226 if (hasMultipleRanges
) {
1227 m_endTransactionAnimationHint
= NoAnimation
;
1229 updateSiblingsInformation();
1232 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1233 // In case if the first item of a group has been removed, the group header
1234 // must be applied to the next visible item.
1235 updateVisibleGroupHeaders();
1238 if (useAlternateBackgrounds()) {
1239 updateAlternateBackgrounds();
1243 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1245 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1246 m_layouter
->markAsDirty();
1249 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1252 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1253 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1255 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1256 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1258 updateWidgetProperties(widget
, index
);
1259 initializeItemListWidget(widget
);
1263 doLayout(NoAnimation
);
1264 updateSiblingsInformation();
1267 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1268 const QSet
<QByteArray
>& roles
)
1270 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1271 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1272 updatePreferredColumnWidths(itemRanges
);
1275 for (const KItemRange
& itemRange
: itemRanges
) {
1276 const int index
= itemRange
.index
;
1277 const int count
= itemRange
.count
;
1279 if (updateSizeHints
) {
1280 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1281 m_layouter
->markAsDirty();
1283 if (!m_layoutTimer
->isActive()) {
1284 m_layoutTimer
->start();
1288 // Apply the changed roles to the visible item-widgets
1289 const int lastIndex
= index
+ count
- 1;
1290 for (int i
= index
; i
<= lastIndex
; ++i
) {
1291 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1293 widget
->setData(m_model
->data(i
), roles
);
1297 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1298 // The sort-role has been changed which might result
1299 // in modified group headers
1300 updateVisibleGroupHeaders();
1301 doLayout(NoAnimation
);
1304 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1305 ev
.setFirstRow(itemRange
.index
);
1306 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1307 QAccessible::updateAccessibility(&ev
);
1311 void KItemListView::slotGroupsChanged()
1313 updateVisibleGroupHeaders();
1314 doLayout(NoAnimation
);
1315 updateSiblingsInformation();
1318 void KItemListView::slotGroupedSortingChanged(bool current
)
1320 m_grouped
= current
;
1321 m_layouter
->markAsDirty();
1324 updateGroupHeaderHeight();
1326 // Clear all visible headers. Note that the QHashIterator takes a copy of
1327 // m_visibleGroups. Therefore, it remains valid even if items are removed
1328 // from m_visibleGroups in recycleGroupHeaderForWidget().
1329 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1330 while (it
.hasNext()) {
1332 recycleGroupHeaderForWidget(it
.key());
1334 Q_ASSERT(m_visibleGroups
.isEmpty());
1337 if (useAlternateBackgrounds()) {
1338 // Changing the group mode requires to update the alternate backgrounds
1339 // as with the enabled group mode the altering is done on base of the first
1341 updateAlternateBackgrounds();
1343 updateSiblingsInformation();
1344 doLayout(NoAnimation
);
1347 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1352 updateVisibleGroupHeaders();
1353 doLayout(NoAnimation
);
1357 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1362 updateVisibleGroupHeaders();
1363 doLayout(NoAnimation
);
1367 void KItemListView::slotCurrentChanged(int current
, int previous
)
1371 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1372 // always the selected item. It is not necessary to highlight the current item then.
1373 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1374 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1375 if (previousWidget
) {
1376 previousWidget
->setCurrent(false);
1379 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1380 if (currentWidget
) {
1381 currentWidget
->setCurrent(true);
1385 QAccessibleEvent
ev(this, QAccessible::Focus
);
1386 ev
.setChild(current
);
1387 QAccessible::updateAccessibility(&ev
);
1390 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1394 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1395 while (it
.hasNext()) {
1397 const int index
= it
.key();
1398 KItemListWidget
* widget
= it
.value();
1399 widget
->setSelected(current
.contains(index
));
1403 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1404 KItemListViewAnimation::AnimationType type
)
1406 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1407 Q_ASSERT(itemListWidget
);
1410 case KItemListViewAnimation::DeleteAnimation
: {
1411 // As we recycle the widget in this case it is important to assure that no
1412 // other animation has been started. This is a convention in KItemListView and
1413 // not a requirement defined by KItemListViewAnimation.
1414 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1416 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1417 // by m_visibleWidgets and must be deleted manually after the animation has
1419 recycleGroupHeaderForWidget(itemListWidget
);
1420 widgetCreator()->recycle(itemListWidget
);
1424 case KItemListViewAnimation::CreateAnimation
:
1425 case KItemListViewAnimation::MovingAnimation
:
1426 case KItemListViewAnimation::ResizeAnimation
: {
1427 const int index
= itemListWidget
->index();
1428 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1429 (index
> m_layouter
->lastVisibleIndex());
1430 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1431 recycleWidget(itemListWidget
);
1440 void KItemListView::slotLayoutTimerFinished()
1442 m_layouter
->setSize(geometry().size());
1443 doLayout(Animation
);
1446 void KItemListView::slotRubberBandPosChanged()
1451 void KItemListView::slotRubberBandActivationChanged(bool active
)
1454 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1455 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1456 m_skipAutoScrollForRubberBand
= true;
1458 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1459 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1460 m_skipAutoScrollForRubberBand
= false;
1466 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1468 qreal previousWidth
)
1471 Q_UNUSED(currentWidth
)
1472 Q_UNUSED(previousWidth
)
1474 m_headerWidget
->setAutomaticColumnResizing(false);
1475 applyColumnWidthsFromHeader();
1476 doLayout(NoAnimation
);
1479 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1483 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1485 const QList
<QByteArray
> previous
= m_visibleRoles
;
1487 QList
<QByteArray
> current
= m_visibleRoles
;
1488 current
.removeAt(previousIndex
);
1489 current
.insert(currentIndex
, role
);
1491 setVisibleRoles(current
);
1493 Q_EMIT
visibleRolesChanged(current
, previous
);
1496 void KItemListView::triggerAutoScrolling()
1498 if (!m_autoScrollTimer
) {
1503 int visibleSize
= 0;
1504 if (scrollOrientation() == Qt::Vertical
) {
1505 pos
= m_mousePos
.y();
1506 visibleSize
= size().height();
1508 pos
= m_mousePos
.x();
1509 visibleSize
= size().width();
1512 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1513 m_autoScrollIncrement
= 0;
1516 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1517 if (m_autoScrollIncrement
== 0) {
1518 // The mouse position is not above an autoscroll margin (the autoscroll timer
1519 // will be restarted in mouseMoveEvent())
1520 m_autoScrollTimer
->stop();
1524 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1525 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1526 // if the direction of the rubberband is similar to the autoscroll direction. This
1527 // prevents that starting to create a rubberband within the autoscroll margins starts
1528 // an autoscrolling.
1530 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1531 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1532 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1533 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1534 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1535 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1536 // been moved up although the autoscroll direction might be down)
1537 m_autoScrollTimer
->stop();
1542 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1543 // the autoscrolling may not get skipped anymore until a new rubberband is created
1544 m_skipAutoScrollForRubberBand
= false;
1546 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1547 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1548 setScrollOffset(newScrollOffset
);
1550 // Trigger the autoscroll timer which will periodically call
1551 // triggerAutoScrolling()
1552 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1555 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1557 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1559 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1560 Q_ASSERT(groupHeader
);
1561 updateGroupHeaderLayout(widget
);
1564 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1566 disconnectRoleEditingSignals(index
);
1568 Q_EMIT
roleEditingCanceled(index
, role
, value
);
1569 m_editingRole
= false;
1572 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1574 disconnectRoleEditingSignals(index
);
1576 Q_EMIT
roleEditingFinished(index
, role
, value
);
1577 m_editingRole
= false;
1580 void KItemListView::setController(KItemListController
* controller
)
1582 if (m_controller
!= controller
) {
1583 KItemListController
* previous
= m_controller
;
1585 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1586 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1587 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1590 m_controller
= controller
;
1593 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1594 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1595 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1598 onControllerChanged(controller
, previous
);
1602 void KItemListView::setModel(KItemModelBase
* model
)
1604 if (m_model
== model
) {
1608 KItemModelBase
* previous
= m_model
;
1611 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1612 this, &KItemListView::slotItemsChanged
);
1613 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1614 this, &KItemListView::slotItemsInserted
);
1615 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1616 this, &KItemListView::slotItemsRemoved
);
1617 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1618 this, &KItemListView::slotItemsMoved
);
1619 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1620 this, &KItemListView::slotGroupsChanged
);
1621 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1622 this, &KItemListView::slotGroupedSortingChanged
);
1623 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1624 this, &KItemListView::slotSortOrderChanged
);
1625 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1626 this, &KItemListView::slotSortRoleChanged
);
1628 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1632 m_layouter
->setModel(model
);
1633 m_grouped
= model
->groupedSorting();
1636 connect(m_model
, &KItemModelBase::itemsChanged
,
1637 this, &KItemListView::slotItemsChanged
);
1638 connect(m_model
, &KItemModelBase::itemsInserted
,
1639 this, &KItemListView::slotItemsInserted
);
1640 connect(m_model
, &KItemModelBase::itemsRemoved
,
1641 this, &KItemListView::slotItemsRemoved
);
1642 connect(m_model
, &KItemModelBase::itemsMoved
,
1643 this, &KItemListView::slotItemsMoved
);
1644 connect(m_model
, &KItemModelBase::groupsChanged
,
1645 this, &KItemListView::slotGroupsChanged
);
1646 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1647 this, &KItemListView::slotGroupedSortingChanged
);
1648 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1649 this, &KItemListView::slotSortOrderChanged
);
1650 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1651 this, &KItemListView::slotSortRoleChanged
);
1653 const int itemCount
= m_model
->count();
1654 if (itemCount
> 0) {
1655 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1659 onModelChanged(model
, previous
);
1662 KItemListRubberBand
* KItemListView::rubberBand() const
1664 return m_rubberBand
;
1667 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1669 if (m_layoutTimer
->isActive()) {
1670 m_layoutTimer
->stop();
1673 if (m_activeTransactions
> 0) {
1674 if (hint
== NoAnimation
) {
1675 // As soon as at least one property change should be done without animation,
1676 // the whole transaction will be marked as not animated.
1677 m_endTransactionAnimationHint
= NoAnimation
;
1682 if (!m_model
|| m_model
->count() < 0) {
1686 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1687 if (firstVisibleIndex
< 0) {
1688 emitOffsetChanges();
1692 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1693 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1694 // is still shown if the maximum offset got decreased.
1695 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1696 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1697 if (scrollOffset() > maxOffsetToShowFullRange
) {
1698 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1699 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1702 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1704 int firstSibblingIndex
= -1;
1705 int lastSibblingIndex
= -1;
1706 const bool supportsExpanding
= supportsItemExpanding();
1708 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1710 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1711 // instances from invisible items are reused. If no reusable items are
1712 // found then new KItemListWidget instances get created.
1713 const bool animate
= (hint
== Animation
);
1714 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1715 bool applyNewPos
= true;
1716 bool wasHidden
= false;
1718 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1719 const QPointF newPos
= itemBounds
.topLeft();
1720 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1723 if (!reusableItems
.isEmpty()) {
1724 // Reuse a KItemListWidget instance from an invisible item
1725 const int oldIndex
= reusableItems
.takeLast();
1726 widget
= m_visibleItems
.value(oldIndex
);
1727 setWidgetIndex(widget
, i
);
1728 updateWidgetProperties(widget
, i
);
1729 initializeItemListWidget(widget
);
1731 // No reusable KItemListWidget instance is available, create a new one
1732 widget
= createWidget(i
);
1734 widget
->resize(itemBounds
.size());
1736 if (animate
&& changedCount
< 0) {
1737 // Items have been deleted.
1738 if (i
>= changedIndex
) {
1739 // The item is located behind the removed range. Move the
1740 // created item to the imaginary old position outside the
1741 // view. It will get animated to the new position later.
1742 const int previousIndex
= i
- changedCount
;
1743 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1744 if (itemRect
.isEmpty()) {
1745 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1746 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1747 widget
->setPos(invisibleOldPos
);
1749 widget
->setPos(itemRect
.topLeft());
1751 applyNewPos
= false;
1755 if (supportsExpanding
&& changedCount
== 0) {
1756 if (firstSibblingIndex
< 0) {
1757 firstSibblingIndex
= i
;
1759 lastSibblingIndex
= i
;
1764 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1765 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1766 applyNewPos
= false;
1769 const bool itemsRemoved
= (changedCount
< 0);
1770 const bool itemsInserted
= (changedCount
> 0);
1771 if (itemsRemoved
&& (i
>= changedIndex
)) {
1772 // The item is located after the removed items. Animate the moving of the position.
1773 applyNewPos
= !moveWidget(widget
, newPos
);
1774 } else if (itemsInserted
&& i
>= changedIndex
) {
1775 // The item is located after the first inserted item
1776 if (i
<= changedIndex
+ changedCount
- 1) {
1777 // The item is an inserted item. Animate the appearing of the item.
1778 // For performance reasons no animation is done when changedCount is equal
1779 // to all available items.
1780 if (changedCount
< m_model
->count()) {
1781 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1783 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1784 // The item was already there before, so animate the moving of the position.
1785 // No moving animation is done if the item is animated by a create animation: This
1786 // prevents a "move animation mess" when inserting several ranges in parallel.
1787 applyNewPos
= !moveWidget(widget
, newPos
);
1789 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1790 // The size of the view might have been changed. Animate the moving of the position.
1791 applyNewPos
= !moveWidget(widget
, newPos
);
1794 m_animation
->stop(widget
);
1798 widget
->setPos(newPos
);
1801 Q_ASSERT(widget
->index() == i
);
1802 widget
->setVisible(true);
1804 if (widget
->size() != itemBounds
.size()) {
1805 // Resize the widget for the item to the changed size.
1807 // If a dynamic item size is used then no animation is done in the direction
1808 // of the dynamic size.
1809 if (m_itemSize
.width() <= 0) {
1810 // The width is dynamic, apply the new width without animation.
1811 widget
->resize(itemBounds
.width(), widget
->size().height());
1812 } else if (m_itemSize
.height() <= 0) {
1813 // The height is dynamic, apply the new height without animation.
1814 widget
->resize(widget
->size().width(), itemBounds
.height());
1816 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1818 widget
->resize(itemBounds
.size());
1822 // Updating the cell-information must be done as last step: The decision whether the
1823 // moving-animation should be started at all is based on the previous cell-information.
1824 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1825 m_visibleCells
.insert(i
, cell
);
1828 // Delete invisible KItemListWidget instances that have not been reused
1829 for (int index
: qAsConst(reusableItems
)) {
1830 recycleWidget(m_visibleItems
.value(index
));
1833 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1834 Q_ASSERT(lastSibblingIndex
>= 0);
1835 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1839 // Update the layout of all visible group headers
1840 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1841 while (it
.hasNext()) {
1843 updateGroupHeaderLayout(it
.key());
1847 emitOffsetChanges();
1850 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1851 int lastVisibleIndex
,
1852 LayoutAnimationHint hint
)
1854 // Determine all items that are completely invisible and might be
1855 // reused for items that just got (at least partly) visible. If the
1856 // animation hint is set to 'Animation' items that do e.g. an animated
1857 // moving of their position are not marked as invisible: This assures
1858 // that a scrolling inside the view can be done without breaking an animation.
1862 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1863 while (it
.hasNext()) {
1866 KItemListWidget
* widget
= it
.value();
1867 const int index
= widget
->index();
1868 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1871 if (m_animation
->isStarted(widget
)) {
1872 if (hint
== NoAnimation
) {
1873 // Stopping the animation will call KItemListView::slotAnimationFinished()
1874 // and the widget will be recycled if necessary there.
1875 m_animation
->stop(widget
);
1878 widget
->setVisible(false);
1879 items
.append(index
);
1882 recycleGroupHeaderForWidget(widget
);
1891 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1893 if (widget
->pos() == newPos
) {
1897 bool startMovingAnim
= false;
1899 if (m_itemSize
.isEmpty()) {
1900 // The items are not aligned in a grid but either as columns or rows.
1901 startMovingAnim
= true;
1903 // When having a grid the moving-animation should only be started, if it is done within
1904 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1905 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1906 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1907 const int index
= widget
->index();
1908 const Cell cell
= m_visibleCells
.value(index
);
1909 if (cell
.column
>= 0 && cell
.row
>= 0) {
1910 if (scrollOrientation() == Qt::Vertical
) {
1911 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1913 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1918 if (startMovingAnim
) {
1919 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1923 m_animation
->stop(widget
);
1924 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1928 void KItemListView::emitOffsetChanges()
1930 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1931 if (m_oldScrollOffset
!= newScrollOffset
) {
1932 Q_EMIT
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1933 m_oldScrollOffset
= newScrollOffset
;
1936 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1937 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1938 Q_EMIT
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1939 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1942 const qreal newItemOffset
= m_layouter
->itemOffset();
1943 if (m_oldItemOffset
!= newItemOffset
) {
1944 Q_EMIT
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1945 m_oldItemOffset
= newItemOffset
;
1948 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1949 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1950 Q_EMIT
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1951 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1955 KItemListWidget
* KItemListView::createWidget(int index
)
1957 KItemListWidget
* widget
= widgetCreator()->create(this);
1958 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1960 m_visibleItems
.insert(index
, widget
);
1961 m_visibleCells
.insert(index
, Cell());
1962 updateWidgetProperties(widget
, index
);
1963 initializeItemListWidget(widget
);
1967 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1970 recycleGroupHeaderForWidget(widget
);
1973 const int index
= widget
->index();
1974 m_visibleItems
.remove(index
);
1975 m_visibleCells
.remove(index
);
1977 widgetCreator()->recycle(widget
);
1980 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1982 const int oldIndex
= widget
->index();
1983 m_visibleItems
.remove(oldIndex
);
1984 m_visibleCells
.remove(oldIndex
);
1986 m_visibleItems
.insert(index
, widget
);
1987 m_visibleCells
.insert(index
, Cell());
1989 widget
->setIndex(index
);
1992 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1994 const int oldIndex
= widget
->index();
1995 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1997 setWidgetIndex(widget
, index
);
1999 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
2000 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
2001 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
2002 (!vertical
&& oldCell
.column
== newCell
.column
);
2004 m_visibleCells
.insert(index
, newCell
);
2008 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2011 case LayouterSize
: m_layouter
->setSize(size
); break;
2012 case ItemSize
: m_layouter
->setItemSize(size
); break;
2017 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2019 widget
->setVisibleRoles(m_visibleRoles
);
2020 updateWidgetColumnWidths(widget
);
2021 widget
->setStyleOption(m_styleOption
);
2023 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2025 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2026 // always the selected item. It is not necessary to highlight the current item then.
2027 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2028 widget
->setCurrent(index
== selectionManager
->currentItem());
2030 widget
->setSelected(selectionManager
->isSelected(index
));
2031 widget
->setHovered(false);
2032 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2033 widget
->setIndex(index
);
2034 widget
->setData(m_model
->data(index
));
2035 widget
->setSiblingsInformation(QBitArray());
2036 updateAlternateBackgroundForWidget(widget
);
2039 updateGroupHeaderForWidget(widget
);
2043 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2045 Q_ASSERT(m_grouped
);
2047 const int index
= widget
->index();
2048 if (!m_layouter
->isFirstGroupItem(index
)) {
2049 // The widget does not represent the first item of a group
2050 // and hence requires no header
2051 recycleGroupHeaderForWidget(widget
);
2055 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2056 if (groups
.isEmpty() || !groupHeaderCreator()) {
2060 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2062 groupHeader
= groupHeaderCreator()->create(this);
2063 groupHeader
->setParentItem(widget
);
2064 m_visibleGroups
.insert(widget
, groupHeader
);
2065 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2067 Q_ASSERT(groupHeader
->parentItem() == widget
);
2069 const int groupIndex
= groupIndexForItem(index
);
2070 Q_ASSERT(groupIndex
>= 0);
2071 groupHeader
->setData(groups
.at(groupIndex
).second
);
2072 groupHeader
->setRole(model()->sortRole());
2073 groupHeader
->setStyleOption(m_styleOption
);
2074 groupHeader
->setScrollOrientation(scrollOrientation());
2075 groupHeader
->setItemIndex(index
);
2077 groupHeader
->show();
2080 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2082 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2083 Q_ASSERT(groupHeader
);
2085 const int index
= widget
->index();
2086 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2087 const QRectF itemRect
= m_layouter
->itemRect(index
);
2089 // The group-header is a child of the itemlist widget. Translate the
2090 // group header position to the relative position.
2091 if (scrollOrientation() == Qt::Vertical
) {
2092 // In the vertical scroll orientation the group header should always span
2093 // the whole width no matter which temporary position the parent widget
2094 // has. In this case the x-position and width will be adjusted manually.
2095 const qreal x
= -widget
->x() - itemOffset();
2096 const qreal width
= maximumItemOffset();
2097 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2098 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2100 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2101 groupHeader
->resize(groupHeaderRect
.size());
2105 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2107 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2109 header
->setParentItem(nullptr);
2110 groupHeaderCreator()->recycle(header
);
2111 m_visibleGroups
.remove(widget
);
2112 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2116 void KItemListView::updateVisibleGroupHeaders()
2118 Q_ASSERT(m_grouped
);
2119 m_layouter
->markAsDirty();
2121 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2122 while (it
.hasNext()) {
2124 updateGroupHeaderForWidget(it
.value());
2128 int KItemListView::groupIndexForItem(int index
) const
2130 Q_ASSERT(m_grouped
);
2132 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2133 if (groups
.isEmpty()) {
2138 int max
= groups
.count() - 1;
2141 mid
= (min
+ max
) / 2;
2142 if (index
> groups
[mid
].first
) {
2147 } while (groups
[mid
].first
!= index
&& min
<= max
);
2150 while (groups
[mid
].first
> index
&& mid
> 0) {
2158 void KItemListView::updateAlternateBackgrounds()
2160 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2161 while (it
.hasNext()) {
2163 updateAlternateBackgroundForWidget(it
.value());
2167 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2169 bool enabled
= useAlternateBackgrounds();
2171 const int index
= widget
->index();
2172 enabled
= (index
& 0x1) > 0;
2174 const int groupIndex
= groupIndexForItem(index
);
2175 if (groupIndex
>= 0) {
2176 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2177 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2178 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2179 enabled
= (relativeIndex
& 0x1) > 0;
2183 widget
->setAlternateBackground(enabled
);
2186 bool KItemListView::useAlternateBackgrounds() const
2188 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2191 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2193 QElapsedTimer timer
;
2196 QHash
<QByteArray
, qreal
> widths
;
2198 // Calculate the minimum width for each column that is required
2199 // to show the headline unclipped.
2200 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2201 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2202 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2203 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2204 const QString headerText
= m_model
->roleDescription(visibleRole
);
2205 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2206 widths
.insert(visibleRole
, headerWidth
);
2209 // Calculate the preferred column withs for each item and ignore values
2210 // smaller than the width for showing the headline unclipped.
2211 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2212 int calculatedItemCount
= 0;
2213 bool maxTimeExceeded
= false;
2214 for (const KItemRange
& itemRange
: itemRanges
) {
2215 const int startIndex
= itemRange
.index
;
2216 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2218 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2219 for (const QByteArray
& visibleRole
: qAsConst(m_visibleRoles
)) {
2220 qreal maxWidth
= widths
.value(visibleRole
, 0);
2221 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2222 maxWidth
= qMax(width
, maxWidth
);
2223 widths
.insert(visibleRole
, maxWidth
);
2226 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2227 // When having several thousands of items calculating the sizes can get
2228 // very expensive. We accept a possibly too small role-size in favour
2229 // of having no blocking user interface.
2230 maxTimeExceeded
= true;
2233 ++calculatedItemCount
;
2235 if (maxTimeExceeded
) {
2243 void KItemListView::applyColumnWidthsFromHeader()
2245 // Apply the new size to the layouter
2246 const qreal requiredWidth
= columnWidthsSum();
2247 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2248 m_itemSize
.height());
2249 m_layouter
->setItemSize(dynamicItemSize
);
2251 // Update the role sizes for all visible widgets
2252 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2253 while (it
.hasNext()) {
2255 updateWidgetColumnWidths(it
.value());
2259 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2261 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2262 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2266 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2268 Q_ASSERT(m_itemSize
.isEmpty());
2269 const int itemCount
= m_model
->count();
2270 int rangesItemCount
= 0;
2271 for (const KItemRange
& range
: itemRanges
) {
2272 rangesItemCount
+= range
.count
;
2275 if (itemCount
== rangesItemCount
) {
2276 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2277 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2278 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2281 // Only a sub range of the roles need to be determined.
2282 // The chances are good that the widths of the sub ranges
2283 // already fit into the available widths and hence no
2284 // expensive update might be required.
2285 bool changed
= false;
2287 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2288 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2289 while (it
.hasNext()) {
2291 const QByteArray
& role
= it
.key();
2292 const qreal updatedWidth
= it
.value();
2293 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2294 if (updatedWidth
> currentWidth
) {
2295 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2301 // All the updated sizes are smaller than the current sizes and no change
2302 // of the stretched roles-widths is required
2307 if (m_headerWidget
->automaticColumnResizing()) {
2308 applyAutomaticColumnWidths();
2312 void KItemListView::updatePreferredColumnWidths()
2315 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2319 void KItemListView::applyAutomaticColumnWidths()
2321 Q_ASSERT(m_itemSize
.isEmpty());
2322 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2323 if (m_visibleRoles
.isEmpty()) {
2327 // Calculate the maximum size of an item by considering the
2328 // visible role sizes and apply them to the layouter. If the
2329 // size does not use the available view-size the size of the
2330 // first role will get stretched.
2332 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2333 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2334 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2337 const QByteArray firstRole
= m_visibleRoles
.first();
2338 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2339 QSizeF dynamicItemSize
= m_itemSize
;
2341 qreal requiredWidth
= columnWidthsSum();
2342 const qreal availableWidth
= size().width();
2343 if (requiredWidth
< availableWidth
) {
2344 // Stretch the first column to use the whole remaining width
2345 firstColumnWidth
+= availableWidth
- requiredWidth
;
2346 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2347 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2348 // Shrink the first column to be able to show as much other
2349 // columns as possible
2350 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2352 // TODO: A proper calculation of the minimum width depends on the implementation
2353 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2355 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2356 if (shrinkedFirstColumnWidth
< minWidth
) {
2357 shrinkedFirstColumnWidth
= minWidth
;
2360 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2361 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2364 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2366 m_layouter
->setItemSize(dynamicItemSize
);
2368 // Update the role sizes for all visible widgets
2369 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2370 while (it
.hasNext()) {
2372 updateWidgetColumnWidths(it
.value());
2376 qreal
KItemListView::columnWidthsSum() const
2378 qreal widthsSum
= 0;
2379 for (const QByteArray
& role
: qAsConst(m_visibleRoles
)) {
2380 widthsSum
+= m_headerWidget
->columnWidth(role
);
2385 QRectF
KItemListView::headerBoundaries() const
2387 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2390 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2391 const QSizeF
& newItemSize
,
2392 const QSizeF
& newItemMargin
) const
2394 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2398 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2399 const qreal itemWidth
= m_layouter
->itemSize().width();
2400 if (itemWidth
> 0) {
2401 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2402 newItemSize
.width(),
2403 newItemMargin
.width());
2404 if (m_model
->count() > newColumnCount
) {
2405 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2407 m_layouter
->itemMargin().width());
2408 return oldColumnCount
!= newColumnCount
;
2412 const qreal itemHeight
= m_layouter
->itemSize().height();
2413 if (itemHeight
> 0) {
2414 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2415 newItemSize
.height(),
2416 newItemMargin
.height());
2417 if (m_model
->count() > newRowCount
) {
2418 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2420 m_layouter
->itemMargin().height());
2421 return oldRowCount
!= newRowCount
;
2429 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2431 if (m_itemSize
.isEmpty()) {
2432 // We have only columns or only rows, but no grid: An animation is usually
2433 // welcome when inserting or removing items.
2434 return !supportsItemExpanding();
2437 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2441 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2442 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2443 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2444 // Only animate if up to 2/3 of a row or column are inserted or removed
2445 return changedItemCount
<= maximum
* 2 / 3;
2449 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2451 const QSizeF oldSize
= m_layouter
->size();
2453 m_layouter
->setSize(size
);
2454 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2455 m_layouter
->setSize(oldSize
);
2457 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2458 : maxOffset
> size
.width();
2461 int KItemListView::showDropIndicator(const QPointF
& pos
)
2463 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2464 while (it
.hasNext()) {
2466 const KItemListWidget
* widget
= it
.value();
2468 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2469 const QRectF rect
= itemRect(widget
->index());
2470 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2471 if (m_model
->supportsDropping(widget
->index())) {
2472 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2473 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2474 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2479 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2480 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2482 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2483 if (m_dropIndicator
!= draggingInsertIndicator
) {
2484 m_dropIndicator
= draggingInsertIndicator
;
2488 int index
= widget
->index();
2496 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2497 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2500 void KItemListView::hideDropIndicator()
2502 if (!m_dropIndicator
.isNull()) {
2503 m_dropIndicator
= QRectF();
2508 void KItemListView::updateGroupHeaderHeight()
2510 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2511 qreal groupHeaderMargin
= 0;
2513 if (scrollOrientation() == Qt::Horizontal
) {
2514 // The vertical margin above and below the header should be
2515 // equal to the horizontal margin, not the vertical margin
2516 // from m_styleOption.
2517 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2518 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2519 } else if (m_itemSize
.isEmpty()){
2520 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2521 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2523 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2524 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2526 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2527 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2529 updateVisibleGroupHeaders();
2532 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2534 if (!supportsItemExpanding() || !m_model
) {
2538 if (firstIndex
< 0 || lastIndex
< 0) {
2539 firstIndex
= m_layouter
->firstVisibleIndex();
2540 lastIndex
= m_layouter
->lastVisibleIndex();
2542 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2543 lastIndex
>= m_layouter
->firstVisibleIndex());
2544 if (!isRangeVisible
) {
2549 int previousParents
= 0;
2550 QBitArray previousSiblings
;
2552 // The rootIndex describes the first index where the siblings get
2553 // calculated from. For the calculation the upper most parent item
2554 // is required. For performance reasons it is checked first whether
2555 // the visible items before or after the current range already
2556 // contain a siblings information which can be used as base.
2557 int rootIndex
= firstIndex
;
2559 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2561 // There is no visible widget before the range, check whether there
2562 // is one after the range:
2563 widget
= m_visibleItems
.value(lastIndex
+ 1);
2565 // The sibling information of the widget may only be used if
2566 // all items of the range have the same number of parents.
2567 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2568 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2569 if (m_model
->expandedParentsCount(i
) != parents
) {
2578 // Performance optimization: Use the sibling information of the visible
2579 // widget beside the given range.
2580 previousSiblings
= widget
->siblingsInformation();
2581 if (previousSiblings
.isEmpty()) {
2584 previousParents
= previousSiblings
.count() - 1;
2585 previousSiblings
.truncate(previousParents
);
2587 // Potentially slow path: Go back to the upper most parent of firstIndex
2588 // to be able to calculate the initial value for the siblings.
2589 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2594 Q_ASSERT(previousParents
>= 0);
2595 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2596 // Update the parent-siblings in case if the current item represents
2597 // a child or an upper parent.
2598 const int currentParents
= m_model
->expandedParentsCount(i
);
2599 Q_ASSERT(currentParents
>= 0);
2600 if (previousParents
< currentParents
) {
2601 previousParents
= currentParents
;
2602 previousSiblings
.resize(currentParents
);
2603 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2604 } else if (previousParents
> currentParents
) {
2605 previousParents
= currentParents
;
2606 previousSiblings
.truncate(currentParents
);
2609 if (i
>= firstIndex
) {
2610 // The index represents a visible item. Apply the parent-siblings
2611 // and update the sibling of the current item.
2612 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2617 QBitArray siblings
= previousSiblings
;
2618 siblings
.resize(siblings
.count() + 1);
2619 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2621 widget
->setSiblingsInformation(siblings
);
2626 bool KItemListView::hasSiblingSuccessor(int index
) const
2628 bool hasSuccessor
= false;
2629 const int parentsCount
= m_model
->expandedParentsCount(index
);
2630 int successorIndex
= index
+ 1;
2632 // Search the next sibling
2633 const int itemCount
= m_model
->count();
2634 while (successorIndex
< itemCount
) {
2635 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2636 if (currentParentsCount
== parentsCount
) {
2637 hasSuccessor
= true;
2639 } else if (currentParentsCount
< parentsCount
) {
2645 if (m_grouped
&& hasSuccessor
) {
2646 // If the sibling is part of another group, don't mark it as
2647 // successor as the group header is between the sibling connections.
2648 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2649 if (m_layouter
->isFirstGroupItem(i
)) {
2650 hasSuccessor
= false;
2656 return hasSuccessor
;
2659 void KItemListView::disconnectRoleEditingSignals(int index
)
2661 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2666 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2667 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2668 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2671 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2675 const int minSpeed
= 4;
2676 const int maxSpeed
= 128;
2677 const int speedLimiter
= 96;
2678 const int autoScrollBorder
= 64;
2680 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2681 // This assures that the autoscrolling speed grows gradually.
2682 const int incLimiter
= 1;
2684 if (pos
< autoScrollBorder
) {
2685 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2686 inc
= qMax(inc
, -maxSpeed
);
2687 inc
= qMax(inc
, oldInc
- incLimiter
);
2688 } else if (pos
> range
- autoScrollBorder
) {
2689 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2690 inc
= qMin(inc
, maxSpeed
);
2691 inc
= qMin(inc
, oldInc
+ incLimiter
);
2697 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2699 const qreal availableSize
= size
- itemMargin
;
2700 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2706 KItemListCreatorBase::~KItemListCreatorBase()
2708 qDeleteAll(m_recycleableWidgets
);
2709 qDeleteAll(m_createdWidgets
);
2712 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2714 m_createdWidgets
.insert(widget
);
2717 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2719 Q_ASSERT(m_createdWidgets
.contains(widget
));
2720 m_createdWidgets
.remove(widget
);
2722 if (m_recycleableWidgets
.count() < 100) {
2723 m_recycleableWidgets
.append(widget
);
2724 widget
->setVisible(false);
2730 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2732 if (m_recycleableWidgets
.isEmpty()) {
2736 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2737 m_createdWidgets
.insert(widget
);
2741 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2745 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2747 widget
->setParentItem(nullptr);
2748 widget
->setOpacity(1.0);
2749 pushRecycleableWidget(widget
);
2752 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2756 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2758 header
->setOpacity(1.0);
2759 pushRecycleableWidget(header
);