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 <QStyleOptionRubberBand>
32 // Time in ms until reaching the autoscroll margin triggers
33 // an initial autoscrolling
34 const int InitialAutoScrollDelay
= 700;
36 // Delay in ms for triggering the next autoscroll
37 const int RepeatingAutoScrollDelay
= 1000 / 60;
40 #ifndef QT_NO_ACCESSIBILITY
41 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
45 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
46 return new KItemListContainerAccessible(container
);
47 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
48 return new KItemListViewAccessible(view
);
55 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
56 QGraphicsWidget(parent
),
57 m_enabledSelectionToggles(false),
59 m_supportsItemExpanding(false),
61 m_activeTransactions(0),
62 m_endTransactionAnimationHint(Animation
),
64 m_controller(nullptr),
67 m_widgetCreator(nullptr),
68 m_groupHeaderCreator(nullptr),
73 m_sizeHintResolver(nullptr),
76 m_layoutTimer(nullptr),
78 m_oldMaximumScrollOffset(0),
80 m_oldMaximumItemOffset(0),
81 m_skipAutoScrollForRubberBand(false),
82 m_rubberBand(nullptr),
84 m_autoScrollIncrement(0),
85 m_autoScrollTimer(nullptr),
87 m_headerWidget(nullptr),
90 setAcceptHoverEvents(true);
92 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
94 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
96 m_animation
= new KItemListViewAnimation(this);
97 connect(m_animation
, &KItemListViewAnimation::finished
,
98 this, &KItemListView::slotAnimationFinished
);
100 m_layoutTimer
= new QTimer(this);
101 m_layoutTimer
->setInterval(300);
102 m_layoutTimer
->setSingleShot(true);
103 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
105 m_rubberBand
= new KItemListRubberBand(this);
106 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
108 m_headerWidget
= new KItemListHeaderWidget(this);
109 m_headerWidget
->setVisible(false);
111 m_header
= new KItemListHeader(this);
113 #ifndef QT_NO_ACCESSIBILITY
114 QAccessible::installFactory(accessibleInterfaceFactory
);
119 KItemListView::~KItemListView()
121 // The group headers are children of the widgets created by
122 // widgetCreator(). So it is mandatory to delete the group headers
124 delete m_groupHeaderCreator
;
125 m_groupHeaderCreator
= nullptr;
127 delete m_widgetCreator
;
128 m_widgetCreator
= nullptr;
130 delete m_sizeHintResolver
;
131 m_sizeHintResolver
= nullptr;
134 void KItemListView::setScrollOffset(qreal offset
)
140 const qreal previousOffset
= m_layouter
->scrollOffset();
141 if (offset
== previousOffset
) {
145 m_layouter
->setScrollOffset(offset
);
146 m_animation
->setScrollOffset(offset
);
148 // Don't check whether the m_layoutTimer is active: Changing the
149 // scroll offset must always trigger a synchronous layout, otherwise
150 // the smooth-scrolling might get jerky.
151 doLayout(NoAnimation
);
152 onScrollOffsetChanged(offset
, previousOffset
);
155 qreal
KItemListView::scrollOffset() const
157 return m_layouter
->scrollOffset();
160 qreal
KItemListView::maximumScrollOffset() const
162 return m_layouter
->maximumScrollOffset();
165 void KItemListView::setItemOffset(qreal offset
)
167 if (m_layouter
->itemOffset() == offset
) {
171 m_layouter
->setItemOffset(offset
);
172 if (m_headerWidget
->isVisible()) {
173 m_headerWidget
->setOffset(offset
);
176 // Don't check whether the m_layoutTimer is active: Changing the
177 // item offset must always trigger a synchronous layout, otherwise
178 // the smooth-scrolling might get jerky.
179 doLayout(NoAnimation
);
182 qreal
KItemListView::itemOffset() const
184 return m_layouter
->itemOffset();
187 qreal
KItemListView::maximumItemOffset() const
189 return m_layouter
->maximumItemOffset();
192 int KItemListView::maximumVisibleItems() const
194 return m_layouter
->maximumVisibleItems();
197 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
199 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
200 m_visibleRoles
= roles
;
201 onVisibleRolesChanged(roles
, previousRoles
);
203 m_sizeHintResolver
->clearCache();
204 m_layouter
->markAsDirty();
206 if (m_itemSize
.isEmpty()) {
207 m_headerWidget
->setColumns(roles
);
208 updatePreferredColumnWidths();
209 if (!m_headerWidget
->automaticColumnResizing()) {
210 // The column-width of new roles are still 0. Apply the preferred
211 // column-width as default with.
212 foreach (const QByteArray
& role
, m_visibleRoles
) {
213 if (m_headerWidget
->columnWidth(role
) == 0) {
214 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
215 m_headerWidget
->setColumnWidth(role
, width
);
219 applyColumnWidthsFromHeader();
223 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
224 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
225 (roles
.count() <= 1 && previousRoles
.count() > 1));
227 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
228 while (it
.hasNext()) {
230 KItemListWidget
* widget
= it
.value();
231 widget
->setVisibleRoles(roles
);
232 if (alternateBackgroundsChanged
) {
233 updateAlternateBackgroundForWidget(widget
);
237 doLayout(NoAnimation
);
240 QList
<QByteArray
> KItemListView::visibleRoles() const
242 return m_visibleRoles
;
245 void KItemListView::setAutoScroll(bool enabled
)
247 if (enabled
&& !m_autoScrollTimer
) {
248 m_autoScrollTimer
= new QTimer(this);
249 m_autoScrollTimer
->setSingleShot(true);
250 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
251 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
252 } else if (!enabled
&& m_autoScrollTimer
) {
253 delete m_autoScrollTimer
;
254 m_autoScrollTimer
= nullptr;
258 bool KItemListView::autoScroll() const
260 return m_autoScrollTimer
!= nullptr;
263 void KItemListView::setEnabledSelectionToggles(bool enabled
)
265 if (m_enabledSelectionToggles
!= enabled
) {
266 m_enabledSelectionToggles
= enabled
;
268 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
269 while (it
.hasNext()) {
271 it
.value()->setEnabledSelectionToggle(enabled
);
276 bool KItemListView::enabledSelectionToggles() const
278 return m_enabledSelectionToggles
;
281 KItemListController
* KItemListView::controller() const
286 KItemModelBase
* KItemListView::model() const
291 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
293 delete m_widgetCreator
;
294 m_widgetCreator
= widgetCreator
;
297 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
299 if (!m_widgetCreator
) {
300 m_widgetCreator
= defaultWidgetCreator();
302 return m_widgetCreator
;
305 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
307 delete m_groupHeaderCreator
;
308 m_groupHeaderCreator
= groupHeaderCreator
;
311 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
313 if (!m_groupHeaderCreator
) {
314 m_groupHeaderCreator
= defaultGroupHeaderCreator();
316 return m_groupHeaderCreator
;
319 QSizeF
KItemListView::itemSize() const
324 const KItemListStyleOption
& KItemListView::styleOption() const
326 return m_styleOption
;
329 void KItemListView::setGeometry(const QRectF
& rect
)
331 QGraphicsWidget::setGeometry(rect
);
337 const QSizeF newSize
= rect
.size();
338 if (m_itemSize
.isEmpty()) {
339 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
340 if (m_headerWidget
->automaticColumnResizing()) {
341 applyAutomaticColumnWidths();
343 const qreal requiredWidth
= columnWidthsSum();
344 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
345 m_itemSize
.height());
346 m_layouter
->setItemSize(dynamicItemSize
);
349 // Triggering a synchronous layout is fine from a performance point of view,
350 // as with dynamic item sizes no moving animation must be done.
351 m_layouter
->setSize(newSize
);
352 doLayout(NoAnimation
);
354 const bool animate
= !changesItemGridLayout(newSize
,
355 m_layouter
->itemSize(),
356 m_layouter
->itemMargin());
357 m_layouter
->setSize(newSize
);
360 // Trigger an asynchronous relayout with m_layoutTimer to prevent
361 // performance bottlenecks. If the timer is exceeded, an animated layout
362 // will be triggered.
363 if (!m_layoutTimer
->isActive()) {
364 m_layoutTimer
->start();
367 m_layoutTimer
->stop();
368 doLayout(NoAnimation
);
373 qreal
KItemListView::verticalPageStep() const
375 qreal headerHeight
= 0;
376 if (m_headerWidget
->isVisible()) {
377 headerHeight
= m_headerWidget
->size().height();
379 return size().height() - headerHeight
;
382 int KItemListView::itemAt(const QPointF
& pos
) const
384 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
385 while (it
.hasNext()) {
388 const KItemListWidget
* widget
= it
.value();
389 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
390 if (widget
->contains(mappedPos
)) {
398 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
400 if (!m_enabledSelectionToggles
) {
404 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
406 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
407 if (!selectionToggleRect
.isEmpty()) {
408 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
409 return selectionToggleRect
.contains(mappedPos
);
415 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
417 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
419 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
420 if (!expansionToggleRect
.isEmpty()) {
421 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
422 return expansionToggleRect
.contains(mappedPos
);
428 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
430 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
432 const QRectF
&textRect
= widget
->textRect();
433 if (!textRect
.isEmpty()) {
434 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
435 return textRect
.contains(mappedPos
);
441 int KItemListView::firstVisibleIndex() const
443 return m_layouter
->firstVisibleIndex();
446 int KItemListView::lastVisibleIndex() const
448 return m_layouter
->lastVisibleIndex();
451 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
453 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
456 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
458 if (m_supportsItemExpanding
!= supportsExpanding
) {
459 m_supportsItemExpanding
= supportsExpanding
;
460 updateSiblingsInformation();
461 onSupportsItemExpandingChanged(supportsExpanding
);
465 bool KItemListView::supportsItemExpanding() const
467 return m_supportsItemExpanding
;
470 QRectF
KItemListView::itemRect(int index
) const
472 return m_layouter
->itemRect(index
);
475 QRectF
KItemListView::itemContextRect(int index
) const
479 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
481 contextRect
= widget
->iconRect() | widget
->textRect();
482 contextRect
.translate(itemRect(index
).topLeft());
488 void KItemListView::scrollToItem(int index
)
490 QRectF viewGeometry
= geometry();
491 if (m_headerWidget
->isVisible()) {
492 const qreal headerHeight
= m_headerWidget
->size().height();
493 viewGeometry
.adjust(0, headerHeight
, 0, 0);
495 QRectF currentRect
= itemRect(index
);
497 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
498 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
499 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
501 if (!viewGeometry
.contains(currentRect
)) {
502 qreal newOffset
= scrollOffset();
503 if (scrollOrientation() == Qt::Vertical
) {
504 if (currentRect
.top() < viewGeometry
.top()) {
505 newOffset
+= currentRect
.top() - viewGeometry
.top();
506 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
507 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
510 if (currentRect
.left() < viewGeometry
.left()) {
511 newOffset
+= currentRect
.left() - viewGeometry
.left();
512 } else if (currentRect
.right() > viewGeometry
.right()) {
513 newOffset
+= currentRect
.right() - viewGeometry
.right();
517 if (newOffset
!= scrollOffset()) {
518 emit
scrollTo(newOffset
);
523 void KItemListView::beginTransaction()
525 ++m_activeTransactions
;
526 if (m_activeTransactions
== 1) {
527 onTransactionBegin();
531 void KItemListView::endTransaction()
533 --m_activeTransactions
;
534 if (m_activeTransactions
< 0) {
535 m_activeTransactions
= 0;
536 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
539 if (m_activeTransactions
== 0) {
541 doLayout(m_endTransactionAnimationHint
);
542 m_endTransactionAnimationHint
= Animation
;
546 bool KItemListView::isTransactionActive() const
548 return m_activeTransactions
> 0;
551 void KItemListView::setHeaderVisible(bool visible
)
553 if (visible
&& !m_headerWidget
->isVisible()) {
554 QStyleOptionHeader option
;
555 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
558 m_headerWidget
->setPos(0, 0);
559 m_headerWidget
->resize(size().width(), headerSize
.height());
560 m_headerWidget
->setModel(m_model
);
561 m_headerWidget
->setColumns(m_visibleRoles
);
562 m_headerWidget
->setZValue(1);
564 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
565 this, &KItemListView::slotHeaderColumnWidthChanged
);
566 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
567 this, &KItemListView::slotHeaderColumnMoved
);
568 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
569 this, &KItemListView::sortOrderChanged
);
570 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
571 this, &KItemListView::sortRoleChanged
);
573 m_layouter
->setHeaderHeight(headerSize
.height());
574 m_headerWidget
->setVisible(true);
575 } else if (!visible
&& m_headerWidget
->isVisible()) {
576 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
577 this, &KItemListView::slotHeaderColumnWidthChanged
);
578 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
579 this, &KItemListView::slotHeaderColumnMoved
);
580 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
581 this, &KItemListView::sortOrderChanged
);
582 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
583 this, &KItemListView::sortRoleChanged
);
585 m_layouter
->setHeaderHeight(0);
586 m_headerWidget
->setVisible(false);
590 bool KItemListView::isHeaderVisible() const
592 return m_headerWidget
->isVisible();
595 KItemListHeader
* KItemListView::header() const
600 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
604 if (indexes
.count() == 1) {
605 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
606 QGraphicsView
* graphicsView
= scene()->views()[0];
607 if (item
&& graphicsView
) {
608 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
611 // TODO: Not implemented yet. Probably extend the interface
612 // from KItemListWidget::createDragPixmap() to return a pixmap
613 // that can be used for multiple indexes.
619 void KItemListView::editRole(int index
, const QByteArray
& role
)
621 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
622 if (!widget
|| m_editingRole
) {
626 m_editingRole
= true;
627 widget
->setEditedRole(role
);
629 connect(widget
, &KItemListWidget::roleEditingCanceled
,
630 this, &KItemListView::slotRoleEditingCanceled
);
631 connect(widget
, &KItemListWidget::roleEditingFinished
,
632 this, &KItemListView::slotRoleEditingFinished
);
634 connect(this, &KItemListView::scrollOffsetChanged
,
635 widget
, &KStandardItemListWidget::finishRoleEditing
);
638 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
640 QGraphicsWidget::paint(painter
, option
, widget
);
642 if (m_rubberBand
->isActive()) {
643 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
644 m_rubberBand
->endPosition()).normalized();
646 const QPointF topLeft
= rubberBandRect
.topLeft();
647 if (scrollOrientation() == Qt::Vertical
) {
648 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
650 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
653 QStyleOptionRubberBand opt
;
654 initStyleOption(&opt
);
655 opt
.shape
= QRubberBand::Rectangle
;
657 opt
.rect
= rubberBandRect
.toRect();
658 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
661 if (!m_dropIndicator
.isEmpty()) {
662 const QRectF r
= m_dropIndicator
.toRect();
664 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
665 painter
->setPen(color
);
667 // TODO: The following implementation works only for a vertical scroll-orientation
668 // and assumes a height of the m_draggingInsertIndicator of 1.
669 Q_ASSERT(r
.height() == 1);
670 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
673 painter
->setPen(color
);
674 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
678 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
680 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
681 if (!scene()->views().isEmpty()) {
682 m_styleOption
.palette
= scene()->views().at(0)->palette();
685 return QGraphicsItem::itemChange(change
, value
);
688 void KItemListView::setItemSize(const QSizeF
& size
)
690 const QSizeF previousSize
= m_itemSize
;
691 if (size
== previousSize
) {
695 // Skip animations when the number of rows or columns
696 // are changed in the grid layout. Although the animation
697 // engine can handle this usecase, it looks obtrusive.
698 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
700 m_layouter
->itemMargin());
702 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
703 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
704 (!m_itemSize
.isEmpty() && size
.isEmpty()));
708 if (alternateBackgroundsChanged
) {
709 // For an empty item size alternate backgrounds are drawn if more than
710 // one role is shown. Assure that the backgrounds for visible items are
711 // updated when changing the size in this context.
712 updateAlternateBackgrounds();
715 if (size
.isEmpty()) {
716 if (m_headerWidget
->automaticColumnResizing()) {
717 updatePreferredColumnWidths();
719 // Only apply the changed height and respect the header widths
721 const qreal currentWidth
= m_layouter
->itemSize().width();
722 const QSizeF
newSize(currentWidth
, size
.height());
723 m_layouter
->setItemSize(newSize
);
726 m_layouter
->setItemSize(size
);
729 m_sizeHintResolver
->clearCache();
730 doLayout(animate
? Animation
: NoAnimation
);
731 onItemSizeChanged(size
, previousSize
);
734 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
736 if (m_styleOption
== option
) {
740 const KItemListStyleOption previousOption
= m_styleOption
;
741 m_styleOption
= option
;
744 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
745 if (margin
!= m_layouter
->itemMargin()) {
746 // Skip animations when the number of rows or columns
747 // are changed in the grid layout. Although the animation
748 // engine can handle this usecase, it looks obtrusive.
749 animate
= !changesItemGridLayout(m_layouter
->size(),
750 m_layouter
->itemSize(),
752 m_layouter
->setItemMargin(margin
);
756 updateGroupHeaderHeight();
760 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
761 // Animating a change of the maximum text size just results in expensive
762 // temporary eliding and clipping operations and does not look good visually.
766 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
767 while (it
.hasNext()) {
769 it
.value()->setStyleOption(option
);
772 m_sizeHintResolver
->clearCache();
773 m_layouter
->markAsDirty();
774 doLayout(animate
? Animation
: NoAnimation
);
776 if (m_itemSize
.isEmpty()) {
777 updatePreferredColumnWidths();
780 onStyleOptionChanged(option
, previousOption
);
783 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
785 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
786 if (orientation
== previousOrientation
) {
790 m_layouter
->setScrollOrientation(orientation
);
791 m_animation
->setScrollOrientation(orientation
);
792 m_sizeHintResolver
->clearCache();
795 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
796 while (it
.hasNext()) {
798 it
.value()->setScrollOrientation(orientation
);
800 updateGroupHeaderHeight();
804 doLayout(NoAnimation
);
806 onScrollOrientationChanged(orientation
, previousOrientation
);
807 emit
scrollOrientationChanged(orientation
, previousOrientation
);
810 Qt::Orientation
KItemListView::scrollOrientation() const
812 return m_layouter
->scrollOrientation();
815 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
820 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
825 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
830 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
832 Q_UNUSED(changedRoles
)
836 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
842 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
848 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
854 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
860 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
866 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
872 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
878 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
880 Q_UNUSED(supportsExpanding
)
883 void KItemListView::onTransactionBegin()
887 void KItemListView::onTransactionEnd()
891 bool KItemListView::event(QEvent
* event
)
893 switch (event
->type()) {
894 case QEvent::PaletteChange
:
898 case QEvent::FontChange
:
903 // Forward all other events to the controller and handle them there
904 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
910 return QGraphicsWidget::event(event
);
913 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
915 m_mousePos
= transform().map(event
->pos());
919 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
921 QGraphicsWidget::mouseMoveEvent(event
);
923 m_mousePos
= transform().map(event
->pos());
924 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
925 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
929 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
931 event
->setAccepted(true);
935 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
937 QGraphicsWidget::dragMoveEvent(event
);
939 m_mousePos
= transform().map(event
->pos());
940 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
941 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
945 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
947 QGraphicsWidget::dragLeaveEvent(event
);
948 setAutoScroll(false);
951 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
953 QGraphicsWidget::dropEvent(event
);
954 setAutoScroll(false);
957 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
959 return m_visibleItems
.values();
962 void KItemListView::updateFont()
964 if (scene() && !scene()->views().isEmpty()) {
965 KItemListStyleOption option
= styleOption();
966 option
.font
= scene()->views().first()->font();
967 option
.fontMetrics
= QFontMetrics(option
.font
);
969 setStyleOption(option
);
973 void KItemListView::updatePalette()
975 if (scene() && !scene()->views().isEmpty()) {
976 KItemListStyleOption option
= styleOption();
977 option
.palette
= scene()->views().first()->palette();
979 setStyleOption(option
);
983 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
985 if (m_itemSize
.isEmpty()) {
986 updatePreferredColumnWidths(itemRanges
);
989 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
990 if (hasMultipleRanges
) {
994 m_layouter
->markAsDirty();
996 m_sizeHintResolver
->itemsInserted(itemRanges
);
998 int previouslyInsertedCount
= 0;
999 foreach (const KItemRange
& range
, itemRanges
) {
1000 // range.index is related to the model before anything has been inserted.
1001 // As in each loop the current item-range gets inserted the index must
1002 // be increased by the already previously inserted items.
1003 const int index
= range
.index
+ previouslyInsertedCount
;
1004 const int count
= range
.count
;
1005 if (index
< 0 || count
<= 0) {
1006 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1009 previouslyInsertedCount
+= count
;
1011 // Determine which visible items must be moved
1012 QList
<int> itemsToMove
;
1013 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1014 while (it
.hasNext()) {
1016 const int visibleItemIndex
= it
.key();
1017 if (visibleItemIndex
>= index
) {
1018 itemsToMove
.append(visibleItemIndex
);
1022 // Update the indexes of all KItemListWidget instances that are located
1023 // after the inserted items. It is important to adjust the indexes in the order
1024 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1025 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1026 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1027 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1029 const int newIndex
= widget
->index() + count
;
1030 if (hasMultipleRanges
) {
1031 setWidgetIndex(widget
, newIndex
);
1033 // Try to animate the moving of the item
1034 moveWidgetToIndex(widget
, newIndex
);
1038 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1039 // Check whether a scrollbar is required to show the inserted items. In this case
1040 // the size of the layouter will be decreased before calling doLayout(): This prevents
1041 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1042 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1043 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1044 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1045 if (decreaseLayouterSize
) {
1046 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1048 int scrollbarSpacing
= 0;
1049 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1050 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1053 QSizeF layouterSize
= m_layouter
->size();
1054 if (verticalScrollOrientation
) {
1055 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1057 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1059 m_layouter
->setSize(layouterSize
);
1063 if (!hasMultipleRanges
) {
1064 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1065 updateSiblingsInformation();
1070 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1073 if (hasMultipleRanges
) {
1074 m_endTransactionAnimationHint
= NoAnimation
;
1077 updateSiblingsInformation();
1080 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1081 // In case if items of the same group have been inserted before an item that
1082 // currently represents the first item of the group, the group header of
1083 // this item must be removed.
1084 updateVisibleGroupHeaders();
1087 if (useAlternateBackgrounds()) {
1088 updateAlternateBackgrounds();
1092 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1094 if (m_itemSize
.isEmpty()) {
1095 // Don't pass the item-range: The preferred column-widths of
1096 // all items must be adjusted when removing items.
1097 updatePreferredColumnWidths();
1100 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1101 if (hasMultipleRanges
) {
1105 m_layouter
->markAsDirty();
1107 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1109 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1110 const KItemRange
& range
= itemRanges
[i
];
1111 const int index
= range
.index
;
1112 const int count
= range
.count
;
1113 if (index
< 0 || count
<= 0) {
1114 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1118 const int firstRemovedIndex
= index
;
1119 const int lastRemovedIndex
= index
+ count
- 1;
1121 // Remember which items have to be moved because they are behind the removed range.
1122 QVector
<int> itemsToMove
;
1124 // Remove all KItemListWidget instances that got deleted
1125 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1126 const int i
= widget
->index();
1127 if (i
< firstRemovedIndex
) {
1129 } else if (i
> lastRemovedIndex
) {
1130 itemsToMove
.append(i
);
1134 m_animation
->stop(widget
);
1135 // Stopping the animation might lead to recycling the widget if
1136 // it is invisible (see slotAnimationFinished()).
1137 // Check again whether it is still visible:
1138 if (!m_visibleItems
.contains(i
)) {
1142 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1143 // Remove the widget without animation
1144 recycleWidget(widget
);
1146 // Animate the removing of the items. Special case: When removing an item there
1147 // is no valid model index available anymore. For the
1148 // remove-animation the item gets removed from m_visibleItems but the widget
1149 // will stay alive until the animation has been finished and will
1150 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1151 m_visibleItems
.remove(i
);
1152 widget
->setIndex(-1);
1153 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1157 // Update the indexes of all KItemListWidget instances that are located
1158 // after the deleted items. It is important to update them in ascending
1159 // order to prevent overlaps when setting the new index.
1160 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1161 foreach (int i
, itemsToMove
) {
1162 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1164 const int newIndex
= i
- count
;
1165 if (hasMultipleRanges
) {
1166 setWidgetIndex(widget
, newIndex
);
1168 // Try to animate the moving of the item
1169 moveWidgetToIndex(widget
, newIndex
);
1173 if (!hasMultipleRanges
) {
1174 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1175 // assumes an updated geometry. If items are removed during an active transaction,
1176 // the transaction will be temporary deactivated so that doLayout() triggers a
1177 // geometry update if necessary.
1178 const int activeTransactions
= m_activeTransactions
;
1179 m_activeTransactions
= 0;
1180 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1181 m_activeTransactions
= activeTransactions
;
1182 updateSiblingsInformation();
1187 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1190 if (hasMultipleRanges
) {
1191 m_endTransactionAnimationHint
= NoAnimation
;
1193 updateSiblingsInformation();
1196 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1197 // In case if the first item of a group has been removed, the group header
1198 // must be applied to the next visible item.
1199 updateVisibleGroupHeaders();
1202 if (useAlternateBackgrounds()) {
1203 updateAlternateBackgrounds();
1207 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1209 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1210 m_layouter
->markAsDirty();
1213 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1216 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1217 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1219 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1220 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1222 updateWidgetProperties(widget
, index
);
1223 initializeItemListWidget(widget
);
1227 doLayout(NoAnimation
);
1228 updateSiblingsInformation();
1231 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1232 const QSet
<QByteArray
>& roles
)
1234 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1235 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1236 updatePreferredColumnWidths(itemRanges
);
1239 foreach (const KItemRange
& itemRange
, itemRanges
) {
1240 const int index
= itemRange
.index
;
1241 const int count
= itemRange
.count
;
1243 if (updateSizeHints
) {
1244 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1245 m_layouter
->markAsDirty();
1247 if (!m_layoutTimer
->isActive()) {
1248 m_layoutTimer
->start();
1252 // Apply the changed roles to the visible item-widgets
1253 const int lastIndex
= index
+ count
- 1;
1254 for (int i
= index
; i
<= lastIndex
; ++i
) {
1255 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1257 widget
->setData(m_model
->data(i
), roles
);
1261 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1262 // The sort-role has been changed which might result
1263 // in modified group headers
1264 updateVisibleGroupHeaders();
1265 doLayout(NoAnimation
);
1268 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1269 ev
.setFirstRow(itemRange
.index
);
1270 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1271 QAccessible::updateAccessibility(&ev
);
1275 void KItemListView::slotGroupsChanged()
1277 updateVisibleGroupHeaders();
1278 doLayout(NoAnimation
);
1279 updateSiblingsInformation();
1282 void KItemListView::slotGroupedSortingChanged(bool current
)
1284 m_grouped
= current
;
1285 m_layouter
->markAsDirty();
1288 updateGroupHeaderHeight();
1290 // Clear all visible headers. Note that the QHashIterator takes a copy of
1291 // m_visibleGroups. Therefore, it remains valid even if items are removed
1292 // from m_visibleGroups in recycleGroupHeaderForWidget().
1293 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1294 while (it
.hasNext()) {
1296 recycleGroupHeaderForWidget(it
.key());
1298 Q_ASSERT(m_visibleGroups
.isEmpty());
1301 if (useAlternateBackgrounds()) {
1302 // Changing the group mode requires to update the alternate backgrounds
1303 // as with the enabled group mode the altering is done on base of the first
1305 updateAlternateBackgrounds();
1307 updateSiblingsInformation();
1308 doLayout(NoAnimation
);
1311 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1316 updateVisibleGroupHeaders();
1317 doLayout(NoAnimation
);
1321 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1326 updateVisibleGroupHeaders();
1327 doLayout(NoAnimation
);
1331 void KItemListView::slotCurrentChanged(int current
, int previous
)
1335 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1336 // always the selected item. It is not necessary to highlight the current item then.
1337 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1338 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1339 if (previousWidget
) {
1340 previousWidget
->setCurrent(false);
1343 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1344 if (currentWidget
) {
1345 currentWidget
->setCurrent(true);
1349 QAccessibleEvent
ev(this, QAccessible::Focus
);
1350 ev
.setChild(current
);
1351 QAccessible::updateAccessibility(&ev
);
1354 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1358 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1359 while (it
.hasNext()) {
1361 const int index
= it
.key();
1362 KItemListWidget
* widget
= it
.value();
1363 widget
->setSelected(current
.contains(index
));
1367 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1368 KItemListViewAnimation::AnimationType type
)
1370 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1371 Q_ASSERT(itemListWidget
);
1374 case KItemListViewAnimation::DeleteAnimation
: {
1375 // As we recycle the widget in this case it is important to assure that no
1376 // other animation has been started. This is a convention in KItemListView and
1377 // not a requirement defined by KItemListViewAnimation.
1378 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1380 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1381 // by m_visibleWidgets and must be deleted manually after the animation has
1383 recycleGroupHeaderForWidget(itemListWidget
);
1384 widgetCreator()->recycle(itemListWidget
);
1388 case KItemListViewAnimation::CreateAnimation
:
1389 case KItemListViewAnimation::MovingAnimation
:
1390 case KItemListViewAnimation::ResizeAnimation
: {
1391 const int index
= itemListWidget
->index();
1392 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1393 (index
> m_layouter
->lastVisibleIndex());
1394 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1395 recycleWidget(itemListWidget
);
1404 void KItemListView::slotLayoutTimerFinished()
1406 m_layouter
->setSize(geometry().size());
1407 doLayout(Animation
);
1410 void KItemListView::slotRubberBandPosChanged()
1415 void KItemListView::slotRubberBandActivationChanged(bool active
)
1418 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1419 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1420 m_skipAutoScrollForRubberBand
= true;
1422 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1423 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1424 m_skipAutoScrollForRubberBand
= false;
1430 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1432 qreal previousWidth
)
1435 Q_UNUSED(currentWidth
)
1436 Q_UNUSED(previousWidth
)
1438 m_headerWidget
->setAutomaticColumnResizing(false);
1439 applyColumnWidthsFromHeader();
1440 doLayout(NoAnimation
);
1443 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1447 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1449 const QList
<QByteArray
> previous
= m_visibleRoles
;
1451 QList
<QByteArray
> current
= m_visibleRoles
;
1452 current
.removeAt(previousIndex
);
1453 current
.insert(currentIndex
, role
);
1455 setVisibleRoles(current
);
1457 emit
visibleRolesChanged(current
, previous
);
1460 void KItemListView::triggerAutoScrolling()
1462 if (!m_autoScrollTimer
) {
1467 int visibleSize
= 0;
1468 if (scrollOrientation() == Qt::Vertical
) {
1469 pos
= m_mousePos
.y();
1470 visibleSize
= size().height();
1472 pos
= m_mousePos
.x();
1473 visibleSize
= size().width();
1476 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1477 m_autoScrollIncrement
= 0;
1480 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1481 if (m_autoScrollIncrement
== 0) {
1482 // The mouse position is not above an autoscroll margin (the autoscroll timer
1483 // will be restarted in mouseMoveEvent())
1484 m_autoScrollTimer
->stop();
1488 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1489 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1490 // if the direction of the rubberband is similar to the autoscroll direction. This
1491 // prevents that starting to create a rubberband within the autoscroll margins starts
1492 // an autoscrolling.
1494 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1495 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1496 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1497 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1498 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1499 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1500 // been moved up although the autoscroll direction might be down)
1501 m_autoScrollTimer
->stop();
1506 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1507 // the autoscrolling may not get skipped anymore until a new rubberband is created
1508 m_skipAutoScrollForRubberBand
= false;
1510 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1511 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1512 setScrollOffset(newScrollOffset
);
1514 // Trigger the autoscroll timer which will periodically call
1515 // triggerAutoScrolling()
1516 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1519 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1521 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1523 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1524 Q_ASSERT(groupHeader
);
1525 updateGroupHeaderLayout(widget
);
1528 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1530 disconnectRoleEditingSignals(index
);
1532 emit
roleEditingCanceled(index
, role
, value
);
1533 m_editingRole
= false;
1536 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1538 disconnectRoleEditingSignals(index
);
1540 emit
roleEditingFinished(index
, role
, value
);
1541 m_editingRole
= false;
1544 void KItemListView::setController(KItemListController
* controller
)
1546 if (m_controller
!= controller
) {
1547 KItemListController
* previous
= m_controller
;
1549 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1550 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1551 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1554 m_controller
= controller
;
1557 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1558 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1559 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1562 onControllerChanged(controller
, previous
);
1566 void KItemListView::setModel(KItemModelBase
* model
)
1568 if (m_model
== model
) {
1572 KItemModelBase
* previous
= m_model
;
1575 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1576 this, &KItemListView::slotItemsChanged
);
1577 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1578 this, &KItemListView::slotItemsInserted
);
1579 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1580 this, &KItemListView::slotItemsRemoved
);
1581 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1582 this, &KItemListView::slotItemsMoved
);
1583 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1584 this, &KItemListView::slotGroupsChanged
);
1585 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1586 this, &KItemListView::slotGroupedSortingChanged
);
1587 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1588 this, &KItemListView::slotSortOrderChanged
);
1589 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1590 this, &KItemListView::slotSortRoleChanged
);
1592 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1596 m_layouter
->setModel(model
);
1597 m_grouped
= model
->groupedSorting();
1600 connect(m_model
, &KItemModelBase::itemsChanged
,
1601 this, &KItemListView::slotItemsChanged
);
1602 connect(m_model
, &KItemModelBase::itemsInserted
,
1603 this, &KItemListView::slotItemsInserted
);
1604 connect(m_model
, &KItemModelBase::itemsRemoved
,
1605 this, &KItemListView::slotItemsRemoved
);
1606 connect(m_model
, &KItemModelBase::itemsMoved
,
1607 this, &KItemListView::slotItemsMoved
);
1608 connect(m_model
, &KItemModelBase::groupsChanged
,
1609 this, &KItemListView::slotGroupsChanged
);
1610 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1611 this, &KItemListView::slotGroupedSortingChanged
);
1612 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1613 this, &KItemListView::slotSortOrderChanged
);
1614 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1615 this, &KItemListView::slotSortRoleChanged
);
1617 const int itemCount
= m_model
->count();
1618 if (itemCount
> 0) {
1619 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1623 onModelChanged(model
, previous
);
1626 KItemListRubberBand
* KItemListView::rubberBand() const
1628 return m_rubberBand
;
1631 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1633 if (m_layoutTimer
->isActive()) {
1634 m_layoutTimer
->stop();
1637 if (m_activeTransactions
> 0) {
1638 if (hint
== NoAnimation
) {
1639 // As soon as at least one property change should be done without animation,
1640 // the whole transaction will be marked as not animated.
1641 m_endTransactionAnimationHint
= NoAnimation
;
1646 if (!m_model
|| m_model
->count() < 0) {
1650 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1651 if (firstVisibleIndex
< 0) {
1652 emitOffsetChanges();
1656 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1657 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1658 // is still shown if the maximum offset got decreased.
1659 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1660 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1661 if (scrollOffset() > maxOffsetToShowFullRange
) {
1662 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1663 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1666 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1668 int firstSibblingIndex
= -1;
1669 int lastSibblingIndex
= -1;
1670 const bool supportsExpanding
= supportsItemExpanding();
1672 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1674 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1675 // instances from invisible items are reused. If no reusable items are
1676 // found then new KItemListWidget instances get created.
1677 const bool animate
= (hint
== Animation
);
1678 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1679 bool applyNewPos
= true;
1680 bool wasHidden
= false;
1682 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1683 const QPointF newPos
= itemBounds
.topLeft();
1684 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1687 if (!reusableItems
.isEmpty()) {
1688 // Reuse a KItemListWidget instance from an invisible item
1689 const int oldIndex
= reusableItems
.takeLast();
1690 widget
= m_visibleItems
.value(oldIndex
);
1691 setWidgetIndex(widget
, i
);
1692 updateWidgetProperties(widget
, i
);
1693 initializeItemListWidget(widget
);
1695 // No reusable KItemListWidget instance is available, create a new one
1696 widget
= createWidget(i
);
1698 widget
->resize(itemBounds
.size());
1700 if (animate
&& changedCount
< 0) {
1701 // Items have been deleted.
1702 if (i
>= changedIndex
) {
1703 // The item is located behind the removed range. Move the
1704 // created item to the imaginary old position outside the
1705 // view. It will get animated to the new position later.
1706 const int previousIndex
= i
- changedCount
;
1707 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1708 if (itemRect
.isEmpty()) {
1709 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1710 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1711 widget
->setPos(invisibleOldPos
);
1713 widget
->setPos(itemRect
.topLeft());
1715 applyNewPos
= false;
1719 if (supportsExpanding
&& changedCount
== 0) {
1720 if (firstSibblingIndex
< 0) {
1721 firstSibblingIndex
= i
;
1723 lastSibblingIndex
= i
;
1728 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1729 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1730 applyNewPos
= false;
1733 const bool itemsRemoved
= (changedCount
< 0);
1734 const bool itemsInserted
= (changedCount
> 0);
1735 if (itemsRemoved
&& (i
>= changedIndex
)) {
1736 // The item is located after the removed items. Animate the moving of the position.
1737 applyNewPos
= !moveWidget(widget
, newPos
);
1738 } else if (itemsInserted
&& i
>= changedIndex
) {
1739 // The item is located after the first inserted item
1740 if (i
<= changedIndex
+ changedCount
- 1) {
1741 // The item is an inserted item. Animate the appearing of the item.
1742 // For performance reasons no animation is done when changedCount is equal
1743 // to all available items.
1744 if (changedCount
< m_model
->count()) {
1745 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1747 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1748 // The item was already there before, so animate the moving of the position.
1749 // No moving animation is done if the item is animated by a create animation: This
1750 // prevents a "move animation mess" when inserting several ranges in parallel.
1751 applyNewPos
= !moveWidget(widget
, newPos
);
1753 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1754 // The size of the view might have been changed. Animate the moving of the position.
1755 applyNewPos
= !moveWidget(widget
, newPos
);
1758 m_animation
->stop(widget
);
1762 widget
->setPos(newPos
);
1765 Q_ASSERT(widget
->index() == i
);
1766 widget
->setVisible(true);
1768 if (widget
->size() != itemBounds
.size()) {
1769 // Resize the widget for the item to the changed size.
1771 // If a dynamic item size is used then no animation is done in the direction
1772 // of the dynamic size.
1773 if (m_itemSize
.width() <= 0) {
1774 // The width is dynamic, apply the new width without animation.
1775 widget
->resize(itemBounds
.width(), widget
->size().height());
1776 } else if (m_itemSize
.height() <= 0) {
1777 // The height is dynamic, apply the new height without animation.
1778 widget
->resize(widget
->size().width(), itemBounds
.height());
1780 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1782 widget
->resize(itemBounds
.size());
1786 // Updating the cell-information must be done as last step: The decision whether the
1787 // moving-animation should be started at all is based on the previous cell-information.
1788 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1789 m_visibleCells
.insert(i
, cell
);
1792 // Delete invisible KItemListWidget instances that have not been reused
1793 foreach (int index
, reusableItems
) {
1794 recycleWidget(m_visibleItems
.value(index
));
1797 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1798 Q_ASSERT(lastSibblingIndex
>= 0);
1799 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1803 // Update the layout of all visible group headers
1804 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1805 while (it
.hasNext()) {
1807 updateGroupHeaderLayout(it
.key());
1811 emitOffsetChanges();
1814 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1815 int lastVisibleIndex
,
1816 LayoutAnimationHint hint
)
1818 // Determine all items that are completely invisible and might be
1819 // reused for items that just got (at least partly) visible. If the
1820 // animation hint is set to 'Animation' items that do e.g. an animated
1821 // moving of their position are not marked as invisible: This assures
1822 // that a scrolling inside the view can be done without breaking an animation.
1826 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1827 while (it
.hasNext()) {
1830 KItemListWidget
* widget
= it
.value();
1831 const int index
= widget
->index();
1832 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1835 if (m_animation
->isStarted(widget
)) {
1836 if (hint
== NoAnimation
) {
1837 // Stopping the animation will call KItemListView::slotAnimationFinished()
1838 // and the widget will be recycled if necessary there.
1839 m_animation
->stop(widget
);
1842 widget
->setVisible(false);
1843 items
.append(index
);
1846 recycleGroupHeaderForWidget(widget
);
1855 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1857 if (widget
->pos() == newPos
) {
1861 bool startMovingAnim
= false;
1863 if (m_itemSize
.isEmpty()) {
1864 // The items are not aligned in a grid but either as columns or rows.
1865 startMovingAnim
= true;
1867 // When having a grid the moving-animation should only be started, if it is done within
1868 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1869 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1870 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1871 const int index
= widget
->index();
1872 const Cell cell
= m_visibleCells
.value(index
);
1873 if (cell
.column
>= 0 && cell
.row
>= 0) {
1874 if (scrollOrientation() == Qt::Vertical
) {
1875 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1877 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1882 if (startMovingAnim
) {
1883 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1887 m_animation
->stop(widget
);
1888 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1892 void KItemListView::emitOffsetChanges()
1894 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1895 if (m_oldScrollOffset
!= newScrollOffset
) {
1896 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1897 m_oldScrollOffset
= newScrollOffset
;
1900 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1901 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1902 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1903 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1906 const qreal newItemOffset
= m_layouter
->itemOffset();
1907 if (m_oldItemOffset
!= newItemOffset
) {
1908 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1909 m_oldItemOffset
= newItemOffset
;
1912 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1913 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1914 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1915 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1919 KItemListWidget
* KItemListView::createWidget(int index
)
1921 KItemListWidget
* widget
= widgetCreator()->create(this);
1922 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1924 m_visibleItems
.insert(index
, widget
);
1925 m_visibleCells
.insert(index
, Cell());
1926 updateWidgetProperties(widget
, index
);
1927 initializeItemListWidget(widget
);
1931 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1934 recycleGroupHeaderForWidget(widget
);
1937 const int index
= widget
->index();
1938 m_visibleItems
.remove(index
);
1939 m_visibleCells
.remove(index
);
1941 widgetCreator()->recycle(widget
);
1944 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1946 const int oldIndex
= widget
->index();
1947 m_visibleItems
.remove(oldIndex
);
1948 m_visibleCells
.remove(oldIndex
);
1950 m_visibleItems
.insert(index
, widget
);
1951 m_visibleCells
.insert(index
, Cell());
1953 widget
->setIndex(index
);
1956 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1958 const int oldIndex
= widget
->index();
1959 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1961 setWidgetIndex(widget
, index
);
1963 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1964 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1965 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1966 (!vertical
&& oldCell
.column
== newCell
.column
);
1968 m_visibleCells
.insert(index
, newCell
);
1972 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1975 case LayouterSize
: m_layouter
->setSize(size
); break;
1976 case ItemSize
: m_layouter
->setItemSize(size
); break;
1981 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1983 widget
->setVisibleRoles(m_visibleRoles
);
1984 updateWidgetColumnWidths(widget
);
1985 widget
->setStyleOption(m_styleOption
);
1987 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1989 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1990 // always the selected item. It is not necessary to highlight the current item then.
1991 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1992 widget
->setCurrent(index
== selectionManager
->currentItem());
1994 widget
->setSelected(selectionManager
->isSelected(index
));
1995 widget
->setHovered(false);
1996 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1997 widget
->setIndex(index
);
1998 widget
->setData(m_model
->data(index
));
1999 widget
->setSiblingsInformation(QBitArray());
2000 updateAlternateBackgroundForWidget(widget
);
2003 updateGroupHeaderForWidget(widget
);
2007 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2009 Q_ASSERT(m_grouped
);
2011 const int index
= widget
->index();
2012 if (!m_layouter
->isFirstGroupItem(index
)) {
2013 // The widget does not represent the first item of a group
2014 // and hence requires no header
2015 recycleGroupHeaderForWidget(widget
);
2019 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2020 if (groups
.isEmpty() || !groupHeaderCreator()) {
2024 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2026 groupHeader
= groupHeaderCreator()->create(this);
2027 groupHeader
->setParentItem(widget
);
2028 m_visibleGroups
.insert(widget
, groupHeader
);
2029 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2031 Q_ASSERT(groupHeader
->parentItem() == widget
);
2033 const int groupIndex
= groupIndexForItem(index
);
2034 Q_ASSERT(groupIndex
>= 0);
2035 groupHeader
->setData(groups
.at(groupIndex
).second
);
2036 groupHeader
->setRole(model()->sortRole());
2037 groupHeader
->setStyleOption(m_styleOption
);
2038 groupHeader
->setScrollOrientation(scrollOrientation());
2039 groupHeader
->setItemIndex(index
);
2041 groupHeader
->show();
2044 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2046 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2047 Q_ASSERT(groupHeader
);
2049 const int index
= widget
->index();
2050 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2051 const QRectF itemRect
= m_layouter
->itemRect(index
);
2053 // The group-header is a child of the itemlist widget. Translate the
2054 // group header position to the relative position.
2055 if (scrollOrientation() == Qt::Vertical
) {
2056 // In the vertical scroll orientation the group header should always span
2057 // the whole width no matter which temporary position the parent widget
2058 // has. In this case the x-position and width will be adjusted manually.
2059 const qreal x
= -widget
->x() - itemOffset();
2060 const qreal width
= maximumItemOffset();
2061 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2062 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2064 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2065 groupHeader
->resize(groupHeaderRect
.size());
2069 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2071 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2073 header
->setParentItem(nullptr);
2074 groupHeaderCreator()->recycle(header
);
2075 m_visibleGroups
.remove(widget
);
2076 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2080 void KItemListView::updateVisibleGroupHeaders()
2082 Q_ASSERT(m_grouped
);
2083 m_layouter
->markAsDirty();
2085 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2086 while (it
.hasNext()) {
2088 updateGroupHeaderForWidget(it
.value());
2092 int KItemListView::groupIndexForItem(int index
) const
2094 Q_ASSERT(m_grouped
);
2096 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2097 if (groups
.isEmpty()) {
2102 int max
= groups
.count() - 1;
2105 mid
= (min
+ max
) / 2;
2106 if (index
> groups
[mid
].first
) {
2111 } while (groups
[mid
].first
!= index
&& min
<= max
);
2114 while (groups
[mid
].first
> index
&& mid
> 0) {
2122 void KItemListView::updateAlternateBackgrounds()
2124 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2125 while (it
.hasNext()) {
2127 updateAlternateBackgroundForWidget(it
.value());
2131 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2133 bool enabled
= useAlternateBackgrounds();
2135 const int index
= widget
->index();
2136 enabled
= (index
& 0x1) > 0;
2138 const int groupIndex
= groupIndexForItem(index
);
2139 if (groupIndex
>= 0) {
2140 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2141 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2142 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2143 enabled
= (relativeIndex
& 0x1) > 0;
2147 widget
->setAlternateBackground(enabled
);
2150 bool KItemListView::useAlternateBackgrounds() const
2152 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2155 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2157 QElapsedTimer timer
;
2160 QHash
<QByteArray
, qreal
> widths
;
2162 // Calculate the minimum width for each column that is required
2163 // to show the headline unclipped.
2164 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2165 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2166 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2167 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2168 const QString headerText
= m_model
->roleDescription(visibleRole
);
2169 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2170 widths
.insert(visibleRole
, headerWidth
);
2173 // Calculate the preferred column withs for each item and ignore values
2174 // smaller than the width for showing the headline unclipped.
2175 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2176 int calculatedItemCount
= 0;
2177 bool maxTimeExceeded
= false;
2178 foreach (const KItemRange
& itemRange
, itemRanges
) {
2179 const int startIndex
= itemRange
.index
;
2180 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2182 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2183 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2184 qreal maxWidth
= widths
.value(visibleRole
, 0);
2185 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2186 maxWidth
= qMax(width
, maxWidth
);
2187 widths
.insert(visibleRole
, maxWidth
);
2190 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2191 // When having several thousands of items calculating the sizes can get
2192 // very expensive. We accept a possibly too small role-size in favour
2193 // of having no blocking user interface.
2194 maxTimeExceeded
= true;
2197 ++calculatedItemCount
;
2199 if (maxTimeExceeded
) {
2207 void KItemListView::applyColumnWidthsFromHeader()
2209 // Apply the new size to the layouter
2210 const qreal requiredWidth
= columnWidthsSum();
2211 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2212 m_itemSize
.height());
2213 m_layouter
->setItemSize(dynamicItemSize
);
2215 // Update the role sizes for all visible widgets
2216 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2217 while (it
.hasNext()) {
2219 updateWidgetColumnWidths(it
.value());
2223 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2225 foreach (const QByteArray
& role
, m_visibleRoles
) {
2226 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2230 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2232 Q_ASSERT(m_itemSize
.isEmpty());
2233 const int itemCount
= m_model
->count();
2234 int rangesItemCount
= 0;
2235 foreach (const KItemRange
& range
, itemRanges
) {
2236 rangesItemCount
+= range
.count
;
2239 if (itemCount
== rangesItemCount
) {
2240 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2241 foreach (const QByteArray
& role
, m_visibleRoles
) {
2242 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2245 // Only a sub range of the roles need to be determined.
2246 // The chances are good that the widths of the sub ranges
2247 // already fit into the available widths and hence no
2248 // expensive update might be required.
2249 bool changed
= false;
2251 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2252 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2253 while (it
.hasNext()) {
2255 const QByteArray
& role
= it
.key();
2256 const qreal updatedWidth
= it
.value();
2257 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2258 if (updatedWidth
> currentWidth
) {
2259 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2265 // All the updated sizes are smaller than the current sizes and no change
2266 // of the stretched roles-widths is required
2271 if (m_headerWidget
->automaticColumnResizing()) {
2272 applyAutomaticColumnWidths();
2276 void KItemListView::updatePreferredColumnWidths()
2279 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2283 void KItemListView::applyAutomaticColumnWidths()
2285 Q_ASSERT(m_itemSize
.isEmpty());
2286 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2287 if (m_visibleRoles
.isEmpty()) {
2291 // Calculate the maximum size of an item by considering the
2292 // visible role sizes and apply them to the layouter. If the
2293 // size does not use the available view-size the size of the
2294 // first role will get stretched.
2296 foreach (const QByteArray
& role
, m_visibleRoles
) {
2297 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2298 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2301 const QByteArray firstRole
= m_visibleRoles
.first();
2302 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2303 QSizeF dynamicItemSize
= m_itemSize
;
2305 qreal requiredWidth
= columnWidthsSum();
2306 const qreal availableWidth
= size().width();
2307 if (requiredWidth
< availableWidth
) {
2308 // Stretch the first column to use the whole remaining width
2309 firstColumnWidth
+= availableWidth
- requiredWidth
;
2310 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2311 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2312 // Shrink the first column to be able to show as much other
2313 // columns as possible
2314 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2316 // TODO: A proper calculation of the minimum width depends on the implementation
2317 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2319 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2320 if (shrinkedFirstColumnWidth
< minWidth
) {
2321 shrinkedFirstColumnWidth
= minWidth
;
2324 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2325 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2328 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2330 m_layouter
->setItemSize(dynamicItemSize
);
2332 // Update the role sizes for all visible widgets
2333 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2334 while (it
.hasNext()) {
2336 updateWidgetColumnWidths(it
.value());
2340 qreal
KItemListView::columnWidthsSum() const
2342 qreal widthsSum
= 0;
2343 foreach (const QByteArray
& role
, m_visibleRoles
) {
2344 widthsSum
+= m_headerWidget
->columnWidth(role
);
2349 QRectF
KItemListView::headerBoundaries() const
2351 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2354 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2355 const QSizeF
& newItemSize
,
2356 const QSizeF
& newItemMargin
) const
2358 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2362 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2363 const qreal itemWidth
= m_layouter
->itemSize().width();
2364 if (itemWidth
> 0) {
2365 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2366 newItemSize
.width(),
2367 newItemMargin
.width());
2368 if (m_model
->count() > newColumnCount
) {
2369 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2371 m_layouter
->itemMargin().width());
2372 return oldColumnCount
!= newColumnCount
;
2376 const qreal itemHeight
= m_layouter
->itemSize().height();
2377 if (itemHeight
> 0) {
2378 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2379 newItemSize
.height(),
2380 newItemMargin
.height());
2381 if (m_model
->count() > newRowCount
) {
2382 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2384 m_layouter
->itemMargin().height());
2385 return oldRowCount
!= newRowCount
;
2393 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2395 if (m_itemSize
.isEmpty()) {
2396 // We have only columns or only rows, but no grid: An animation is usually
2397 // welcome when inserting or removing items.
2398 return !supportsItemExpanding();
2401 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2405 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2406 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2407 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2408 // Only animate if up to 2/3 of a row or column are inserted or removed
2409 return changedItemCount
<= maximum
* 2 / 3;
2413 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2415 const QSizeF oldSize
= m_layouter
->size();
2417 m_layouter
->setSize(size
);
2418 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2419 m_layouter
->setSize(oldSize
);
2421 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2422 : maxOffset
> size
.width();
2425 int KItemListView::showDropIndicator(const QPointF
& pos
)
2427 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2428 while (it
.hasNext()) {
2430 const KItemListWidget
* widget
= it
.value();
2432 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2433 const QRectF rect
= itemRect(widget
->index());
2434 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2435 if (m_model
->supportsDropping(widget
->index())) {
2436 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2437 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2438 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2443 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2444 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2446 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2447 if (m_dropIndicator
!= draggingInsertIndicator
) {
2448 m_dropIndicator
= draggingInsertIndicator
;
2452 int index
= widget
->index();
2460 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2461 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2464 void KItemListView::hideDropIndicator()
2466 if (!m_dropIndicator
.isNull()) {
2467 m_dropIndicator
= QRectF();
2472 void KItemListView::updateGroupHeaderHeight()
2474 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2475 qreal groupHeaderMargin
= 0;
2477 if (scrollOrientation() == Qt::Horizontal
) {
2478 // The vertical margin above and below the header should be
2479 // equal to the horizontal margin, not the vertical margin
2480 // from m_styleOption.
2481 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2482 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2483 } else if (m_itemSize
.isEmpty()){
2484 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2485 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2487 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2488 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2490 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2491 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2493 updateVisibleGroupHeaders();
2496 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2498 if (!supportsItemExpanding() || !m_model
) {
2502 if (firstIndex
< 0 || lastIndex
< 0) {
2503 firstIndex
= m_layouter
->firstVisibleIndex();
2504 lastIndex
= m_layouter
->lastVisibleIndex();
2506 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2507 lastIndex
>= m_layouter
->firstVisibleIndex());
2508 if (!isRangeVisible
) {
2513 int previousParents
= 0;
2514 QBitArray previousSiblings
;
2516 // The rootIndex describes the first index where the siblings get
2517 // calculated from. For the calculation the upper most parent item
2518 // is required. For performance reasons it is checked first whether
2519 // the visible items before or after the current range already
2520 // contain a siblings information which can be used as base.
2521 int rootIndex
= firstIndex
;
2523 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2525 // There is no visible widget before the range, check whether there
2526 // is one after the range:
2527 widget
= m_visibleItems
.value(lastIndex
+ 1);
2529 // The sibling information of the widget may only be used if
2530 // all items of the range have the same number of parents.
2531 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2532 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2533 if (m_model
->expandedParentsCount(i
) != parents
) {
2542 // Performance optimization: Use the sibling information of the visible
2543 // widget beside the given range.
2544 previousSiblings
= widget
->siblingsInformation();
2545 if (previousSiblings
.isEmpty()) {
2548 previousParents
= previousSiblings
.count() - 1;
2549 previousSiblings
.truncate(previousParents
);
2551 // Potentially slow path: Go back to the upper most parent of firstIndex
2552 // to be able to calculate the initial value for the siblings.
2553 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2558 Q_ASSERT(previousParents
>= 0);
2559 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2560 // Update the parent-siblings in case if the current item represents
2561 // a child or an upper parent.
2562 const int currentParents
= m_model
->expandedParentsCount(i
);
2563 Q_ASSERT(currentParents
>= 0);
2564 if (previousParents
< currentParents
) {
2565 previousParents
= currentParents
;
2566 previousSiblings
.resize(currentParents
);
2567 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2568 } else if (previousParents
> currentParents
) {
2569 previousParents
= currentParents
;
2570 previousSiblings
.truncate(currentParents
);
2573 if (i
>= firstIndex
) {
2574 // The index represents a visible item. Apply the parent-siblings
2575 // and update the sibling of the current item.
2576 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2581 QBitArray siblings
= previousSiblings
;
2582 siblings
.resize(siblings
.count() + 1);
2583 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2585 widget
->setSiblingsInformation(siblings
);
2590 bool KItemListView::hasSiblingSuccessor(int index
) const
2592 bool hasSuccessor
= false;
2593 const int parentsCount
= m_model
->expandedParentsCount(index
);
2594 int successorIndex
= index
+ 1;
2596 // Search the next sibling
2597 const int itemCount
= m_model
->count();
2598 while (successorIndex
< itemCount
) {
2599 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2600 if (currentParentsCount
== parentsCount
) {
2601 hasSuccessor
= true;
2603 } else if (currentParentsCount
< parentsCount
) {
2609 if (m_grouped
&& hasSuccessor
) {
2610 // If the sibling is part of another group, don't mark it as
2611 // successor as the group header is between the sibling connections.
2612 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2613 if (m_layouter
->isFirstGroupItem(i
)) {
2614 hasSuccessor
= false;
2620 return hasSuccessor
;
2623 void KItemListView::disconnectRoleEditingSignals(int index
)
2625 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2630 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2631 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2632 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2635 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2639 const int minSpeed
= 4;
2640 const int maxSpeed
= 128;
2641 const int speedLimiter
= 96;
2642 const int autoScrollBorder
= 64;
2644 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2645 // This assures that the autoscrolling speed grows gradually.
2646 const int incLimiter
= 1;
2648 if (pos
< autoScrollBorder
) {
2649 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2650 inc
= qMax(inc
, -maxSpeed
);
2651 inc
= qMax(inc
, oldInc
- incLimiter
);
2652 } else if (pos
> range
- autoScrollBorder
) {
2653 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2654 inc
= qMin(inc
, maxSpeed
);
2655 inc
= qMin(inc
, oldInc
+ incLimiter
);
2661 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2663 const qreal availableSize
= size
- itemMargin
;
2664 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2670 KItemListCreatorBase::~KItemListCreatorBase()
2672 qDeleteAll(m_recycleableWidgets
);
2673 qDeleteAll(m_createdWidgets
);
2676 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2678 m_createdWidgets
.insert(widget
);
2681 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2683 Q_ASSERT(m_createdWidgets
.contains(widget
));
2684 m_createdWidgets
.remove(widget
);
2686 if (m_recycleableWidgets
.count() < 100) {
2687 m_recycleableWidgets
.append(widget
);
2688 widget
->setVisible(false);
2694 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2696 if (m_recycleableWidgets
.isEmpty()) {
2700 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2701 m_createdWidgets
.insert(widget
);
2705 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2709 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2711 widget
->setParentItem(nullptr);
2712 widget
->setOpacity(1.0);
2713 pushRecycleableWidget(widget
);
2716 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2720 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2722 header
->setOpacity(1.0);
2723 pushRecycleableWidget(header
);