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);
95 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
97 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
99 m_animation
= new KItemListViewAnimation(this);
100 connect(m_animation
, &KItemListViewAnimation::finished
,
101 this, &KItemListView::slotAnimationFinished
);
103 m_layoutTimer
= new QTimer(this);
104 m_layoutTimer
->setInterval(300);
105 m_layoutTimer
->setSingleShot(true);
106 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
108 m_rubberBand
= new KItemListRubberBand(this);
109 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
111 m_tapAndHoldIndicator
= new KItemListRubberBand(this);
112 m_indicatorAnimation
= new QPropertyAnimation(m_tapAndHoldIndicator
, "endPosition", this);
113 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::activationChanged
, this, [this](bool active
) {
115 m_indicatorAnimation
->setDuration(150);
116 m_indicatorAnimation
->setStartValue(QPointF(1, 1));
117 m_indicatorAnimation
->setEndValue(QPointF(40, 40));
118 m_indicatorAnimation
->start();
122 connect(m_tapAndHoldIndicator
, &KItemListRubberBand::endPositionChanged
, this, [this]() {
123 if (m_tapAndHoldIndicator
->isActive()) {
128 m_headerWidget
= new KItemListHeaderWidget(this);
129 m_headerWidget
->setVisible(false);
131 m_header
= new KItemListHeader(this);
133 #ifndef QT_NO_ACCESSIBILITY
134 QAccessible::installFactory(accessibleInterfaceFactory
);
139 KItemListView::~KItemListView()
141 // The group headers are children of the widgets created by
142 // widgetCreator(). So it is mandatory to delete the group headers
144 delete m_groupHeaderCreator
;
145 m_groupHeaderCreator
= nullptr;
147 delete m_widgetCreator
;
148 m_widgetCreator
= nullptr;
150 delete m_sizeHintResolver
;
151 m_sizeHintResolver
= nullptr;
154 void KItemListView::setScrollOffset(qreal offset
)
160 const qreal previousOffset
= m_layouter
->scrollOffset();
161 if (offset
== previousOffset
) {
165 m_layouter
->setScrollOffset(offset
);
166 m_animation
->setScrollOffset(offset
);
168 // Don't check whether the m_layoutTimer is active: Changing the
169 // scroll offset must always trigger a synchronous layout, otherwise
170 // the smooth-scrolling might get jerky.
171 doLayout(NoAnimation
);
172 onScrollOffsetChanged(offset
, previousOffset
);
175 qreal
KItemListView::scrollOffset() const
177 return m_layouter
->scrollOffset();
180 qreal
KItemListView::maximumScrollOffset() const
182 return m_layouter
->maximumScrollOffset();
185 void KItemListView::setItemOffset(qreal offset
)
187 if (m_layouter
->itemOffset() == offset
) {
191 m_layouter
->setItemOffset(offset
);
192 if (m_headerWidget
->isVisible()) {
193 m_headerWidget
->setOffset(offset
);
196 // Don't check whether the m_layoutTimer is active: Changing the
197 // item offset must always trigger a synchronous layout, otherwise
198 // the smooth-scrolling might get jerky.
199 doLayout(NoAnimation
);
202 qreal
KItemListView::itemOffset() const
204 return m_layouter
->itemOffset();
207 qreal
KItemListView::maximumItemOffset() const
209 return m_layouter
->maximumItemOffset();
212 int KItemListView::maximumVisibleItems() const
214 return m_layouter
->maximumVisibleItems();
217 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
219 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
220 m_visibleRoles
= roles
;
221 onVisibleRolesChanged(roles
, previousRoles
);
223 m_sizeHintResolver
->clearCache();
224 m_layouter
->markAsDirty();
226 if (m_itemSize
.isEmpty()) {
227 m_headerWidget
->setColumns(roles
);
228 updatePreferredColumnWidths();
229 if (!m_headerWidget
->automaticColumnResizing()) {
230 // The column-width of new roles are still 0. Apply the preferred
231 // column-width as default with.
232 foreach (const QByteArray
& role
, m_visibleRoles
) {
233 if (m_headerWidget
->columnWidth(role
) == 0) {
234 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
235 m_headerWidget
->setColumnWidth(role
, width
);
239 applyColumnWidthsFromHeader();
243 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
244 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
245 (roles
.count() <= 1 && previousRoles
.count() > 1));
247 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
248 while (it
.hasNext()) {
250 KItemListWidget
* widget
= it
.value();
251 widget
->setVisibleRoles(roles
);
252 if (alternateBackgroundsChanged
) {
253 updateAlternateBackgroundForWidget(widget
);
257 doLayout(NoAnimation
);
260 QList
<QByteArray
> KItemListView::visibleRoles() const
262 return m_visibleRoles
;
265 void KItemListView::setAutoScroll(bool enabled
)
267 if (enabled
&& !m_autoScrollTimer
) {
268 m_autoScrollTimer
= new QTimer(this);
269 m_autoScrollTimer
->setSingleShot(true);
270 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
271 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
272 } else if (!enabled
&& m_autoScrollTimer
) {
273 delete m_autoScrollTimer
;
274 m_autoScrollTimer
= nullptr;
278 bool KItemListView::autoScroll() const
280 return m_autoScrollTimer
!= nullptr;
283 void KItemListView::setEnabledSelectionToggles(bool enabled
)
285 if (m_enabledSelectionToggles
!= enabled
) {
286 m_enabledSelectionToggles
= enabled
;
288 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
289 while (it
.hasNext()) {
291 it
.value()->setEnabledSelectionToggle(enabled
);
296 bool KItemListView::enabledSelectionToggles() const
298 return m_enabledSelectionToggles
;
301 KItemListController
* KItemListView::controller() const
306 KItemModelBase
* KItemListView::model() const
311 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
313 delete m_widgetCreator
;
314 m_widgetCreator
= widgetCreator
;
317 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
319 if (!m_widgetCreator
) {
320 m_widgetCreator
= defaultWidgetCreator();
322 return m_widgetCreator
;
325 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
327 delete m_groupHeaderCreator
;
328 m_groupHeaderCreator
= groupHeaderCreator
;
331 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
333 if (!m_groupHeaderCreator
) {
334 m_groupHeaderCreator
= defaultGroupHeaderCreator();
336 return m_groupHeaderCreator
;
339 QSizeF
KItemListView::itemSize() const
344 const KItemListStyleOption
& KItemListView::styleOption() const
346 return m_styleOption
;
349 void KItemListView::setGeometry(const QRectF
& rect
)
351 QGraphicsWidget::setGeometry(rect
);
357 const QSizeF newSize
= rect
.size();
358 if (m_itemSize
.isEmpty()) {
359 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
360 if (m_headerWidget
->automaticColumnResizing()) {
361 applyAutomaticColumnWidths();
363 const qreal requiredWidth
= columnWidthsSum();
364 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
365 m_itemSize
.height());
366 m_layouter
->setItemSize(dynamicItemSize
);
369 // Triggering a synchronous layout is fine from a performance point of view,
370 // as with dynamic item sizes no moving animation must be done.
371 m_layouter
->setSize(newSize
);
372 doLayout(NoAnimation
);
374 const bool animate
= !changesItemGridLayout(newSize
,
375 m_layouter
->itemSize(),
376 m_layouter
->itemMargin());
377 m_layouter
->setSize(newSize
);
380 // Trigger an asynchronous relayout with m_layoutTimer to prevent
381 // performance bottlenecks. If the timer is exceeded, an animated layout
382 // will be triggered.
383 if (!m_layoutTimer
->isActive()) {
384 m_layoutTimer
->start();
387 m_layoutTimer
->stop();
388 doLayout(NoAnimation
);
393 qreal
KItemListView::verticalPageStep() const
395 qreal headerHeight
= 0;
396 if (m_headerWidget
->isVisible()) {
397 headerHeight
= m_headerWidget
->size().height();
399 return size().height() - headerHeight
;
402 int KItemListView::itemAt(const QPointF
& pos
) const
404 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
405 while (it
.hasNext()) {
408 const KItemListWidget
* widget
= it
.value();
409 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
410 if (widget
->contains(mappedPos
)) {
418 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
420 if (!m_enabledSelectionToggles
) {
424 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
426 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
427 if (!selectionToggleRect
.isEmpty()) {
428 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
429 return selectionToggleRect
.contains(mappedPos
);
435 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
437 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
439 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
440 if (!expansionToggleRect
.isEmpty()) {
441 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
442 return expansionToggleRect
.contains(mappedPos
);
448 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
450 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
452 const QRectF
&textRect
= widget
->textRect();
453 if (!textRect
.isEmpty()) {
454 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
455 return textRect
.contains(mappedPos
);
461 int KItemListView::firstVisibleIndex() const
463 return m_layouter
->firstVisibleIndex();
466 int KItemListView::lastVisibleIndex() const
468 return m_layouter
->lastVisibleIndex();
471 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
473 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
476 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
478 if (m_supportsItemExpanding
!= supportsExpanding
) {
479 m_supportsItemExpanding
= supportsExpanding
;
480 updateSiblingsInformation();
481 onSupportsItemExpandingChanged(supportsExpanding
);
485 bool KItemListView::supportsItemExpanding() const
487 return m_supportsItemExpanding
;
490 QRectF
KItemListView::itemRect(int index
) const
492 return m_layouter
->itemRect(index
);
495 QRectF
KItemListView::itemContextRect(int index
) const
499 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
501 contextRect
= widget
->iconRect() | widget
->textRect();
502 contextRect
.translate(itemRect(index
).topLeft());
508 void KItemListView::scrollToItem(int index
)
510 QRectF viewGeometry
= geometry();
511 if (m_headerWidget
->isVisible()) {
512 const qreal headerHeight
= m_headerWidget
->size().height();
513 viewGeometry
.adjust(0, headerHeight
, 0, 0);
515 QRectF currentRect
= itemRect(index
);
517 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
518 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
519 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
521 if (!viewGeometry
.contains(currentRect
)) {
522 qreal newOffset
= scrollOffset();
523 if (scrollOrientation() == Qt::Vertical
) {
524 if (currentRect
.top() < viewGeometry
.top()) {
525 newOffset
+= currentRect
.top() - viewGeometry
.top();
526 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
527 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
530 if (currentRect
.left() < viewGeometry
.left()) {
531 newOffset
+= currentRect
.left() - viewGeometry
.left();
532 } else if (currentRect
.right() > viewGeometry
.right()) {
533 newOffset
+= currentRect
.right() - viewGeometry
.right();
537 if (newOffset
!= scrollOffset()) {
538 emit
scrollTo(newOffset
);
543 void KItemListView::beginTransaction()
545 ++m_activeTransactions
;
546 if (m_activeTransactions
== 1) {
547 onTransactionBegin();
551 void KItemListView::endTransaction()
553 --m_activeTransactions
;
554 if (m_activeTransactions
< 0) {
555 m_activeTransactions
= 0;
556 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
559 if (m_activeTransactions
== 0) {
561 doLayout(m_endTransactionAnimationHint
);
562 m_endTransactionAnimationHint
= Animation
;
566 bool KItemListView::isTransactionActive() const
568 return m_activeTransactions
> 0;
571 void KItemListView::setHeaderVisible(bool visible
)
573 if (visible
&& !m_headerWidget
->isVisible()) {
574 QStyleOptionHeader option
;
575 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
578 m_headerWidget
->setPos(0, 0);
579 m_headerWidget
->resize(size().width(), headerSize
.height());
580 m_headerWidget
->setModel(m_model
);
581 m_headerWidget
->setColumns(m_visibleRoles
);
582 m_headerWidget
->setZValue(1);
584 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
585 this, &KItemListView::slotHeaderColumnWidthChanged
);
586 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
587 this, &KItemListView::slotHeaderColumnMoved
);
588 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
589 this, &KItemListView::sortOrderChanged
);
590 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
591 this, &KItemListView::sortRoleChanged
);
593 m_layouter
->setHeaderHeight(headerSize
.height());
594 m_headerWidget
->setVisible(true);
595 } else if (!visible
&& m_headerWidget
->isVisible()) {
596 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
597 this, &KItemListView::slotHeaderColumnWidthChanged
);
598 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
599 this, &KItemListView::slotHeaderColumnMoved
);
600 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
601 this, &KItemListView::sortOrderChanged
);
602 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
603 this, &KItemListView::sortRoleChanged
);
605 m_layouter
->setHeaderHeight(0);
606 m_headerWidget
->setVisible(false);
610 bool KItemListView::isHeaderVisible() const
612 return m_headerWidget
->isVisible();
615 KItemListHeader
* KItemListView::header() const
620 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
624 if (indexes
.count() == 1) {
625 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
626 QGraphicsView
* graphicsView
= scene()->views()[0];
627 if (item
&& graphicsView
) {
628 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
631 // TODO: Not implemented yet. Probably extend the interface
632 // from KItemListWidget::createDragPixmap() to return a pixmap
633 // that can be used for multiple indexes.
639 void KItemListView::editRole(int index
, const QByteArray
& role
)
641 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
642 if (!widget
|| m_editingRole
) {
646 m_editingRole
= true;
647 widget
->setEditedRole(role
);
649 connect(widget
, &KItemListWidget::roleEditingCanceled
,
650 this, &KItemListView::slotRoleEditingCanceled
);
651 connect(widget
, &KItemListWidget::roleEditingFinished
,
652 this, &KItemListView::slotRoleEditingFinished
);
654 connect(this, &KItemListView::scrollOffsetChanged
,
655 widget
, &KStandardItemListWidget::finishRoleEditing
);
658 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
660 QGraphicsWidget::paint(painter
, option
, widget
);
662 if (m_rubberBand
->isActive()) {
663 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
664 m_rubberBand
->endPosition()).normalized();
666 const QPointF topLeft
= rubberBandRect
.topLeft();
667 if (scrollOrientation() == Qt::Vertical
) {
668 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
670 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
673 QStyleOptionRubberBand opt
;
674 initStyleOption(&opt
);
675 opt
.shape
= QRubberBand::Rectangle
;
677 opt
.rect
= rubberBandRect
.toRect();
678 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
681 if (m_tapAndHoldIndicator
->isActive()) {
682 const QPointF indicatorSize
= m_tapAndHoldIndicator
->endPosition();
683 const QRectF rubberBandRect
= QRectF(m_tapAndHoldIndicator
->startPosition() - indicatorSize
,
684 (m_tapAndHoldIndicator
->startPosition()) + indicatorSize
).normalized();
685 QStyleOptionRubberBand opt
;
686 initStyleOption(&opt
);
687 opt
.shape
= QRubberBand::Rectangle
;
689 opt
.rect
= rubberBandRect
.toRect();
690 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
693 if (!m_dropIndicator
.isEmpty()) {
694 const QRectF r
= m_dropIndicator
.toRect();
696 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
697 painter
->setPen(color
);
699 // TODO: The following implementation works only for a vertical scroll-orientation
700 // and assumes a height of the m_draggingInsertIndicator of 1.
701 Q_ASSERT(r
.height() == 1);
702 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
705 painter
->setPen(color
);
706 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
710 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
712 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
713 if (!scene()->views().isEmpty()) {
714 m_styleOption
.palette
= scene()->views().at(0)->palette();
717 return QGraphicsItem::itemChange(change
, value
);
720 void KItemListView::setItemSize(const QSizeF
& size
)
722 const QSizeF previousSize
= m_itemSize
;
723 if (size
== previousSize
) {
727 // Skip animations when the number of rows or columns
728 // are changed in the grid layout. Although the animation
729 // engine can handle this usecase, it looks obtrusive.
730 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
732 m_layouter
->itemMargin());
734 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
735 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
736 (!m_itemSize
.isEmpty() && size
.isEmpty()));
740 if (alternateBackgroundsChanged
) {
741 // For an empty item size alternate backgrounds are drawn if more than
742 // one role is shown. Assure that the backgrounds for visible items are
743 // updated when changing the size in this context.
744 updateAlternateBackgrounds();
747 if (size
.isEmpty()) {
748 if (m_headerWidget
->automaticColumnResizing()) {
749 updatePreferredColumnWidths();
751 // Only apply the changed height and respect the header widths
753 const qreal currentWidth
= m_layouter
->itemSize().width();
754 const QSizeF
newSize(currentWidth
, size
.height());
755 m_layouter
->setItemSize(newSize
);
758 m_layouter
->setItemSize(size
);
761 m_sizeHintResolver
->clearCache();
762 doLayout(animate
? Animation
: NoAnimation
);
763 onItemSizeChanged(size
, previousSize
);
766 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
768 if (m_styleOption
== option
) {
772 const KItemListStyleOption previousOption
= m_styleOption
;
773 m_styleOption
= option
;
776 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
777 if (margin
!= m_layouter
->itemMargin()) {
778 // Skip animations when the number of rows or columns
779 // are changed in the grid layout. Although the animation
780 // engine can handle this usecase, it looks obtrusive.
781 animate
= !changesItemGridLayout(m_layouter
->size(),
782 m_layouter
->itemSize(),
784 m_layouter
->setItemMargin(margin
);
788 updateGroupHeaderHeight();
792 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
793 // Animating a change of the maximum text size just results in expensive
794 // temporary eliding and clipping operations and does not look good visually.
798 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
799 while (it
.hasNext()) {
801 it
.value()->setStyleOption(option
);
804 m_sizeHintResolver
->clearCache();
805 m_layouter
->markAsDirty();
806 doLayout(animate
? Animation
: NoAnimation
);
808 if (m_itemSize
.isEmpty()) {
809 updatePreferredColumnWidths();
812 onStyleOptionChanged(option
, previousOption
);
815 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
817 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
818 if (orientation
== previousOrientation
) {
822 m_layouter
->setScrollOrientation(orientation
);
823 m_animation
->setScrollOrientation(orientation
);
824 m_sizeHintResolver
->clearCache();
827 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
828 while (it
.hasNext()) {
830 it
.value()->setScrollOrientation(orientation
);
832 updateGroupHeaderHeight();
836 doLayout(NoAnimation
);
838 onScrollOrientationChanged(orientation
, previousOrientation
);
839 emit
scrollOrientationChanged(orientation
, previousOrientation
);
842 Qt::Orientation
KItemListView::scrollOrientation() const
844 return m_layouter
->scrollOrientation();
847 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
852 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
857 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
862 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
864 Q_UNUSED(changedRoles
)
868 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
874 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
880 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
886 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
892 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
898 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
904 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
910 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
912 Q_UNUSED(supportsExpanding
)
915 void KItemListView::onTransactionBegin()
919 void KItemListView::onTransactionEnd()
923 bool KItemListView::event(QEvent
* event
)
925 switch (event
->type()) {
926 case QEvent::PaletteChange
:
930 case QEvent::FontChange
:
935 // Forward all other events to the controller and handle them there
936 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
942 return QGraphicsWidget::event(event
);
945 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
947 m_mousePos
= transform().map(event
->pos());
951 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
953 QGraphicsWidget::mouseMoveEvent(event
);
955 m_mousePos
= transform().map(event
->pos());
956 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
957 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
961 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
963 event
->setAccepted(true);
967 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
969 QGraphicsWidget::dragMoveEvent(event
);
971 m_mousePos
= transform().map(event
->pos());
972 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
973 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
977 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
979 QGraphicsWidget::dragLeaveEvent(event
);
980 setAutoScroll(false);
983 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
985 QGraphicsWidget::dropEvent(event
);
986 setAutoScroll(false);
989 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
991 return m_visibleItems
.values();
994 void KItemListView::updateFont()
996 if (scene() && !scene()->views().isEmpty()) {
997 KItemListStyleOption option
= styleOption();
998 option
.font
= scene()->views().first()->font();
999 option
.fontMetrics
= QFontMetrics(option
.font
);
1001 setStyleOption(option
);
1005 void KItemListView::updatePalette()
1007 if (scene() && !scene()->views().isEmpty()) {
1008 KItemListStyleOption option
= styleOption();
1009 option
.palette
= scene()->views().first()->palette();
1011 setStyleOption(option
);
1015 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1017 if (m_itemSize
.isEmpty()) {
1018 updatePreferredColumnWidths(itemRanges
);
1021 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1022 if (hasMultipleRanges
) {
1026 m_layouter
->markAsDirty();
1028 m_sizeHintResolver
->itemsInserted(itemRanges
);
1030 int previouslyInsertedCount
= 0;
1031 foreach (const KItemRange
& range
, itemRanges
) {
1032 // range.index is related to the model before anything has been inserted.
1033 // As in each loop the current item-range gets inserted the index must
1034 // be increased by the already previously inserted items.
1035 const int index
= range
.index
+ previouslyInsertedCount
;
1036 const int count
= range
.count
;
1037 if (index
< 0 || count
<= 0) {
1038 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1041 previouslyInsertedCount
+= count
;
1043 // Determine which visible items must be moved
1044 QList
<int> itemsToMove
;
1045 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1046 while (it
.hasNext()) {
1048 const int visibleItemIndex
= it
.key();
1049 if (visibleItemIndex
>= index
) {
1050 itemsToMove
.append(visibleItemIndex
);
1054 // Update the indexes of all KItemListWidget instances that are located
1055 // after the inserted items. It is important to adjust the indexes in the order
1056 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1057 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1058 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1059 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1061 const int newIndex
= widget
->index() + count
;
1062 if (hasMultipleRanges
) {
1063 setWidgetIndex(widget
, newIndex
);
1065 // Try to animate the moving of the item
1066 moveWidgetToIndex(widget
, newIndex
);
1070 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1071 // Check whether a scrollbar is required to show the inserted items. In this case
1072 // the size of the layouter will be decreased before calling doLayout(): This prevents
1073 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1074 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1075 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1076 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1077 if (decreaseLayouterSize
) {
1078 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1080 int scrollbarSpacing
= 0;
1081 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1082 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1085 QSizeF layouterSize
= m_layouter
->size();
1086 if (verticalScrollOrientation
) {
1087 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1089 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1091 m_layouter
->setSize(layouterSize
);
1095 if (!hasMultipleRanges
) {
1096 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1097 updateSiblingsInformation();
1102 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1105 if (hasMultipleRanges
) {
1106 m_endTransactionAnimationHint
= NoAnimation
;
1109 updateSiblingsInformation();
1112 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1113 // In case if items of the same group have been inserted before an item that
1114 // currently represents the first item of the group, the group header of
1115 // this item must be removed.
1116 updateVisibleGroupHeaders();
1119 if (useAlternateBackgrounds()) {
1120 updateAlternateBackgrounds();
1124 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1126 if (m_itemSize
.isEmpty()) {
1127 // Don't pass the item-range: The preferred column-widths of
1128 // all items must be adjusted when removing items.
1129 updatePreferredColumnWidths();
1132 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1133 if (hasMultipleRanges
) {
1137 m_layouter
->markAsDirty();
1139 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1141 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1142 const KItemRange
& range
= itemRanges
[i
];
1143 const int index
= range
.index
;
1144 const int count
= range
.count
;
1145 if (index
< 0 || count
<= 0) {
1146 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1150 const int firstRemovedIndex
= index
;
1151 const int lastRemovedIndex
= index
+ count
- 1;
1153 // Remember which items have to be moved because they are behind the removed range.
1154 QVector
<int> itemsToMove
;
1156 // Remove all KItemListWidget instances that got deleted
1157 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1158 const int i
= widget
->index();
1159 if (i
< firstRemovedIndex
) {
1161 } else if (i
> lastRemovedIndex
) {
1162 itemsToMove
.append(i
);
1166 m_animation
->stop(widget
);
1167 // Stopping the animation might lead to recycling the widget if
1168 // it is invisible (see slotAnimationFinished()).
1169 // Check again whether it is still visible:
1170 if (!m_visibleItems
.contains(i
)) {
1174 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1175 // Remove the widget without animation
1176 recycleWidget(widget
);
1178 // Animate the removing of the items. Special case: When removing an item there
1179 // is no valid model index available anymore. For the
1180 // remove-animation the item gets removed from m_visibleItems but the widget
1181 // will stay alive until the animation has been finished and will
1182 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1183 m_visibleItems
.remove(i
);
1184 widget
->setIndex(-1);
1185 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1189 // Update the indexes of all KItemListWidget instances that are located
1190 // after the deleted items. It is important to update them in ascending
1191 // order to prevent overlaps when setting the new index.
1192 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1193 foreach (int i
, itemsToMove
) {
1194 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1196 const int newIndex
= i
- count
;
1197 if (hasMultipleRanges
) {
1198 setWidgetIndex(widget
, newIndex
);
1200 // Try to animate the moving of the item
1201 moveWidgetToIndex(widget
, newIndex
);
1205 if (!hasMultipleRanges
) {
1206 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1207 // assumes an updated geometry. If items are removed during an active transaction,
1208 // the transaction will be temporary deactivated so that doLayout() triggers a
1209 // geometry update if necessary.
1210 const int activeTransactions
= m_activeTransactions
;
1211 m_activeTransactions
= 0;
1212 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1213 m_activeTransactions
= activeTransactions
;
1214 updateSiblingsInformation();
1219 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1222 if (hasMultipleRanges
) {
1223 m_endTransactionAnimationHint
= NoAnimation
;
1225 updateSiblingsInformation();
1228 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1229 // In case if the first item of a group has been removed, the group header
1230 // must be applied to the next visible item.
1231 updateVisibleGroupHeaders();
1234 if (useAlternateBackgrounds()) {
1235 updateAlternateBackgrounds();
1239 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1241 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1242 m_layouter
->markAsDirty();
1245 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1248 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1249 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1251 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1252 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1254 updateWidgetProperties(widget
, index
);
1255 initializeItemListWidget(widget
);
1259 doLayout(NoAnimation
);
1260 updateSiblingsInformation();
1263 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1264 const QSet
<QByteArray
>& roles
)
1266 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1267 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1268 updatePreferredColumnWidths(itemRanges
);
1271 foreach (const KItemRange
& itemRange
, itemRanges
) {
1272 const int index
= itemRange
.index
;
1273 const int count
= itemRange
.count
;
1275 if (updateSizeHints
) {
1276 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1277 m_layouter
->markAsDirty();
1279 if (!m_layoutTimer
->isActive()) {
1280 m_layoutTimer
->start();
1284 // Apply the changed roles to the visible item-widgets
1285 const int lastIndex
= index
+ count
- 1;
1286 for (int i
= index
; i
<= lastIndex
; ++i
) {
1287 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1289 widget
->setData(m_model
->data(i
), roles
);
1293 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1294 // The sort-role has been changed which might result
1295 // in modified group headers
1296 updateVisibleGroupHeaders();
1297 doLayout(NoAnimation
);
1300 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1301 ev
.setFirstRow(itemRange
.index
);
1302 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1303 QAccessible::updateAccessibility(&ev
);
1307 void KItemListView::slotGroupsChanged()
1309 updateVisibleGroupHeaders();
1310 doLayout(NoAnimation
);
1311 updateSiblingsInformation();
1314 void KItemListView::slotGroupedSortingChanged(bool current
)
1316 m_grouped
= current
;
1317 m_layouter
->markAsDirty();
1320 updateGroupHeaderHeight();
1322 // Clear all visible headers. Note that the QHashIterator takes a copy of
1323 // m_visibleGroups. Therefore, it remains valid even if items are removed
1324 // from m_visibleGroups in recycleGroupHeaderForWidget().
1325 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1326 while (it
.hasNext()) {
1328 recycleGroupHeaderForWidget(it
.key());
1330 Q_ASSERT(m_visibleGroups
.isEmpty());
1333 if (useAlternateBackgrounds()) {
1334 // Changing the group mode requires to update the alternate backgrounds
1335 // as with the enabled group mode the altering is done on base of the first
1337 updateAlternateBackgrounds();
1339 updateSiblingsInformation();
1340 doLayout(NoAnimation
);
1343 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1348 updateVisibleGroupHeaders();
1349 doLayout(NoAnimation
);
1353 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1358 updateVisibleGroupHeaders();
1359 doLayout(NoAnimation
);
1363 void KItemListView::slotCurrentChanged(int current
, int previous
)
1367 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1368 // always the selected item. It is not necessary to highlight the current item then.
1369 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1370 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1371 if (previousWidget
) {
1372 previousWidget
->setCurrent(false);
1375 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1376 if (currentWidget
) {
1377 currentWidget
->setCurrent(true);
1381 QAccessibleEvent
ev(this, QAccessible::Focus
);
1382 ev
.setChild(current
);
1383 QAccessible::updateAccessibility(&ev
);
1386 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1390 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1391 while (it
.hasNext()) {
1393 const int index
= it
.key();
1394 KItemListWidget
* widget
= it
.value();
1395 widget
->setSelected(current
.contains(index
));
1399 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1400 KItemListViewAnimation::AnimationType type
)
1402 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1403 Q_ASSERT(itemListWidget
);
1406 case KItemListViewAnimation::DeleteAnimation
: {
1407 // As we recycle the widget in this case it is important to assure that no
1408 // other animation has been started. This is a convention in KItemListView and
1409 // not a requirement defined by KItemListViewAnimation.
1410 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1412 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1413 // by m_visibleWidgets and must be deleted manually after the animation has
1415 recycleGroupHeaderForWidget(itemListWidget
);
1416 widgetCreator()->recycle(itemListWidget
);
1420 case KItemListViewAnimation::CreateAnimation
:
1421 case KItemListViewAnimation::MovingAnimation
:
1422 case KItemListViewAnimation::ResizeAnimation
: {
1423 const int index
= itemListWidget
->index();
1424 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1425 (index
> m_layouter
->lastVisibleIndex());
1426 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1427 recycleWidget(itemListWidget
);
1436 void KItemListView::slotLayoutTimerFinished()
1438 m_layouter
->setSize(geometry().size());
1439 doLayout(Animation
);
1442 void KItemListView::slotRubberBandPosChanged()
1447 void KItemListView::slotRubberBandActivationChanged(bool active
)
1450 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1451 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1452 m_skipAutoScrollForRubberBand
= true;
1454 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1455 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1456 m_skipAutoScrollForRubberBand
= false;
1462 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1464 qreal previousWidth
)
1467 Q_UNUSED(currentWidth
)
1468 Q_UNUSED(previousWidth
)
1470 m_headerWidget
->setAutomaticColumnResizing(false);
1471 applyColumnWidthsFromHeader();
1472 doLayout(NoAnimation
);
1475 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1479 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1481 const QList
<QByteArray
> previous
= m_visibleRoles
;
1483 QList
<QByteArray
> current
= m_visibleRoles
;
1484 current
.removeAt(previousIndex
);
1485 current
.insert(currentIndex
, role
);
1487 setVisibleRoles(current
);
1489 emit
visibleRolesChanged(current
, previous
);
1492 void KItemListView::triggerAutoScrolling()
1494 if (!m_autoScrollTimer
) {
1499 int visibleSize
= 0;
1500 if (scrollOrientation() == Qt::Vertical
) {
1501 pos
= m_mousePos
.y();
1502 visibleSize
= size().height();
1504 pos
= m_mousePos
.x();
1505 visibleSize
= size().width();
1508 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1509 m_autoScrollIncrement
= 0;
1512 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1513 if (m_autoScrollIncrement
== 0) {
1514 // The mouse position is not above an autoscroll margin (the autoscroll timer
1515 // will be restarted in mouseMoveEvent())
1516 m_autoScrollTimer
->stop();
1520 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1521 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1522 // if the direction of the rubberband is similar to the autoscroll direction. This
1523 // prevents that starting to create a rubberband within the autoscroll margins starts
1524 // an autoscrolling.
1526 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1527 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1528 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1529 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1530 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1531 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1532 // been moved up although the autoscroll direction might be down)
1533 m_autoScrollTimer
->stop();
1538 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1539 // the autoscrolling may not get skipped anymore until a new rubberband is created
1540 m_skipAutoScrollForRubberBand
= false;
1542 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1543 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1544 setScrollOffset(newScrollOffset
);
1546 // Trigger the autoscroll timer which will periodically call
1547 // triggerAutoScrolling()
1548 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1551 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1553 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1555 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1556 Q_ASSERT(groupHeader
);
1557 updateGroupHeaderLayout(widget
);
1560 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1562 disconnectRoleEditingSignals(index
);
1564 emit
roleEditingCanceled(index
, role
, value
);
1565 m_editingRole
= false;
1568 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1570 disconnectRoleEditingSignals(index
);
1572 emit
roleEditingFinished(index
, role
, value
);
1573 m_editingRole
= false;
1576 void KItemListView::setController(KItemListController
* controller
)
1578 if (m_controller
!= controller
) {
1579 KItemListController
* previous
= m_controller
;
1581 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1582 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1583 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1586 m_controller
= controller
;
1589 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1590 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1591 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1594 onControllerChanged(controller
, previous
);
1598 void KItemListView::setModel(KItemModelBase
* model
)
1600 if (m_model
== model
) {
1604 KItemModelBase
* previous
= m_model
;
1607 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1608 this, &KItemListView::slotItemsChanged
);
1609 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1610 this, &KItemListView::slotItemsInserted
);
1611 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1612 this, &KItemListView::slotItemsRemoved
);
1613 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1614 this, &KItemListView::slotItemsMoved
);
1615 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1616 this, &KItemListView::slotGroupsChanged
);
1617 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1618 this, &KItemListView::slotGroupedSortingChanged
);
1619 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1620 this, &KItemListView::slotSortOrderChanged
);
1621 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1622 this, &KItemListView::slotSortRoleChanged
);
1624 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1628 m_layouter
->setModel(model
);
1629 m_grouped
= model
->groupedSorting();
1632 connect(m_model
, &KItemModelBase::itemsChanged
,
1633 this, &KItemListView::slotItemsChanged
);
1634 connect(m_model
, &KItemModelBase::itemsInserted
,
1635 this, &KItemListView::slotItemsInserted
);
1636 connect(m_model
, &KItemModelBase::itemsRemoved
,
1637 this, &KItemListView::slotItemsRemoved
);
1638 connect(m_model
, &KItemModelBase::itemsMoved
,
1639 this, &KItemListView::slotItemsMoved
);
1640 connect(m_model
, &KItemModelBase::groupsChanged
,
1641 this, &KItemListView::slotGroupsChanged
);
1642 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1643 this, &KItemListView::slotGroupedSortingChanged
);
1644 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1645 this, &KItemListView::slotSortOrderChanged
);
1646 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1647 this, &KItemListView::slotSortRoleChanged
);
1649 const int itemCount
= m_model
->count();
1650 if (itemCount
> 0) {
1651 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1655 onModelChanged(model
, previous
);
1658 KItemListRubberBand
* KItemListView::rubberBand() const
1660 return m_rubberBand
;
1663 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1665 if (m_layoutTimer
->isActive()) {
1666 m_layoutTimer
->stop();
1669 if (m_activeTransactions
> 0) {
1670 if (hint
== NoAnimation
) {
1671 // As soon as at least one property change should be done without animation,
1672 // the whole transaction will be marked as not animated.
1673 m_endTransactionAnimationHint
= NoAnimation
;
1678 if (!m_model
|| m_model
->count() < 0) {
1682 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1683 if (firstVisibleIndex
< 0) {
1684 emitOffsetChanges();
1688 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1689 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1690 // is still shown if the maximum offset got decreased.
1691 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1692 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1693 if (scrollOffset() > maxOffsetToShowFullRange
) {
1694 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1695 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1698 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1700 int firstSibblingIndex
= -1;
1701 int lastSibblingIndex
= -1;
1702 const bool supportsExpanding
= supportsItemExpanding();
1704 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1706 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1707 // instances from invisible items are reused. If no reusable items are
1708 // found then new KItemListWidget instances get created.
1709 const bool animate
= (hint
== Animation
);
1710 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1711 bool applyNewPos
= true;
1712 bool wasHidden
= false;
1714 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1715 const QPointF newPos
= itemBounds
.topLeft();
1716 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1719 if (!reusableItems
.isEmpty()) {
1720 // Reuse a KItemListWidget instance from an invisible item
1721 const int oldIndex
= reusableItems
.takeLast();
1722 widget
= m_visibleItems
.value(oldIndex
);
1723 setWidgetIndex(widget
, i
);
1724 updateWidgetProperties(widget
, i
);
1725 initializeItemListWidget(widget
);
1727 // No reusable KItemListWidget instance is available, create a new one
1728 widget
= createWidget(i
);
1730 widget
->resize(itemBounds
.size());
1732 if (animate
&& changedCount
< 0) {
1733 // Items have been deleted.
1734 if (i
>= changedIndex
) {
1735 // The item is located behind the removed range. Move the
1736 // created item to the imaginary old position outside the
1737 // view. It will get animated to the new position later.
1738 const int previousIndex
= i
- changedCount
;
1739 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1740 if (itemRect
.isEmpty()) {
1741 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1742 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1743 widget
->setPos(invisibleOldPos
);
1745 widget
->setPos(itemRect
.topLeft());
1747 applyNewPos
= false;
1751 if (supportsExpanding
&& changedCount
== 0) {
1752 if (firstSibblingIndex
< 0) {
1753 firstSibblingIndex
= i
;
1755 lastSibblingIndex
= i
;
1760 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1761 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1762 applyNewPos
= false;
1765 const bool itemsRemoved
= (changedCount
< 0);
1766 const bool itemsInserted
= (changedCount
> 0);
1767 if (itemsRemoved
&& (i
>= changedIndex
)) {
1768 // The item is located after the removed items. Animate the moving of the position.
1769 applyNewPos
= !moveWidget(widget
, newPos
);
1770 } else if (itemsInserted
&& i
>= changedIndex
) {
1771 // The item is located after the first inserted item
1772 if (i
<= changedIndex
+ changedCount
- 1) {
1773 // The item is an inserted item. Animate the appearing of the item.
1774 // For performance reasons no animation is done when changedCount is equal
1775 // to all available items.
1776 if (changedCount
< m_model
->count()) {
1777 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1779 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1780 // The item was already there before, so animate the moving of the position.
1781 // No moving animation is done if the item is animated by a create animation: This
1782 // prevents a "move animation mess" when inserting several ranges in parallel.
1783 applyNewPos
= !moveWidget(widget
, newPos
);
1785 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1786 // The size of the view might have been changed. Animate the moving of the position.
1787 applyNewPos
= !moveWidget(widget
, newPos
);
1790 m_animation
->stop(widget
);
1794 widget
->setPos(newPos
);
1797 Q_ASSERT(widget
->index() == i
);
1798 widget
->setVisible(true);
1800 if (widget
->size() != itemBounds
.size()) {
1801 // Resize the widget for the item to the changed size.
1803 // If a dynamic item size is used then no animation is done in the direction
1804 // of the dynamic size.
1805 if (m_itemSize
.width() <= 0) {
1806 // The width is dynamic, apply the new width without animation.
1807 widget
->resize(itemBounds
.width(), widget
->size().height());
1808 } else if (m_itemSize
.height() <= 0) {
1809 // The height is dynamic, apply the new height without animation.
1810 widget
->resize(widget
->size().width(), itemBounds
.height());
1812 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1814 widget
->resize(itemBounds
.size());
1818 // Updating the cell-information must be done as last step: The decision whether the
1819 // moving-animation should be started at all is based on the previous cell-information.
1820 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1821 m_visibleCells
.insert(i
, cell
);
1824 // Delete invisible KItemListWidget instances that have not been reused
1825 foreach (int index
, reusableItems
) {
1826 recycleWidget(m_visibleItems
.value(index
));
1829 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1830 Q_ASSERT(lastSibblingIndex
>= 0);
1831 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1835 // Update the layout of all visible group headers
1836 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1837 while (it
.hasNext()) {
1839 updateGroupHeaderLayout(it
.key());
1843 emitOffsetChanges();
1846 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1847 int lastVisibleIndex
,
1848 LayoutAnimationHint hint
)
1850 // Determine all items that are completely invisible and might be
1851 // reused for items that just got (at least partly) visible. If the
1852 // animation hint is set to 'Animation' items that do e.g. an animated
1853 // moving of their position are not marked as invisible: This assures
1854 // that a scrolling inside the view can be done without breaking an animation.
1858 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1859 while (it
.hasNext()) {
1862 KItemListWidget
* widget
= it
.value();
1863 const int index
= widget
->index();
1864 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1867 if (m_animation
->isStarted(widget
)) {
1868 if (hint
== NoAnimation
) {
1869 // Stopping the animation will call KItemListView::slotAnimationFinished()
1870 // and the widget will be recycled if necessary there.
1871 m_animation
->stop(widget
);
1874 widget
->setVisible(false);
1875 items
.append(index
);
1878 recycleGroupHeaderForWidget(widget
);
1887 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1889 if (widget
->pos() == newPos
) {
1893 bool startMovingAnim
= false;
1895 if (m_itemSize
.isEmpty()) {
1896 // The items are not aligned in a grid but either as columns or rows.
1897 startMovingAnim
= true;
1899 // When having a grid the moving-animation should only be started, if it is done within
1900 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1901 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1902 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1903 const int index
= widget
->index();
1904 const Cell cell
= m_visibleCells
.value(index
);
1905 if (cell
.column
>= 0 && cell
.row
>= 0) {
1906 if (scrollOrientation() == Qt::Vertical
) {
1907 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1909 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1914 if (startMovingAnim
) {
1915 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1919 m_animation
->stop(widget
);
1920 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1924 void KItemListView::emitOffsetChanges()
1926 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1927 if (m_oldScrollOffset
!= newScrollOffset
) {
1928 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1929 m_oldScrollOffset
= newScrollOffset
;
1932 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1933 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1934 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1935 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1938 const qreal newItemOffset
= m_layouter
->itemOffset();
1939 if (m_oldItemOffset
!= newItemOffset
) {
1940 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1941 m_oldItemOffset
= newItemOffset
;
1944 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1945 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1946 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1947 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1951 KItemListWidget
* KItemListView::createWidget(int index
)
1953 KItemListWidget
* widget
= widgetCreator()->create(this);
1954 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1956 m_visibleItems
.insert(index
, widget
);
1957 m_visibleCells
.insert(index
, Cell());
1958 updateWidgetProperties(widget
, index
);
1959 initializeItemListWidget(widget
);
1963 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1966 recycleGroupHeaderForWidget(widget
);
1969 const int index
= widget
->index();
1970 m_visibleItems
.remove(index
);
1971 m_visibleCells
.remove(index
);
1973 widgetCreator()->recycle(widget
);
1976 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1978 const int oldIndex
= widget
->index();
1979 m_visibleItems
.remove(oldIndex
);
1980 m_visibleCells
.remove(oldIndex
);
1982 m_visibleItems
.insert(index
, widget
);
1983 m_visibleCells
.insert(index
, Cell());
1985 widget
->setIndex(index
);
1988 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1990 const int oldIndex
= widget
->index();
1991 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1993 setWidgetIndex(widget
, index
);
1995 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1996 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1997 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1998 (!vertical
&& oldCell
.column
== newCell
.column
);
2000 m_visibleCells
.insert(index
, newCell
);
2004 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
2007 case LayouterSize
: m_layouter
->setSize(size
); break;
2008 case ItemSize
: m_layouter
->setItemSize(size
); break;
2013 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2015 widget
->setVisibleRoles(m_visibleRoles
);
2016 updateWidgetColumnWidths(widget
);
2017 widget
->setStyleOption(m_styleOption
);
2019 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2021 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2022 // always the selected item. It is not necessary to highlight the current item then.
2023 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2024 widget
->setCurrent(index
== selectionManager
->currentItem());
2026 widget
->setSelected(selectionManager
->isSelected(index
));
2027 widget
->setHovered(false);
2028 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2029 widget
->setIndex(index
);
2030 widget
->setData(m_model
->data(index
));
2031 widget
->setSiblingsInformation(QBitArray());
2032 updateAlternateBackgroundForWidget(widget
);
2035 updateGroupHeaderForWidget(widget
);
2039 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2041 Q_ASSERT(m_grouped
);
2043 const int index
= widget
->index();
2044 if (!m_layouter
->isFirstGroupItem(index
)) {
2045 // The widget does not represent the first item of a group
2046 // and hence requires no header
2047 recycleGroupHeaderForWidget(widget
);
2051 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2052 if (groups
.isEmpty() || !groupHeaderCreator()) {
2056 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2058 groupHeader
= groupHeaderCreator()->create(this);
2059 groupHeader
->setParentItem(widget
);
2060 m_visibleGroups
.insert(widget
, groupHeader
);
2061 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2063 Q_ASSERT(groupHeader
->parentItem() == widget
);
2065 const int groupIndex
= groupIndexForItem(index
);
2066 Q_ASSERT(groupIndex
>= 0);
2067 groupHeader
->setData(groups
.at(groupIndex
).second
);
2068 groupHeader
->setRole(model()->sortRole());
2069 groupHeader
->setStyleOption(m_styleOption
);
2070 groupHeader
->setScrollOrientation(scrollOrientation());
2071 groupHeader
->setItemIndex(index
);
2073 groupHeader
->show();
2076 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2078 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2079 Q_ASSERT(groupHeader
);
2081 const int index
= widget
->index();
2082 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2083 const QRectF itemRect
= m_layouter
->itemRect(index
);
2085 // The group-header is a child of the itemlist widget. Translate the
2086 // group header position to the relative position.
2087 if (scrollOrientation() == Qt::Vertical
) {
2088 // In the vertical scroll orientation the group header should always span
2089 // the whole width no matter which temporary position the parent widget
2090 // has. In this case the x-position and width will be adjusted manually.
2091 const qreal x
= -widget
->x() - itemOffset();
2092 const qreal width
= maximumItemOffset();
2093 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2094 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2096 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2097 groupHeader
->resize(groupHeaderRect
.size());
2101 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2103 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2105 header
->setParentItem(nullptr);
2106 groupHeaderCreator()->recycle(header
);
2107 m_visibleGroups
.remove(widget
);
2108 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2112 void KItemListView::updateVisibleGroupHeaders()
2114 Q_ASSERT(m_grouped
);
2115 m_layouter
->markAsDirty();
2117 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2118 while (it
.hasNext()) {
2120 updateGroupHeaderForWidget(it
.value());
2124 int KItemListView::groupIndexForItem(int index
) const
2126 Q_ASSERT(m_grouped
);
2128 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2129 if (groups
.isEmpty()) {
2134 int max
= groups
.count() - 1;
2137 mid
= (min
+ max
) / 2;
2138 if (index
> groups
[mid
].first
) {
2143 } while (groups
[mid
].first
!= index
&& min
<= max
);
2146 while (groups
[mid
].first
> index
&& mid
> 0) {
2154 void KItemListView::updateAlternateBackgrounds()
2156 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2157 while (it
.hasNext()) {
2159 updateAlternateBackgroundForWidget(it
.value());
2163 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2165 bool enabled
= useAlternateBackgrounds();
2167 const int index
= widget
->index();
2168 enabled
= (index
& 0x1) > 0;
2170 const int groupIndex
= groupIndexForItem(index
);
2171 if (groupIndex
>= 0) {
2172 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2173 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2174 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2175 enabled
= (relativeIndex
& 0x1) > 0;
2179 widget
->setAlternateBackground(enabled
);
2182 bool KItemListView::useAlternateBackgrounds() const
2184 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2187 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2189 QElapsedTimer timer
;
2192 QHash
<QByteArray
, qreal
> widths
;
2194 // Calculate the minimum width for each column that is required
2195 // to show the headline unclipped.
2196 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2197 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2198 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2199 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2200 const QString headerText
= m_model
->roleDescription(visibleRole
);
2201 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2202 widths
.insert(visibleRole
, headerWidth
);
2205 // Calculate the preferred column withs for each item and ignore values
2206 // smaller than the width for showing the headline unclipped.
2207 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2208 int calculatedItemCount
= 0;
2209 bool maxTimeExceeded
= false;
2210 foreach (const KItemRange
& itemRange
, itemRanges
) {
2211 const int startIndex
= itemRange
.index
;
2212 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2214 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2215 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2216 qreal maxWidth
= widths
.value(visibleRole
, 0);
2217 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2218 maxWidth
= qMax(width
, maxWidth
);
2219 widths
.insert(visibleRole
, maxWidth
);
2222 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2223 // When having several thousands of items calculating the sizes can get
2224 // very expensive. We accept a possibly too small role-size in favour
2225 // of having no blocking user interface.
2226 maxTimeExceeded
= true;
2229 ++calculatedItemCount
;
2231 if (maxTimeExceeded
) {
2239 void KItemListView::applyColumnWidthsFromHeader()
2241 // Apply the new size to the layouter
2242 const qreal requiredWidth
= columnWidthsSum();
2243 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2244 m_itemSize
.height());
2245 m_layouter
->setItemSize(dynamicItemSize
);
2247 // Update the role sizes for all visible widgets
2248 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2249 while (it
.hasNext()) {
2251 updateWidgetColumnWidths(it
.value());
2255 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2257 foreach (const QByteArray
& role
, m_visibleRoles
) {
2258 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2262 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2264 Q_ASSERT(m_itemSize
.isEmpty());
2265 const int itemCount
= m_model
->count();
2266 int rangesItemCount
= 0;
2267 foreach (const KItemRange
& range
, itemRanges
) {
2268 rangesItemCount
+= range
.count
;
2271 if (itemCount
== rangesItemCount
) {
2272 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2273 foreach (const QByteArray
& role
, m_visibleRoles
) {
2274 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2277 // Only a sub range of the roles need to be determined.
2278 // The chances are good that the widths of the sub ranges
2279 // already fit into the available widths and hence no
2280 // expensive update might be required.
2281 bool changed
= false;
2283 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2284 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2285 while (it
.hasNext()) {
2287 const QByteArray
& role
= it
.key();
2288 const qreal updatedWidth
= it
.value();
2289 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2290 if (updatedWidth
> currentWidth
) {
2291 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2297 // All the updated sizes are smaller than the current sizes and no change
2298 // of the stretched roles-widths is required
2303 if (m_headerWidget
->automaticColumnResizing()) {
2304 applyAutomaticColumnWidths();
2308 void KItemListView::updatePreferredColumnWidths()
2311 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2315 void KItemListView::applyAutomaticColumnWidths()
2317 Q_ASSERT(m_itemSize
.isEmpty());
2318 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2319 if (m_visibleRoles
.isEmpty()) {
2323 // Calculate the maximum size of an item by considering the
2324 // visible role sizes and apply them to the layouter. If the
2325 // size does not use the available view-size the size of the
2326 // first role will get stretched.
2328 foreach (const QByteArray
& role
, m_visibleRoles
) {
2329 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2330 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2333 const QByteArray firstRole
= m_visibleRoles
.first();
2334 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2335 QSizeF dynamicItemSize
= m_itemSize
;
2337 qreal requiredWidth
= columnWidthsSum();
2338 const qreal availableWidth
= size().width();
2339 if (requiredWidth
< availableWidth
) {
2340 // Stretch the first column to use the whole remaining width
2341 firstColumnWidth
+= availableWidth
- requiredWidth
;
2342 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2343 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2344 // Shrink the first column to be able to show as much other
2345 // columns as possible
2346 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2348 // TODO: A proper calculation of the minimum width depends on the implementation
2349 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2351 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2352 if (shrinkedFirstColumnWidth
< minWidth
) {
2353 shrinkedFirstColumnWidth
= minWidth
;
2356 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2357 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2360 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2362 m_layouter
->setItemSize(dynamicItemSize
);
2364 // Update the role sizes for all visible widgets
2365 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2366 while (it
.hasNext()) {
2368 updateWidgetColumnWidths(it
.value());
2372 qreal
KItemListView::columnWidthsSum() const
2374 qreal widthsSum
= 0;
2375 foreach (const QByteArray
& role
, m_visibleRoles
) {
2376 widthsSum
+= m_headerWidget
->columnWidth(role
);
2381 QRectF
KItemListView::headerBoundaries() const
2383 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2386 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2387 const QSizeF
& newItemSize
,
2388 const QSizeF
& newItemMargin
) const
2390 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2394 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2395 const qreal itemWidth
= m_layouter
->itemSize().width();
2396 if (itemWidth
> 0) {
2397 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2398 newItemSize
.width(),
2399 newItemMargin
.width());
2400 if (m_model
->count() > newColumnCount
) {
2401 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2403 m_layouter
->itemMargin().width());
2404 return oldColumnCount
!= newColumnCount
;
2408 const qreal itemHeight
= m_layouter
->itemSize().height();
2409 if (itemHeight
> 0) {
2410 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2411 newItemSize
.height(),
2412 newItemMargin
.height());
2413 if (m_model
->count() > newRowCount
) {
2414 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2416 m_layouter
->itemMargin().height());
2417 return oldRowCount
!= newRowCount
;
2425 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2427 if (m_itemSize
.isEmpty()) {
2428 // We have only columns or only rows, but no grid: An animation is usually
2429 // welcome when inserting or removing items.
2430 return !supportsItemExpanding();
2433 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2437 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2438 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2439 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2440 // Only animate if up to 2/3 of a row or column are inserted or removed
2441 return changedItemCount
<= maximum
* 2 / 3;
2445 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2447 const QSizeF oldSize
= m_layouter
->size();
2449 m_layouter
->setSize(size
);
2450 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2451 m_layouter
->setSize(oldSize
);
2453 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2454 : maxOffset
> size
.width();
2457 int KItemListView::showDropIndicator(const QPointF
& pos
)
2459 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2460 while (it
.hasNext()) {
2462 const KItemListWidget
* widget
= it
.value();
2464 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2465 const QRectF rect
= itemRect(widget
->index());
2466 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2467 if (m_model
->supportsDropping(widget
->index())) {
2468 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2469 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2470 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2475 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2476 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2478 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2479 if (m_dropIndicator
!= draggingInsertIndicator
) {
2480 m_dropIndicator
= draggingInsertIndicator
;
2484 int index
= widget
->index();
2492 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2493 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2496 void KItemListView::hideDropIndicator()
2498 if (!m_dropIndicator
.isNull()) {
2499 m_dropIndicator
= QRectF();
2504 void KItemListView::updateGroupHeaderHeight()
2506 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2507 qreal groupHeaderMargin
= 0;
2509 if (scrollOrientation() == Qt::Horizontal
) {
2510 // The vertical margin above and below the header should be
2511 // equal to the horizontal margin, not the vertical margin
2512 // from m_styleOption.
2513 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2514 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2515 } else if (m_itemSize
.isEmpty()){
2516 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2517 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2519 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2520 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2522 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2523 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2525 updateVisibleGroupHeaders();
2528 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2530 if (!supportsItemExpanding() || !m_model
) {
2534 if (firstIndex
< 0 || lastIndex
< 0) {
2535 firstIndex
= m_layouter
->firstVisibleIndex();
2536 lastIndex
= m_layouter
->lastVisibleIndex();
2538 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2539 lastIndex
>= m_layouter
->firstVisibleIndex());
2540 if (!isRangeVisible
) {
2545 int previousParents
= 0;
2546 QBitArray previousSiblings
;
2548 // The rootIndex describes the first index where the siblings get
2549 // calculated from. For the calculation the upper most parent item
2550 // is required. For performance reasons it is checked first whether
2551 // the visible items before or after the current range already
2552 // contain a siblings information which can be used as base.
2553 int rootIndex
= firstIndex
;
2555 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2557 // There is no visible widget before the range, check whether there
2558 // is one after the range:
2559 widget
= m_visibleItems
.value(lastIndex
+ 1);
2561 // The sibling information of the widget may only be used if
2562 // all items of the range have the same number of parents.
2563 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2564 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2565 if (m_model
->expandedParentsCount(i
) != parents
) {
2574 // Performance optimization: Use the sibling information of the visible
2575 // widget beside the given range.
2576 previousSiblings
= widget
->siblingsInformation();
2577 if (previousSiblings
.isEmpty()) {
2580 previousParents
= previousSiblings
.count() - 1;
2581 previousSiblings
.truncate(previousParents
);
2583 // Potentially slow path: Go back to the upper most parent of firstIndex
2584 // to be able to calculate the initial value for the siblings.
2585 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2590 Q_ASSERT(previousParents
>= 0);
2591 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2592 // Update the parent-siblings in case if the current item represents
2593 // a child or an upper parent.
2594 const int currentParents
= m_model
->expandedParentsCount(i
);
2595 Q_ASSERT(currentParents
>= 0);
2596 if (previousParents
< currentParents
) {
2597 previousParents
= currentParents
;
2598 previousSiblings
.resize(currentParents
);
2599 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2600 } else if (previousParents
> currentParents
) {
2601 previousParents
= currentParents
;
2602 previousSiblings
.truncate(currentParents
);
2605 if (i
>= firstIndex
) {
2606 // The index represents a visible item. Apply the parent-siblings
2607 // and update the sibling of the current item.
2608 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2613 QBitArray siblings
= previousSiblings
;
2614 siblings
.resize(siblings
.count() + 1);
2615 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2617 widget
->setSiblingsInformation(siblings
);
2622 bool KItemListView::hasSiblingSuccessor(int index
) const
2624 bool hasSuccessor
= false;
2625 const int parentsCount
= m_model
->expandedParentsCount(index
);
2626 int successorIndex
= index
+ 1;
2628 // Search the next sibling
2629 const int itemCount
= m_model
->count();
2630 while (successorIndex
< itemCount
) {
2631 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2632 if (currentParentsCount
== parentsCount
) {
2633 hasSuccessor
= true;
2635 } else if (currentParentsCount
< parentsCount
) {
2641 if (m_grouped
&& hasSuccessor
) {
2642 // If the sibling is part of another group, don't mark it as
2643 // successor as the group header is between the sibling connections.
2644 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2645 if (m_layouter
->isFirstGroupItem(i
)) {
2646 hasSuccessor
= false;
2652 return hasSuccessor
;
2655 void KItemListView::disconnectRoleEditingSignals(int index
)
2657 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2662 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2663 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2664 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2667 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2671 const int minSpeed
= 4;
2672 const int maxSpeed
= 128;
2673 const int speedLimiter
= 96;
2674 const int autoScrollBorder
= 64;
2676 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2677 // This assures that the autoscrolling speed grows gradually.
2678 const int incLimiter
= 1;
2680 if (pos
< autoScrollBorder
) {
2681 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2682 inc
= qMax(inc
, -maxSpeed
);
2683 inc
= qMax(inc
, oldInc
- incLimiter
);
2684 } else if (pos
> range
- autoScrollBorder
) {
2685 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2686 inc
= qMin(inc
, maxSpeed
);
2687 inc
= qMin(inc
, oldInc
+ incLimiter
);
2693 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2695 const qreal availableSize
= size
- itemMargin
;
2696 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2702 KItemListCreatorBase::~KItemListCreatorBase()
2704 qDeleteAll(m_recycleableWidgets
);
2705 qDeleteAll(m_createdWidgets
);
2708 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2710 m_createdWidgets
.insert(widget
);
2713 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2715 Q_ASSERT(m_createdWidgets
.contains(widget
));
2716 m_createdWidgets
.remove(widget
);
2718 if (m_recycleableWidgets
.count() < 100) {
2719 m_recycleableWidgets
.append(widget
);
2720 widget
->setVisible(false);
2726 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2728 if (m_recycleableWidgets
.isEmpty()) {
2732 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2733 m_createdWidgets
.insert(widget
);
2737 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2741 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2743 widget
->setParentItem(nullptr);
2744 widget
->setOpacity(1.0);
2745 pushRecycleableWidget(widget
);
2748 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2752 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2754 header
->setOpacity(1.0);
2755 pushRecycleableWidget(header
);