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 foreach (const QByteArray
& role
, 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 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 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 foreach (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 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1159 const int i
= widget
->index();
1160 if (i
< firstRemovedIndex
) {
1162 } else if (i
> lastRemovedIndex
) {
1163 itemsToMove
.append(i
);
1167 m_animation
->stop(widget
);
1168 // Stopping the animation might lead to recycling the widget if
1169 // it is invisible (see slotAnimationFinished()).
1170 // Check again whether it is still visible:
1171 if (!m_visibleItems
.contains(i
)) {
1175 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1176 // Remove the widget without animation
1177 recycleWidget(widget
);
1179 // Animate the removing of the items. Special case: When removing an item there
1180 // is no valid model index available anymore. For the
1181 // remove-animation the item gets removed from m_visibleItems but the widget
1182 // will stay alive until the animation has been finished and will
1183 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1184 m_visibleItems
.remove(i
);
1185 widget
->setIndex(-1);
1186 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1190 // Update the indexes of all KItemListWidget instances that are located
1191 // after the deleted items. It is important to update them in ascending
1192 // order to prevent overlaps when setting the new index.
1193 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1194 foreach (int i
, itemsToMove
) {
1195 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1197 const int newIndex
= i
- count
;
1198 if (hasMultipleRanges
) {
1199 setWidgetIndex(widget
, newIndex
);
1201 // Try to animate the moving of the item
1202 moveWidgetToIndex(widget
, newIndex
);
1206 if (!hasMultipleRanges
) {
1207 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1208 // assumes an updated geometry. If items are removed during an active transaction,
1209 // the transaction will be temporary deactivated so that doLayout() triggers a
1210 // geometry update if necessary.
1211 const int activeTransactions
= m_activeTransactions
;
1212 m_activeTransactions
= 0;
1213 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1214 m_activeTransactions
= activeTransactions
;
1215 updateSiblingsInformation();
1220 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1223 if (hasMultipleRanges
) {
1224 m_endTransactionAnimationHint
= NoAnimation
;
1226 updateSiblingsInformation();
1229 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1230 // In case if the first item of a group has been removed, the group header
1231 // must be applied to the next visible item.
1232 updateVisibleGroupHeaders();
1235 if (useAlternateBackgrounds()) {
1236 updateAlternateBackgrounds();
1240 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1242 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1243 m_layouter
->markAsDirty();
1246 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1249 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1250 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1252 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1253 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1255 updateWidgetProperties(widget
, index
);
1256 initializeItemListWidget(widget
);
1260 doLayout(NoAnimation
);
1261 updateSiblingsInformation();
1264 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1265 const QSet
<QByteArray
>& roles
)
1267 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1268 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1269 updatePreferredColumnWidths(itemRanges
);
1272 foreach (const KItemRange
& itemRange
, itemRanges
) {
1273 const int index
= itemRange
.index
;
1274 const int count
= itemRange
.count
;
1276 if (updateSizeHints
) {
1277 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1278 m_layouter
->markAsDirty();
1280 if (!m_layoutTimer
->isActive()) {
1281 m_layoutTimer
->start();
1285 // Apply the changed roles to the visible item-widgets
1286 const int lastIndex
= index
+ count
- 1;
1287 for (int i
= index
; i
<= lastIndex
; ++i
) {
1288 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1290 widget
->setData(m_model
->data(i
), roles
);
1294 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1295 // The sort-role has been changed which might result
1296 // in modified group headers
1297 updateVisibleGroupHeaders();
1298 doLayout(NoAnimation
);
1301 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1302 ev
.setFirstRow(itemRange
.index
);
1303 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1304 QAccessible::updateAccessibility(&ev
);
1308 void KItemListView::slotGroupsChanged()
1310 updateVisibleGroupHeaders();
1311 doLayout(NoAnimation
);
1312 updateSiblingsInformation();
1315 void KItemListView::slotGroupedSortingChanged(bool current
)
1317 m_grouped
= current
;
1318 m_layouter
->markAsDirty();
1321 updateGroupHeaderHeight();
1323 // Clear all visible headers. Note that the QHashIterator takes a copy of
1324 // m_visibleGroups. Therefore, it remains valid even if items are removed
1325 // from m_visibleGroups in recycleGroupHeaderForWidget().
1326 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1327 while (it
.hasNext()) {
1329 recycleGroupHeaderForWidget(it
.key());
1331 Q_ASSERT(m_visibleGroups
.isEmpty());
1334 if (useAlternateBackgrounds()) {
1335 // Changing the group mode requires to update the alternate backgrounds
1336 // as with the enabled group mode the altering is done on base of the first
1338 updateAlternateBackgrounds();
1340 updateSiblingsInformation();
1341 doLayout(NoAnimation
);
1344 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1349 updateVisibleGroupHeaders();
1350 doLayout(NoAnimation
);
1354 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1359 updateVisibleGroupHeaders();
1360 doLayout(NoAnimation
);
1364 void KItemListView::slotCurrentChanged(int current
, int previous
)
1368 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1369 // always the selected item. It is not necessary to highlight the current item then.
1370 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1371 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1372 if (previousWidget
) {
1373 previousWidget
->setCurrent(false);
1376 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1377 if (currentWidget
) {
1378 currentWidget
->setCurrent(true);
1382 QAccessibleEvent
ev(this, QAccessible::Focus
);
1383 ev
.setChild(current
);
1384 QAccessible::updateAccessibility(&ev
);
1387 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1391 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1392 while (it
.hasNext()) {
1394 const int index
= it
.key();
1395 KItemListWidget
* widget
= it
.value();
1396 widget
->setSelected(current
.contains(index
));
1400 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1401 KItemListViewAnimation::AnimationType type
)
1403 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1404 Q_ASSERT(itemListWidget
);
1407 case KItemListViewAnimation::DeleteAnimation
: {
1408 // As we recycle the widget in this case it is important to assure that no
1409 // other animation has been started. This is a convention in KItemListView and
1410 // not a requirement defined by KItemListViewAnimation.
1411 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1413 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1414 // by m_visibleWidgets and must be deleted manually after the animation has
1416 recycleGroupHeaderForWidget(itemListWidget
);
1417 widgetCreator()->recycle(itemListWidget
);
1421 case KItemListViewAnimation::CreateAnimation
:
1422 case KItemListViewAnimation::MovingAnimation
:
1423 case KItemListViewAnimation::ResizeAnimation
: {
1424 const int index
= itemListWidget
->index();
1425 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1426 (index
> m_layouter
->lastVisibleIndex());
1427 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1428 recycleWidget(itemListWidget
);
1437 void KItemListView::slotLayoutTimerFinished()
1439 m_layouter
->setSize(geometry().size());
1440 doLayout(Animation
);
1443 void KItemListView::slotRubberBandPosChanged()
1448 void KItemListView::slotRubberBandActivationChanged(bool active
)
1451 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1452 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1453 m_skipAutoScrollForRubberBand
= true;
1455 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1456 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1457 m_skipAutoScrollForRubberBand
= false;
1463 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1465 qreal previousWidth
)
1468 Q_UNUSED(currentWidth
)
1469 Q_UNUSED(previousWidth
)
1471 m_headerWidget
->setAutomaticColumnResizing(false);
1472 applyColumnWidthsFromHeader();
1473 doLayout(NoAnimation
);
1476 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1480 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1482 const QList
<QByteArray
> previous
= m_visibleRoles
;
1484 QList
<QByteArray
> current
= m_visibleRoles
;
1485 current
.removeAt(previousIndex
);
1486 current
.insert(currentIndex
, role
);
1488 setVisibleRoles(current
);
1490 emit
visibleRolesChanged(current
, previous
);
1493 void KItemListView::triggerAutoScrolling()
1495 if (!m_autoScrollTimer
) {
1500 int visibleSize
= 0;
1501 if (scrollOrientation() == Qt::Vertical
) {
1502 pos
= m_mousePos
.y();
1503 visibleSize
= size().height();
1505 pos
= m_mousePos
.x();
1506 visibleSize
= size().width();
1509 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1510 m_autoScrollIncrement
= 0;
1513 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1514 if (m_autoScrollIncrement
== 0) {
1515 // The mouse position is not above an autoscroll margin (the autoscroll timer
1516 // will be restarted in mouseMoveEvent())
1517 m_autoScrollTimer
->stop();
1521 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1522 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1523 // if the direction of the rubberband is similar to the autoscroll direction. This
1524 // prevents that starting to create a rubberband within the autoscroll margins starts
1525 // an autoscrolling.
1527 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1528 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1529 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1530 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1531 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1532 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1533 // been moved up although the autoscroll direction might be down)
1534 m_autoScrollTimer
->stop();
1539 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1540 // the autoscrolling may not get skipped anymore until a new rubberband is created
1541 m_skipAutoScrollForRubberBand
= false;
1543 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1544 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1545 setScrollOffset(newScrollOffset
);
1547 // Trigger the autoscroll timer which will periodically call
1548 // triggerAutoScrolling()
1549 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1552 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1554 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1556 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1557 Q_ASSERT(groupHeader
);
1558 updateGroupHeaderLayout(widget
);
1561 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1563 disconnectRoleEditingSignals(index
);
1565 emit
roleEditingCanceled(index
, role
, value
);
1566 m_editingRole
= false;
1569 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1571 disconnectRoleEditingSignals(index
);
1573 emit
roleEditingFinished(index
, role
, value
);
1574 m_editingRole
= false;
1577 void KItemListView::setController(KItemListController
* controller
)
1579 if (m_controller
!= controller
) {
1580 KItemListController
* previous
= m_controller
;
1582 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1583 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1584 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1587 m_controller
= controller
;
1590 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1591 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1592 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1595 onControllerChanged(controller
, previous
);
1599 void KItemListView::setModel(KItemModelBase
* model
)
1601 if (m_model
== model
) {
1605 KItemModelBase
* previous
= m_model
;
1608 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1609 this, &KItemListView::slotItemsChanged
);
1610 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1611 this, &KItemListView::slotItemsInserted
);
1612 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1613 this, &KItemListView::slotItemsRemoved
);
1614 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1615 this, &KItemListView::slotItemsMoved
);
1616 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1617 this, &KItemListView::slotGroupsChanged
);
1618 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1619 this, &KItemListView::slotGroupedSortingChanged
);
1620 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1621 this, &KItemListView::slotSortOrderChanged
);
1622 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1623 this, &KItemListView::slotSortRoleChanged
);
1625 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1629 m_layouter
->setModel(model
);
1630 m_grouped
= model
->groupedSorting();
1633 connect(m_model
, &KItemModelBase::itemsChanged
,
1634 this, &KItemListView::slotItemsChanged
);
1635 connect(m_model
, &KItemModelBase::itemsInserted
,
1636 this, &KItemListView::slotItemsInserted
);
1637 connect(m_model
, &KItemModelBase::itemsRemoved
,
1638 this, &KItemListView::slotItemsRemoved
);
1639 connect(m_model
, &KItemModelBase::itemsMoved
,
1640 this, &KItemListView::slotItemsMoved
);
1641 connect(m_model
, &KItemModelBase::groupsChanged
,
1642 this, &KItemListView::slotGroupsChanged
);
1643 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1644 this, &KItemListView::slotGroupedSortingChanged
);
1645 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1646 this, &KItemListView::slotSortOrderChanged
);
1647 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1648 this, &KItemListView::slotSortRoleChanged
);
1650 const int itemCount
= m_model
->count();
1651 if (itemCount
> 0) {
1652 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1656 onModelChanged(model
, previous
);
1659 KItemListRubberBand
* KItemListView::rubberBand() const
1661 return m_rubberBand
;
1664 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1666 if (m_layoutTimer
->isActive()) {
1667 m_layoutTimer
->stop();
1670 if (m_activeTransactions
> 0) {
1671 if (hint
== NoAnimation
) {
1672 // As soon as at least one property change should be done without animation,
1673 // the whole transaction will be marked as not animated.
1674 m_endTransactionAnimationHint
= NoAnimation
;
1679 if (!m_model
|| m_model
->count() < 0) {
1683 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1684 if (firstVisibleIndex
< 0) {
1685 emitOffsetChanges();
1689 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1690 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1691 // is still shown if the maximum offset got decreased.
1692 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1693 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1694 if (scrollOffset() > maxOffsetToShowFullRange
) {
1695 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1696 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1699 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1701 int firstSibblingIndex
= -1;
1702 int lastSibblingIndex
= -1;
1703 const bool supportsExpanding
= supportsItemExpanding();
1705 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1707 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1708 // instances from invisible items are reused. If no reusable items are
1709 // found then new KItemListWidget instances get created.
1710 const bool animate
= (hint
== Animation
);
1711 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1712 bool applyNewPos
= true;
1713 bool wasHidden
= false;
1715 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1716 const QPointF newPos
= itemBounds
.topLeft();
1717 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1720 if (!reusableItems
.isEmpty()) {
1721 // Reuse a KItemListWidget instance from an invisible item
1722 const int oldIndex
= reusableItems
.takeLast();
1723 widget
= m_visibleItems
.value(oldIndex
);
1724 setWidgetIndex(widget
, i
);
1725 updateWidgetProperties(widget
, i
);
1726 initializeItemListWidget(widget
);
1728 // No reusable KItemListWidget instance is available, create a new one
1729 widget
= createWidget(i
);
1731 widget
->resize(itemBounds
.size());
1733 if (animate
&& changedCount
< 0) {
1734 // Items have been deleted.
1735 if (i
>= changedIndex
) {
1736 // The item is located behind the removed range. Move the
1737 // created item to the imaginary old position outside the
1738 // view. It will get animated to the new position later.
1739 const int previousIndex
= i
- changedCount
;
1740 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1741 if (itemRect
.isEmpty()) {
1742 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1743 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1744 widget
->setPos(invisibleOldPos
);
1746 widget
->setPos(itemRect
.topLeft());
1748 applyNewPos
= false;
1752 if (supportsExpanding
&& changedCount
== 0) {
1753 if (firstSibblingIndex
< 0) {
1754 firstSibblingIndex
= i
;
1756 lastSibblingIndex
= i
;
1761 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1762 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1763 applyNewPos
= false;
1766 const bool itemsRemoved
= (changedCount
< 0);
1767 const bool itemsInserted
= (changedCount
> 0);
1768 if (itemsRemoved
&& (i
>= changedIndex
)) {
1769 // The item is located after the removed items. Animate the moving of the position.
1770 applyNewPos
= !moveWidget(widget
, newPos
);
1771 } else if (itemsInserted
&& i
>= changedIndex
) {
1772 // The item is located after the first inserted item
1773 if (i
<= changedIndex
+ changedCount
- 1) {
1774 // The item is an inserted item. Animate the appearing of the item.
1775 // For performance reasons no animation is done when changedCount is equal
1776 // to all available items.
1777 if (changedCount
< m_model
->count()) {
1778 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1780 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1781 // The item was already there before, so animate the moving of the position.
1782 // No moving animation is done if the item is animated by a create animation: This
1783 // prevents a "move animation mess" when inserting several ranges in parallel.
1784 applyNewPos
= !moveWidget(widget
, newPos
);
1786 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1787 // The size of the view might have been changed. Animate the moving of the position.
1788 applyNewPos
= !moveWidget(widget
, newPos
);
1791 m_animation
->stop(widget
);
1795 widget
->setPos(newPos
);
1798 Q_ASSERT(widget
->index() == i
);
1799 widget
->setVisible(true);
1801 if (widget
->size() != itemBounds
.size()) {
1802 // Resize the widget for the item to the changed size.
1804 // If a dynamic item size is used then no animation is done in the direction
1805 // of the dynamic size.
1806 if (m_itemSize
.width() <= 0) {
1807 // The width is dynamic, apply the new width without animation.
1808 widget
->resize(itemBounds
.width(), widget
->size().height());
1809 } else if (m_itemSize
.height() <= 0) {
1810 // The height is dynamic, apply the new height without animation.
1811 widget
->resize(widget
->size().width(), itemBounds
.height());
1813 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1815 widget
->resize(itemBounds
.size());
1819 // Updating the cell-information must be done as last step: The decision whether the
1820 // moving-animation should be started at all is based on the previous cell-information.
1821 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1822 m_visibleCells
.insert(i
, cell
);
1825 // Delete invisible KItemListWidget instances that have not been reused
1826 foreach (int index
, reusableItems
) {
1827 recycleWidget(m_visibleItems
.value(index
));
1830 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1831 Q_ASSERT(lastSibblingIndex
>= 0);
1832 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1836 // Update the layout of all visible group headers
1837 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1838 while (it
.hasNext()) {
1840 updateGroupHeaderLayout(it
.key());
1844 emitOffsetChanges();
1847 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1848 int lastVisibleIndex
,
1849 LayoutAnimationHint hint
)
1851 // Determine all items that are completely invisible and might be
1852 // reused for items that just got (at least partly) visible. If the
1853 // animation hint is set to 'Animation' items that do e.g. an animated
1854 // moving of their position are not marked as invisible: This assures
1855 // that a scrolling inside the view can be done without breaking an animation.
1859 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1860 while (it
.hasNext()) {
1863 KItemListWidget
* widget
= it
.value();
1864 const int index
= widget
->index();
1865 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1868 if (m_animation
->isStarted(widget
)) {
1869 if (hint
== NoAnimation
) {
1870 // Stopping the animation will call KItemListView::slotAnimationFinished()
1871 // and the widget will be recycled if necessary there.
1872 m_animation
->stop(widget
);
1875 widget
->setVisible(false);
1876 items
.append(index
);
1879 recycleGroupHeaderForWidget(widget
);
1888 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1890 if (widget
->pos() == newPos
) {
1894 bool startMovingAnim
= false;
1896 if (m_itemSize
.isEmpty()) {
1897 // The items are not aligned in a grid but either as columns or rows.
1898 startMovingAnim
= true;
1900 // When having a grid the moving-animation should only be started, if it is done within
1901 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1902 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1903 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1904 const int index
= widget
->index();
1905 const Cell cell
= m_visibleCells
.value(index
);
1906 if (cell
.column
>= 0 && cell
.row
>= 0) {
1907 if (scrollOrientation() == Qt::Vertical
) {
1908 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1910 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1915 if (startMovingAnim
) {
1916 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1920 m_animation
->stop(widget
);
1921 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1925 void KItemListView::emitOffsetChanges()
1927 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1928 if (m_oldScrollOffset
!= newScrollOffset
) {
1929 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1930 m_oldScrollOffset
= newScrollOffset
;
1933 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1934 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1935 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1936 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1939 const qreal newItemOffset
= m_layouter
->itemOffset();
1940 if (m_oldItemOffset
!= newItemOffset
) {
1941 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1942 m_oldItemOffset
= newItemOffset
;
1945 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1946 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1947 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1948 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1952 KItemListWidget
* KItemListView::createWidget(int index
)
1954 KItemListWidget
* widget
= widgetCreator()->create(this);
1955 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1957 m_visibleItems
.insert(index
, widget
);
1958 m_visibleCells
.insert(index
, Cell());
1959 updateWidgetProperties(widget
, index
);
1960 initializeItemListWidget(widget
);
1964 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1967 recycleGroupHeaderForWidget(widget
);
1970 const int index
= widget
->index();
1971 m_visibleItems
.remove(index
);
1972 m_visibleCells
.remove(index
);
1974 widgetCreator()->recycle(widget
);
1977 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1979 const int oldIndex
= widget
->index();
1980 m_visibleItems
.remove(oldIndex
);
1981 m_visibleCells
.remove(oldIndex
);
1983 m_visibleItems
.insert(index
, widget
);
1984 m_visibleCells
.insert(index
, Cell());
1986 widget
->setIndex(index
);
1989 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1991 const int oldIndex
= widget
->index();
1992 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1994 setWidgetIndex(widget
, index
);
1996 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1997 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1998 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1999 (!vertical
&& oldCell
.column
== newCell
.column
);
2001 m_visibleCells
.insert(index
, newCell
);
2005 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2008 case LayouterSize
: m_layouter
->setSize(size
); break;
2009 case ItemSize
: m_layouter
->setItemSize(size
); break;
2014 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2016 widget
->setVisibleRoles(m_visibleRoles
);
2017 updateWidgetColumnWidths(widget
);
2018 widget
->setStyleOption(m_styleOption
);
2020 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2022 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2023 // always the selected item. It is not necessary to highlight the current item then.
2024 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2025 widget
->setCurrent(index
== selectionManager
->currentItem());
2027 widget
->setSelected(selectionManager
->isSelected(index
));
2028 widget
->setHovered(false);
2029 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2030 widget
->setIndex(index
);
2031 widget
->setData(m_model
->data(index
));
2032 widget
->setSiblingsInformation(QBitArray());
2033 updateAlternateBackgroundForWidget(widget
);
2036 updateGroupHeaderForWidget(widget
);
2040 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2042 Q_ASSERT(m_grouped
);
2044 const int index
= widget
->index();
2045 if (!m_layouter
->isFirstGroupItem(index
)) {
2046 // The widget does not represent the first item of a group
2047 // and hence requires no header
2048 recycleGroupHeaderForWidget(widget
);
2052 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2053 if (groups
.isEmpty() || !groupHeaderCreator()) {
2057 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2059 groupHeader
= groupHeaderCreator()->create(this);
2060 groupHeader
->setParentItem(widget
);
2061 m_visibleGroups
.insert(widget
, groupHeader
);
2062 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2064 Q_ASSERT(groupHeader
->parentItem() == widget
);
2066 const int groupIndex
= groupIndexForItem(index
);
2067 Q_ASSERT(groupIndex
>= 0);
2068 groupHeader
->setData(groups
.at(groupIndex
).second
);
2069 groupHeader
->setRole(model()->sortRole());
2070 groupHeader
->setStyleOption(m_styleOption
);
2071 groupHeader
->setScrollOrientation(scrollOrientation());
2072 groupHeader
->setItemIndex(index
);
2074 groupHeader
->show();
2077 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2079 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2080 Q_ASSERT(groupHeader
);
2082 const int index
= widget
->index();
2083 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2084 const QRectF itemRect
= m_layouter
->itemRect(index
);
2086 // The group-header is a child of the itemlist widget. Translate the
2087 // group header position to the relative position.
2088 if (scrollOrientation() == Qt::Vertical
) {
2089 // In the vertical scroll orientation the group header should always span
2090 // the whole width no matter which temporary position the parent widget
2091 // has. In this case the x-position and width will be adjusted manually.
2092 const qreal x
= -widget
->x() - itemOffset();
2093 const qreal width
= maximumItemOffset();
2094 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2095 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2097 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2098 groupHeader
->resize(groupHeaderRect
.size());
2102 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2104 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2106 header
->setParentItem(nullptr);
2107 groupHeaderCreator()->recycle(header
);
2108 m_visibleGroups
.remove(widget
);
2109 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2113 void KItemListView::updateVisibleGroupHeaders()
2115 Q_ASSERT(m_grouped
);
2116 m_layouter
->markAsDirty();
2118 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2119 while (it
.hasNext()) {
2121 updateGroupHeaderForWidget(it
.value());
2125 int KItemListView::groupIndexForItem(int index
) const
2127 Q_ASSERT(m_grouped
);
2129 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2130 if (groups
.isEmpty()) {
2135 int max
= groups
.count() - 1;
2138 mid
= (min
+ max
) / 2;
2139 if (index
> groups
[mid
].first
) {
2144 } while (groups
[mid
].first
!= index
&& min
<= max
);
2147 while (groups
[mid
].first
> index
&& mid
> 0) {
2155 void KItemListView::updateAlternateBackgrounds()
2157 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2158 while (it
.hasNext()) {
2160 updateAlternateBackgroundForWidget(it
.value());
2164 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2166 bool enabled
= useAlternateBackgrounds();
2168 const int index
= widget
->index();
2169 enabled
= (index
& 0x1) > 0;
2171 const int groupIndex
= groupIndexForItem(index
);
2172 if (groupIndex
>= 0) {
2173 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2174 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2175 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2176 enabled
= (relativeIndex
& 0x1) > 0;
2180 widget
->setAlternateBackground(enabled
);
2183 bool KItemListView::useAlternateBackgrounds() const
2185 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2188 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2190 QElapsedTimer timer
;
2193 QHash
<QByteArray
, qreal
> widths
;
2195 // Calculate the minimum width for each column that is required
2196 // to show the headline unclipped.
2197 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2198 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2199 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2200 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2201 const QString headerText
= m_model
->roleDescription(visibleRole
);
2202 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2203 widths
.insert(visibleRole
, headerWidth
);
2206 // Calculate the preferred column withs for each item and ignore values
2207 // smaller than the width for showing the headline unclipped.
2208 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2209 int calculatedItemCount
= 0;
2210 bool maxTimeExceeded
= false;
2211 foreach (const KItemRange
& itemRange
, itemRanges
) {
2212 const int startIndex
= itemRange
.index
;
2213 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2215 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2216 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2217 qreal maxWidth
= widths
.value(visibleRole
, 0);
2218 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2219 maxWidth
= qMax(width
, maxWidth
);
2220 widths
.insert(visibleRole
, maxWidth
);
2223 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2224 // When having several thousands of items calculating the sizes can get
2225 // very expensive. We accept a possibly too small role-size in favour
2226 // of having no blocking user interface.
2227 maxTimeExceeded
= true;
2230 ++calculatedItemCount
;
2232 if (maxTimeExceeded
) {
2240 void KItemListView::applyColumnWidthsFromHeader()
2242 // Apply the new size to the layouter
2243 const qreal requiredWidth
= columnWidthsSum();
2244 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2245 m_itemSize
.height());
2246 m_layouter
->setItemSize(dynamicItemSize
);
2248 // Update the role sizes for all visible widgets
2249 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2250 while (it
.hasNext()) {
2252 updateWidgetColumnWidths(it
.value());
2256 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2258 foreach (const QByteArray
& role
, m_visibleRoles
) {
2259 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2263 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2265 Q_ASSERT(m_itemSize
.isEmpty());
2266 const int itemCount
= m_model
->count();
2267 int rangesItemCount
= 0;
2268 foreach (const KItemRange
& range
, itemRanges
) {
2269 rangesItemCount
+= range
.count
;
2272 if (itemCount
== rangesItemCount
) {
2273 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2274 foreach (const QByteArray
& role
, m_visibleRoles
) {
2275 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2278 // Only a sub range of the roles need to be determined.
2279 // The chances are good that the widths of the sub ranges
2280 // already fit into the available widths and hence no
2281 // expensive update might be required.
2282 bool changed
= false;
2284 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2285 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2286 while (it
.hasNext()) {
2288 const QByteArray
& role
= it
.key();
2289 const qreal updatedWidth
= it
.value();
2290 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2291 if (updatedWidth
> currentWidth
) {
2292 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2298 // All the updated sizes are smaller than the current sizes and no change
2299 // of the stretched roles-widths is required
2304 if (m_headerWidget
->automaticColumnResizing()) {
2305 applyAutomaticColumnWidths();
2309 void KItemListView::updatePreferredColumnWidths()
2312 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2316 void KItemListView::applyAutomaticColumnWidths()
2318 Q_ASSERT(m_itemSize
.isEmpty());
2319 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2320 if (m_visibleRoles
.isEmpty()) {
2324 // Calculate the maximum size of an item by considering the
2325 // visible role sizes and apply them to the layouter. If the
2326 // size does not use the available view-size the size of the
2327 // first role will get stretched.
2329 foreach (const QByteArray
& role
, m_visibleRoles
) {
2330 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2331 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2334 const QByteArray firstRole
= m_visibleRoles
.first();
2335 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2336 QSizeF dynamicItemSize
= m_itemSize
;
2338 qreal requiredWidth
= columnWidthsSum();
2339 const qreal availableWidth
= size().width();
2340 if (requiredWidth
< availableWidth
) {
2341 // Stretch the first column to use the whole remaining width
2342 firstColumnWidth
+= availableWidth
- requiredWidth
;
2343 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2344 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2345 // Shrink the first column to be able to show as much other
2346 // columns as possible
2347 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2349 // TODO: A proper calculation of the minimum width depends on the implementation
2350 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2352 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2353 if (shrinkedFirstColumnWidth
< minWidth
) {
2354 shrinkedFirstColumnWidth
= minWidth
;
2357 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2358 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2361 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2363 m_layouter
->setItemSize(dynamicItemSize
);
2365 // Update the role sizes for all visible widgets
2366 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2367 while (it
.hasNext()) {
2369 updateWidgetColumnWidths(it
.value());
2373 qreal
KItemListView::columnWidthsSum() const
2375 qreal widthsSum
= 0;
2376 foreach (const QByteArray
& role
, m_visibleRoles
) {
2377 widthsSum
+= m_headerWidget
->columnWidth(role
);
2382 QRectF
KItemListView::headerBoundaries() const
2384 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2387 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2388 const QSizeF
& newItemSize
,
2389 const QSizeF
& newItemMargin
) const
2391 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2395 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2396 const qreal itemWidth
= m_layouter
->itemSize().width();
2397 if (itemWidth
> 0) {
2398 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2399 newItemSize
.width(),
2400 newItemMargin
.width());
2401 if (m_model
->count() > newColumnCount
) {
2402 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2404 m_layouter
->itemMargin().width());
2405 return oldColumnCount
!= newColumnCount
;
2409 const qreal itemHeight
= m_layouter
->itemSize().height();
2410 if (itemHeight
> 0) {
2411 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2412 newItemSize
.height(),
2413 newItemMargin
.height());
2414 if (m_model
->count() > newRowCount
) {
2415 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2417 m_layouter
->itemMargin().height());
2418 return oldRowCount
!= newRowCount
;
2426 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2428 if (m_itemSize
.isEmpty()) {
2429 // We have only columns or only rows, but no grid: An animation is usually
2430 // welcome when inserting or removing items.
2431 return !supportsItemExpanding();
2434 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2438 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2439 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2440 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2441 // Only animate if up to 2/3 of a row or column are inserted or removed
2442 return changedItemCount
<= maximum
* 2 / 3;
2446 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2448 const QSizeF oldSize
= m_layouter
->size();
2450 m_layouter
->setSize(size
);
2451 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2452 m_layouter
->setSize(oldSize
);
2454 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2455 : maxOffset
> size
.width();
2458 int KItemListView::showDropIndicator(const QPointF
& pos
)
2460 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2461 while (it
.hasNext()) {
2463 const KItemListWidget
* widget
= it
.value();
2465 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2466 const QRectF rect
= itemRect(widget
->index());
2467 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2468 if (m_model
->supportsDropping(widget
->index())) {
2469 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2470 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2471 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2476 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2477 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2479 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2480 if (m_dropIndicator
!= draggingInsertIndicator
) {
2481 m_dropIndicator
= draggingInsertIndicator
;
2485 int index
= widget
->index();
2493 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2494 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2497 void KItemListView::hideDropIndicator()
2499 if (!m_dropIndicator
.isNull()) {
2500 m_dropIndicator
= QRectF();
2505 void KItemListView::updateGroupHeaderHeight()
2507 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2508 qreal groupHeaderMargin
= 0;
2510 if (scrollOrientation() == Qt::Horizontal
) {
2511 // The vertical margin above and below the header should be
2512 // equal to the horizontal margin, not the vertical margin
2513 // from m_styleOption.
2514 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2515 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2516 } else if (m_itemSize
.isEmpty()){
2517 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2518 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2520 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2521 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2523 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2524 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2526 updateVisibleGroupHeaders();
2529 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2531 if (!supportsItemExpanding() || !m_model
) {
2535 if (firstIndex
< 0 || lastIndex
< 0) {
2536 firstIndex
= m_layouter
->firstVisibleIndex();
2537 lastIndex
= m_layouter
->lastVisibleIndex();
2539 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2540 lastIndex
>= m_layouter
->firstVisibleIndex());
2541 if (!isRangeVisible
) {
2546 int previousParents
= 0;
2547 QBitArray previousSiblings
;
2549 // The rootIndex describes the first index where the siblings get
2550 // calculated from. For the calculation the upper most parent item
2551 // is required. For performance reasons it is checked first whether
2552 // the visible items before or after the current range already
2553 // contain a siblings information which can be used as base.
2554 int rootIndex
= firstIndex
;
2556 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2558 // There is no visible widget before the range, check whether there
2559 // is one after the range:
2560 widget
= m_visibleItems
.value(lastIndex
+ 1);
2562 // The sibling information of the widget may only be used if
2563 // all items of the range have the same number of parents.
2564 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2565 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2566 if (m_model
->expandedParentsCount(i
) != parents
) {
2575 // Performance optimization: Use the sibling information of the visible
2576 // widget beside the given range.
2577 previousSiblings
= widget
->siblingsInformation();
2578 if (previousSiblings
.isEmpty()) {
2581 previousParents
= previousSiblings
.count() - 1;
2582 previousSiblings
.truncate(previousParents
);
2584 // Potentially slow path: Go back to the upper most parent of firstIndex
2585 // to be able to calculate the initial value for the siblings.
2586 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2591 Q_ASSERT(previousParents
>= 0);
2592 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2593 // Update the parent-siblings in case if the current item represents
2594 // a child or an upper parent.
2595 const int currentParents
= m_model
->expandedParentsCount(i
);
2596 Q_ASSERT(currentParents
>= 0);
2597 if (previousParents
< currentParents
) {
2598 previousParents
= currentParents
;
2599 previousSiblings
.resize(currentParents
);
2600 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2601 } else if (previousParents
> currentParents
) {
2602 previousParents
= currentParents
;
2603 previousSiblings
.truncate(currentParents
);
2606 if (i
>= firstIndex
) {
2607 // The index represents a visible item. Apply the parent-siblings
2608 // and update the sibling of the current item.
2609 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2614 QBitArray siblings
= previousSiblings
;
2615 siblings
.resize(siblings
.count() + 1);
2616 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2618 widget
->setSiblingsInformation(siblings
);
2623 bool KItemListView::hasSiblingSuccessor(int index
) const
2625 bool hasSuccessor
= false;
2626 const int parentsCount
= m_model
->expandedParentsCount(index
);
2627 int successorIndex
= index
+ 1;
2629 // Search the next sibling
2630 const int itemCount
= m_model
->count();
2631 while (successorIndex
< itemCount
) {
2632 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2633 if (currentParentsCount
== parentsCount
) {
2634 hasSuccessor
= true;
2636 } else if (currentParentsCount
< parentsCount
) {
2642 if (m_grouped
&& hasSuccessor
) {
2643 // If the sibling is part of another group, don't mark it as
2644 // successor as the group header is between the sibling connections.
2645 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2646 if (m_layouter
->isFirstGroupItem(i
)) {
2647 hasSuccessor
= false;
2653 return hasSuccessor
;
2656 void KItemListView::disconnectRoleEditingSignals(int index
)
2658 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2663 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2664 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2665 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2668 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2672 const int minSpeed
= 4;
2673 const int maxSpeed
= 128;
2674 const int speedLimiter
= 96;
2675 const int autoScrollBorder
= 64;
2677 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2678 // This assures that the autoscrolling speed grows gradually.
2679 const int incLimiter
= 1;
2681 if (pos
< autoScrollBorder
) {
2682 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2683 inc
= qMax(inc
, -maxSpeed
);
2684 inc
= qMax(inc
, oldInc
- incLimiter
);
2685 } else if (pos
> range
- autoScrollBorder
) {
2686 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2687 inc
= qMin(inc
, maxSpeed
);
2688 inc
= qMin(inc
, oldInc
+ incLimiter
);
2694 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2696 const qreal availableSize
= size
- itemMargin
;
2697 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2703 KItemListCreatorBase::~KItemListCreatorBase()
2705 qDeleteAll(m_recycleableWidgets
);
2706 qDeleteAll(m_createdWidgets
);
2709 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2711 m_createdWidgets
.insert(widget
);
2714 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2716 Q_ASSERT(m_createdWidgets
.contains(widget
));
2717 m_createdWidgets
.remove(widget
);
2719 if (m_recycleableWidgets
.count() < 100) {
2720 m_recycleableWidgets
.append(widget
);
2721 widget
->setVisible(false);
2727 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2729 if (m_recycleableWidgets
.isEmpty()) {
2733 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2734 m_createdWidgets
.insert(widget
);
2738 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2742 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2744 widget
->setParentItem(nullptr);
2745 widget
->setOpacity(1.0);
2746 pushRecycleableWidget(widget
);
2749 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2753 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2755 header
->setOpacity(1.0);
2756 pushRecycleableWidget(header
);