1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 ***************************************************************************/
22 #include "kitemlistview.h"
24 #include "dolphindebug.h"
25 #include "kitemlistcontainer.h"
26 #include "kitemlistcontroller.h"
27 #include "kitemlistheader.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistviewaccessible.h"
30 #include "kstandarditemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
37 #include <QElapsedTimer>
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
40 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 #ifndef QT_NO_ACCESSIBILITY
54 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
58 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
59 return new KItemListContainerAccessible(container
);
60 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
61 return new KItemListViewAccessible(view
);
68 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
69 QGraphicsWidget(parent
),
70 m_enabledSelectionToggles(false),
72 m_supportsItemExpanding(false),
74 m_activeTransactions(0),
75 m_endTransactionAnimationHint(Animation
),
77 m_controller(nullptr),
80 m_widgetCreator(nullptr),
81 m_groupHeaderCreator(nullptr),
86 m_sizeHintResolver(nullptr),
89 m_layoutTimer(nullptr),
91 m_oldMaximumScrollOffset(0),
93 m_oldMaximumItemOffset(0),
94 m_skipAutoScrollForRubberBand(false),
95 m_rubberBand(nullptr),
97 m_autoScrollIncrement(0),
98 m_autoScrollTimer(nullptr),
100 m_headerWidget(nullptr),
103 setAcceptHoverEvents(true);
105 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
107 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
109 m_animation
= new KItemListViewAnimation(this);
110 connect(m_animation
, &KItemListViewAnimation::finished
,
111 this, &KItemListView::slotAnimationFinished
);
113 m_layoutTimer
= new QTimer(this);
114 m_layoutTimer
->setInterval(300);
115 m_layoutTimer
->setSingleShot(true);
116 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
118 m_rubberBand
= new KItemListRubberBand(this);
119 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
121 m_headerWidget
= new KItemListHeaderWidget(this);
122 m_headerWidget
->setVisible(false);
124 m_header
= new KItemListHeader(this);
126 #ifndef QT_NO_ACCESSIBILITY
127 QAccessible::installFactory(accessibleInterfaceFactory
);
132 KItemListView::~KItemListView()
134 // The group headers are children of the widgets created by
135 // widgetCreator(). So it is mandatory to delete the group headers
137 delete m_groupHeaderCreator
;
138 m_groupHeaderCreator
= nullptr;
140 delete m_widgetCreator
;
141 m_widgetCreator
= nullptr;
143 delete m_sizeHintResolver
;
144 m_sizeHintResolver
= nullptr;
147 void KItemListView::setScrollOffset(qreal offset
)
153 const qreal previousOffset
= m_layouter
->scrollOffset();
154 if (offset
== previousOffset
) {
158 m_layouter
->setScrollOffset(offset
);
159 m_animation
->setScrollOffset(offset
);
161 // Don't check whether the m_layoutTimer is active: Changing the
162 // scroll offset must always trigger a synchronous layout, otherwise
163 // the smooth-scrolling might get jerky.
164 doLayout(NoAnimation
);
165 onScrollOffsetChanged(offset
, previousOffset
);
168 qreal
KItemListView::scrollOffset() const
170 return m_layouter
->scrollOffset();
173 qreal
KItemListView::maximumScrollOffset() const
175 return m_layouter
->maximumScrollOffset();
178 void KItemListView::setItemOffset(qreal offset
)
180 if (m_layouter
->itemOffset() == offset
) {
184 m_layouter
->setItemOffset(offset
);
185 if (m_headerWidget
->isVisible()) {
186 m_headerWidget
->setOffset(offset
);
189 // Don't check whether the m_layoutTimer is active: Changing the
190 // item offset must always trigger a synchronous layout, otherwise
191 // the smooth-scrolling might get jerky.
192 doLayout(NoAnimation
);
195 qreal
KItemListView::itemOffset() const
197 return m_layouter
->itemOffset();
200 qreal
KItemListView::maximumItemOffset() const
202 return m_layouter
->maximumItemOffset();
205 int KItemListView::maximumVisibleItems() const
207 return m_layouter
->maximumVisibleItems();
210 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
212 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
213 m_visibleRoles
= roles
;
214 onVisibleRolesChanged(roles
, previousRoles
);
216 m_sizeHintResolver
->clearCache();
217 m_layouter
->markAsDirty();
219 if (m_itemSize
.isEmpty()) {
220 m_headerWidget
->setColumns(roles
);
221 updatePreferredColumnWidths();
222 if (!m_headerWidget
->automaticColumnResizing()) {
223 // The column-width of new roles are still 0. Apply the preferred
224 // column-width as default with.
225 foreach (const QByteArray
& role
, m_visibleRoles
) {
226 if (m_headerWidget
->columnWidth(role
) == 0) {
227 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
228 m_headerWidget
->setColumnWidth(role
, width
);
232 applyColumnWidthsFromHeader();
236 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
237 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
238 (roles
.count() <= 1 && previousRoles
.count() > 1));
240 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
241 while (it
.hasNext()) {
243 KItemListWidget
* widget
= it
.value();
244 widget
->setVisibleRoles(roles
);
245 if (alternateBackgroundsChanged
) {
246 updateAlternateBackgroundForWidget(widget
);
250 doLayout(NoAnimation
);
253 QList
<QByteArray
> KItemListView::visibleRoles() const
255 return m_visibleRoles
;
258 void KItemListView::setAutoScroll(bool enabled
)
260 if (enabled
&& !m_autoScrollTimer
) {
261 m_autoScrollTimer
= new QTimer(this);
262 m_autoScrollTimer
->setSingleShot(true);
263 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
264 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
265 } else if (!enabled
&& m_autoScrollTimer
) {
266 delete m_autoScrollTimer
;
267 m_autoScrollTimer
= nullptr;
271 bool KItemListView::autoScroll() const
273 return m_autoScrollTimer
!= nullptr;
276 void KItemListView::setEnabledSelectionToggles(bool enabled
)
278 if (m_enabledSelectionToggles
!= enabled
) {
279 m_enabledSelectionToggles
= enabled
;
281 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
282 while (it
.hasNext()) {
284 it
.value()->setEnabledSelectionToggle(enabled
);
289 bool KItemListView::enabledSelectionToggles() const
291 return m_enabledSelectionToggles
;
294 KItemListController
* KItemListView::controller() const
299 KItemModelBase
* KItemListView::model() const
304 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
306 delete m_widgetCreator
;
307 m_widgetCreator
= widgetCreator
;
310 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
312 if (!m_widgetCreator
) {
313 m_widgetCreator
= defaultWidgetCreator();
315 return m_widgetCreator
;
318 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
320 delete m_groupHeaderCreator
;
321 m_groupHeaderCreator
= groupHeaderCreator
;
324 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
326 if (!m_groupHeaderCreator
) {
327 m_groupHeaderCreator
= defaultGroupHeaderCreator();
329 return m_groupHeaderCreator
;
332 QSizeF
KItemListView::itemSize() const
337 const KItemListStyleOption
& KItemListView::styleOption() const
339 return m_styleOption
;
342 void KItemListView::setGeometry(const QRectF
& rect
)
344 QGraphicsWidget::setGeometry(rect
);
350 const QSizeF newSize
= rect
.size();
351 if (m_itemSize
.isEmpty()) {
352 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
353 if (m_headerWidget
->automaticColumnResizing()) {
354 applyAutomaticColumnWidths();
356 const qreal requiredWidth
= columnWidthsSum();
357 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
358 m_itemSize
.height());
359 m_layouter
->setItemSize(dynamicItemSize
);
362 // Triggering a synchronous layout is fine from a performance point of view,
363 // as with dynamic item sizes no moving animation must be done.
364 m_layouter
->setSize(newSize
);
365 doLayout(NoAnimation
);
367 const bool animate
= !changesItemGridLayout(newSize
,
368 m_layouter
->itemSize(),
369 m_layouter
->itemMargin());
370 m_layouter
->setSize(newSize
);
373 // Trigger an asynchronous relayout with m_layoutTimer to prevent
374 // performance bottlenecks. If the timer is exceeded, an animated layout
375 // will be triggered.
376 if (!m_layoutTimer
->isActive()) {
377 m_layoutTimer
->start();
380 m_layoutTimer
->stop();
381 doLayout(NoAnimation
);
386 qreal
KItemListView::verticalPageStep() const
388 qreal headerHeight
= 0;
389 if (m_headerWidget
->isVisible()) {
390 headerHeight
= m_headerWidget
->size().height();
392 return size().height() - headerHeight
;
395 int KItemListView::itemAt(const QPointF
& pos
) const
397 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
398 while (it
.hasNext()) {
401 const KItemListWidget
* widget
= it
.value();
402 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
403 if (widget
->contains(mappedPos
)) {
411 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
413 if (!m_enabledSelectionToggles
) {
417 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
419 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
420 if (!selectionToggleRect
.isEmpty()) {
421 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
422 return selectionToggleRect
.contains(mappedPos
);
428 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
430 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
432 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
433 if (!expansionToggleRect
.isEmpty()) {
434 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
435 return expansionToggleRect
.contains(mappedPos
);
441 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
443 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
445 const QRectF
&textRect
= widget
->textRect();
446 if (!textRect
.isEmpty()) {
447 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
448 return textRect
.contains(mappedPos
);
454 int KItemListView::firstVisibleIndex() const
456 return m_layouter
->firstVisibleIndex();
459 int KItemListView::lastVisibleIndex() const
461 return m_layouter
->lastVisibleIndex();
464 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
466 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
469 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
471 if (m_supportsItemExpanding
!= supportsExpanding
) {
472 m_supportsItemExpanding
= supportsExpanding
;
473 updateSiblingsInformation();
474 onSupportsItemExpandingChanged(supportsExpanding
);
478 bool KItemListView::supportsItemExpanding() const
480 return m_supportsItemExpanding
;
483 QRectF
KItemListView::itemRect(int index
) const
485 return m_layouter
->itemRect(index
);
488 QRectF
KItemListView::itemContextRect(int index
) const
492 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
494 contextRect
= widget
->iconRect() | widget
->textRect();
495 contextRect
.translate(itemRect(index
).topLeft());
501 void KItemListView::scrollToItem(int index
)
503 QRectF viewGeometry
= geometry();
504 if (m_headerWidget
->isVisible()) {
505 const qreal headerHeight
= m_headerWidget
->size().height();
506 viewGeometry
.adjust(0, headerHeight
, 0, 0);
508 QRectF currentRect
= itemRect(index
);
510 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
511 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
512 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
514 if (!viewGeometry
.contains(currentRect
)) {
515 qreal newOffset
= scrollOffset();
516 if (scrollOrientation() == Qt::Vertical
) {
517 if (currentRect
.top() < viewGeometry
.top()) {
518 newOffset
+= currentRect
.top() - viewGeometry
.top();
519 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
520 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
523 if (currentRect
.left() < viewGeometry
.left()) {
524 newOffset
+= currentRect
.left() - viewGeometry
.left();
525 } else if (currentRect
.right() > viewGeometry
.right()) {
526 newOffset
+= currentRect
.right() - viewGeometry
.right();
530 if (newOffset
!= scrollOffset()) {
531 emit
scrollTo(newOffset
);
536 void KItemListView::beginTransaction()
538 ++m_activeTransactions
;
539 if (m_activeTransactions
== 1) {
540 onTransactionBegin();
544 void KItemListView::endTransaction()
546 --m_activeTransactions
;
547 if (m_activeTransactions
< 0) {
548 m_activeTransactions
= 0;
549 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
552 if (m_activeTransactions
== 0) {
554 doLayout(m_endTransactionAnimationHint
);
555 m_endTransactionAnimationHint
= Animation
;
559 bool KItemListView::isTransactionActive() const
561 return m_activeTransactions
> 0;
564 void KItemListView::setHeaderVisible(bool visible
)
566 if (visible
&& !m_headerWidget
->isVisible()) {
567 QStyleOptionHeader option
;
568 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
571 m_headerWidget
->setPos(0, 0);
572 m_headerWidget
->resize(size().width(), headerSize
.height());
573 m_headerWidget
->setModel(m_model
);
574 m_headerWidget
->setColumns(m_visibleRoles
);
575 m_headerWidget
->setZValue(1);
577 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
578 this, &KItemListView::slotHeaderColumnWidthChanged
);
579 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
580 this, &KItemListView::slotHeaderColumnMoved
);
581 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
582 this, &KItemListView::sortOrderChanged
);
583 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
584 this, &KItemListView::sortRoleChanged
);
586 m_layouter
->setHeaderHeight(headerSize
.height());
587 m_headerWidget
->setVisible(true);
588 } else if (!visible
&& m_headerWidget
->isVisible()) {
589 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
590 this, &KItemListView::slotHeaderColumnWidthChanged
);
591 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
592 this, &KItemListView::slotHeaderColumnMoved
);
593 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
594 this, &KItemListView::sortOrderChanged
);
595 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
596 this, &KItemListView::sortRoleChanged
);
598 m_layouter
->setHeaderHeight(0);
599 m_headerWidget
->setVisible(false);
603 bool KItemListView::isHeaderVisible() const
605 return m_headerWidget
->isVisible();
608 KItemListHeader
* KItemListView::header() const
613 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
617 if (indexes
.count() == 1) {
618 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
619 QGraphicsView
* graphicsView
= scene()->views()[0];
620 if (item
&& graphicsView
) {
621 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
624 // TODO: Not implemented yet. Probably extend the interface
625 // from KItemListWidget::createDragPixmap() to return a pixmap
626 // that can be used for multiple indexes.
632 void KItemListView::editRole(int index
, const QByteArray
& role
)
634 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
635 if (!widget
|| m_editingRole
) {
639 m_editingRole
= true;
640 widget
->setEditedRole(role
);
642 connect(widget
, &KItemListWidget::roleEditingCanceled
,
643 this, &KItemListView::slotRoleEditingCanceled
);
644 connect(widget
, &KItemListWidget::roleEditingFinished
,
645 this, &KItemListView::slotRoleEditingFinished
);
647 connect(this, &KItemListView::scrollOffsetChanged
,
648 widget
, &KStandardItemListWidget::finishRoleEditing
);
651 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
653 QGraphicsWidget::paint(painter
, option
, widget
);
655 if (m_rubberBand
->isActive()) {
656 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
657 m_rubberBand
->endPosition()).normalized();
659 const QPointF topLeft
= rubberBandRect
.topLeft();
660 if (scrollOrientation() == Qt::Vertical
) {
661 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
663 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
666 QStyleOptionRubberBand opt
;
667 initStyleOption(&opt
);
668 opt
.shape
= QRubberBand::Rectangle
;
670 opt
.rect
= rubberBandRect
.toRect();
671 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
674 if (!m_dropIndicator
.isEmpty()) {
675 const QRectF r
= m_dropIndicator
.toRect();
677 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
678 painter
->setPen(color
);
680 // TODO: The following implementation works only for a vertical scroll-orientation
681 // and assumes a height of the m_draggingInsertIndicator of 1.
682 Q_ASSERT(r
.height() == 1);
683 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
686 painter
->setPen(color
);
687 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
691 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
693 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
694 if (!scene()->views().isEmpty()) {
695 m_styleOption
.palette
= scene()->views().at(0)->palette();
698 return QGraphicsItem::itemChange(change
, value
);
701 void KItemListView::setItemSize(const QSizeF
& size
)
703 const QSizeF previousSize
= m_itemSize
;
704 if (size
== previousSize
) {
708 // Skip animations when the number of rows or columns
709 // are changed in the grid layout. Although the animation
710 // engine can handle this usecase, it looks obtrusive.
711 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
713 m_layouter
->itemMargin());
715 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
716 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
717 (!m_itemSize
.isEmpty() && size
.isEmpty()));
721 if (alternateBackgroundsChanged
) {
722 // For an empty item size alternate backgrounds are drawn if more than
723 // one role is shown. Assure that the backgrounds for visible items are
724 // updated when changing the size in this context.
725 updateAlternateBackgrounds();
728 if (size
.isEmpty()) {
729 if (m_headerWidget
->automaticColumnResizing()) {
730 updatePreferredColumnWidths();
732 // Only apply the changed height and respect the header widths
734 const qreal currentWidth
= m_layouter
->itemSize().width();
735 const QSizeF
newSize(currentWidth
, size
.height());
736 m_layouter
->setItemSize(newSize
);
739 m_layouter
->setItemSize(size
);
742 m_sizeHintResolver
->clearCache();
743 doLayout(animate
? Animation
: NoAnimation
);
744 onItemSizeChanged(size
, previousSize
);
747 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
749 if (m_styleOption
== option
) {
753 const KItemListStyleOption previousOption
= m_styleOption
;
754 m_styleOption
= option
;
757 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
758 if (margin
!= m_layouter
->itemMargin()) {
759 // Skip animations when the number of rows or columns
760 // are changed in the grid layout. Although the animation
761 // engine can handle this usecase, it looks obtrusive.
762 animate
= !changesItemGridLayout(m_layouter
->size(),
763 m_layouter
->itemSize(),
765 m_layouter
->setItemMargin(margin
);
769 updateGroupHeaderHeight();
773 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
774 // Animating a change of the maximum text size just results in expensive
775 // temporary eliding and clipping operations and does not look good visually.
779 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
780 while (it
.hasNext()) {
782 it
.value()->setStyleOption(option
);
785 m_sizeHintResolver
->clearCache();
786 m_layouter
->markAsDirty();
787 doLayout(animate
? Animation
: NoAnimation
);
789 if (m_itemSize
.isEmpty()) {
790 updatePreferredColumnWidths();
793 onStyleOptionChanged(option
, previousOption
);
796 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
798 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
799 if (orientation
== previousOrientation
) {
803 m_layouter
->setScrollOrientation(orientation
);
804 m_animation
->setScrollOrientation(orientation
);
805 m_sizeHintResolver
->clearCache();
808 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
809 while (it
.hasNext()) {
811 it
.value()->setScrollOrientation(orientation
);
813 updateGroupHeaderHeight();
817 doLayout(NoAnimation
);
819 onScrollOrientationChanged(orientation
, previousOrientation
);
820 emit
scrollOrientationChanged(orientation
, previousOrientation
);
823 Qt::Orientation
KItemListView::scrollOrientation() const
825 return m_layouter
->scrollOrientation();
828 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
833 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
838 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
843 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
845 Q_UNUSED(changedRoles
)
849 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
855 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
861 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
867 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
873 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
879 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
885 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
891 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
893 Q_UNUSED(supportsExpanding
)
896 void KItemListView::onTransactionBegin()
900 void KItemListView::onTransactionEnd()
904 bool KItemListView::event(QEvent
* event
)
906 switch (event
->type()) {
907 case QEvent::PaletteChange
:
911 case QEvent::FontChange
:
916 // Forward all other events to the controller and handle them there
917 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
923 return QGraphicsWidget::event(event
);
926 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
928 m_mousePos
= transform().map(event
->pos());
932 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
934 QGraphicsWidget::mouseMoveEvent(event
);
936 m_mousePos
= transform().map(event
->pos());
937 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
938 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
942 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
944 event
->setAccepted(true);
948 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
950 QGraphicsWidget::dragMoveEvent(event
);
952 m_mousePos
= transform().map(event
->pos());
953 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
954 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
958 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
960 QGraphicsWidget::dragLeaveEvent(event
);
961 setAutoScroll(false);
964 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
966 QGraphicsWidget::dropEvent(event
);
967 setAutoScroll(false);
970 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
972 return m_visibleItems
.values();
975 void KItemListView::updateFont()
977 if (scene() && !scene()->views().isEmpty()) {
978 KItemListStyleOption option
= styleOption();
979 option
.font
= scene()->views().first()->font();
980 option
.fontMetrics
= QFontMetrics(option
.font
);
982 setStyleOption(option
);
986 void KItemListView::updatePalette()
988 if (scene() && !scene()->views().isEmpty()) {
989 KItemListStyleOption option
= styleOption();
990 option
.palette
= scene()->views().first()->palette();
992 setStyleOption(option
);
996 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
998 if (m_itemSize
.isEmpty()) {
999 updatePreferredColumnWidths(itemRanges
);
1002 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1003 if (hasMultipleRanges
) {
1007 m_layouter
->markAsDirty();
1009 m_sizeHintResolver
->itemsInserted(itemRanges
);
1011 int previouslyInsertedCount
= 0;
1012 foreach (const KItemRange
& range
, itemRanges
) {
1013 // range.index is related to the model before anything has been inserted.
1014 // As in each loop the current item-range gets inserted the index must
1015 // be increased by the already previously inserted items.
1016 const int index
= range
.index
+ previouslyInsertedCount
;
1017 const int count
= range
.count
;
1018 if (index
< 0 || count
<= 0) {
1019 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1022 previouslyInsertedCount
+= count
;
1024 // Determine which visible items must be moved
1025 QList
<int> itemsToMove
;
1026 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1027 while (it
.hasNext()) {
1029 const int visibleItemIndex
= it
.key();
1030 if (visibleItemIndex
>= index
) {
1031 itemsToMove
.append(visibleItemIndex
);
1035 // Update the indexes of all KItemListWidget instances that are located
1036 // after the inserted items. It is important to adjust the indexes in the order
1037 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1038 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1039 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1040 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1042 const int newIndex
= widget
->index() + count
;
1043 if (hasMultipleRanges
) {
1044 setWidgetIndex(widget
, newIndex
);
1046 // Try to animate the moving of the item
1047 moveWidgetToIndex(widget
, newIndex
);
1051 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1052 // Check whether a scrollbar is required to show the inserted items. In this case
1053 // the size of the layouter will be decreased before calling doLayout(): This prevents
1054 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1055 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1056 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1057 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1058 if (decreaseLayouterSize
) {
1059 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1061 int scrollbarSpacing
= 0;
1062 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1063 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1066 QSizeF layouterSize
= m_layouter
->size();
1067 if (verticalScrollOrientation
) {
1068 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1070 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1072 m_layouter
->setSize(layouterSize
);
1076 if (!hasMultipleRanges
) {
1077 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1078 updateSiblingsInformation();
1083 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1086 if (hasMultipleRanges
) {
1087 m_endTransactionAnimationHint
= NoAnimation
;
1090 updateSiblingsInformation();
1093 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1094 // In case if items of the same group have been inserted before an item that
1095 // currently represents the first item of the group, the group header of
1096 // this item must be removed.
1097 updateVisibleGroupHeaders();
1100 if (useAlternateBackgrounds()) {
1101 updateAlternateBackgrounds();
1105 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1107 if (m_itemSize
.isEmpty()) {
1108 // Don't pass the item-range: The preferred column-widths of
1109 // all items must be adjusted when removing items.
1110 updatePreferredColumnWidths();
1113 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1114 if (hasMultipleRanges
) {
1118 m_layouter
->markAsDirty();
1120 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1122 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1123 const KItemRange
& range
= itemRanges
[i
];
1124 const int index
= range
.index
;
1125 const int count
= range
.count
;
1126 if (index
< 0 || count
<= 0) {
1127 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1131 const int firstRemovedIndex
= index
;
1132 const int lastRemovedIndex
= index
+ count
- 1;
1134 // Remember which items have to be moved because they are behind the removed range.
1135 QVector
<int> itemsToMove
;
1137 // Remove all KItemListWidget instances that got deleted
1138 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1139 const int i
= widget
->index();
1140 if (i
< firstRemovedIndex
) {
1142 } else if (i
> lastRemovedIndex
) {
1143 itemsToMove
.append(i
);
1147 m_animation
->stop(widget
);
1148 // Stopping the animation might lead to recycling the widget if
1149 // it is invisible (see slotAnimationFinished()).
1150 // Check again whether it is still visible:
1151 if (!m_visibleItems
.contains(i
)) {
1155 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1156 // Remove the widget without animation
1157 recycleWidget(widget
);
1159 // Animate the removing of the items. Special case: When removing an item there
1160 // is no valid model index available anymore. For the
1161 // remove-animation the item gets removed from m_visibleItems but the widget
1162 // will stay alive until the animation has been finished and will
1163 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1164 m_visibleItems
.remove(i
);
1165 widget
->setIndex(-1);
1166 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1170 // Update the indexes of all KItemListWidget instances that are located
1171 // after the deleted items. It is important to update them in ascending
1172 // order to prevent overlaps when setting the new index.
1173 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1174 foreach (int i
, itemsToMove
) {
1175 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1177 const int newIndex
= i
- count
;
1178 if (hasMultipleRanges
) {
1179 setWidgetIndex(widget
, newIndex
);
1181 // Try to animate the moving of the item
1182 moveWidgetToIndex(widget
, newIndex
);
1186 if (!hasMultipleRanges
) {
1187 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1188 // assumes an updated geometry. If items are removed during an active transaction,
1189 // the transaction will be temporary deactivated so that doLayout() triggers a
1190 // geometry update if necessary.
1191 const int activeTransactions
= m_activeTransactions
;
1192 m_activeTransactions
= 0;
1193 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1194 m_activeTransactions
= activeTransactions
;
1195 updateSiblingsInformation();
1200 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1203 if (hasMultipleRanges
) {
1204 m_endTransactionAnimationHint
= NoAnimation
;
1206 updateSiblingsInformation();
1209 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1210 // In case if the first item of a group has been removed, the group header
1211 // must be applied to the next visible item.
1212 updateVisibleGroupHeaders();
1215 if (useAlternateBackgrounds()) {
1216 updateAlternateBackgrounds();
1220 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1222 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1223 m_layouter
->markAsDirty();
1226 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1229 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1230 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1232 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1233 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1235 updateWidgetProperties(widget
, index
);
1236 initializeItemListWidget(widget
);
1240 doLayout(NoAnimation
);
1241 updateSiblingsInformation();
1244 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1245 const QSet
<QByteArray
>& roles
)
1247 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1248 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1249 updatePreferredColumnWidths(itemRanges
);
1252 foreach (const KItemRange
& itemRange
, itemRanges
) {
1253 const int index
= itemRange
.index
;
1254 const int count
= itemRange
.count
;
1256 if (updateSizeHints
) {
1257 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1258 m_layouter
->markAsDirty();
1260 if (!m_layoutTimer
->isActive()) {
1261 m_layoutTimer
->start();
1265 // Apply the changed roles to the visible item-widgets
1266 const int lastIndex
= index
+ count
- 1;
1267 for (int i
= index
; i
<= lastIndex
; ++i
) {
1268 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1270 widget
->setData(m_model
->data(i
), roles
);
1274 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1275 // The sort-role has been changed which might result
1276 // in modified group headers
1277 updateVisibleGroupHeaders();
1278 doLayout(NoAnimation
);
1281 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1282 ev
.setFirstRow(itemRange
.index
);
1283 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1284 QAccessible::updateAccessibility(&ev
);
1288 void KItemListView::slotGroupsChanged()
1290 updateVisibleGroupHeaders();
1291 doLayout(NoAnimation
);
1292 updateSiblingsInformation();
1295 void KItemListView::slotGroupedSortingChanged(bool current
)
1297 m_grouped
= current
;
1298 m_layouter
->markAsDirty();
1301 updateGroupHeaderHeight();
1303 // Clear all visible headers. Note that the QHashIterator takes a copy of
1304 // m_visibleGroups. Therefore, it remains valid even if items are removed
1305 // from m_visibleGroups in recycleGroupHeaderForWidget().
1306 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1307 while (it
.hasNext()) {
1309 recycleGroupHeaderForWidget(it
.key());
1311 Q_ASSERT(m_visibleGroups
.isEmpty());
1314 if (useAlternateBackgrounds()) {
1315 // Changing the group mode requires to update the alternate backgrounds
1316 // as with the enabled group mode the altering is done on base of the first
1318 updateAlternateBackgrounds();
1320 updateSiblingsInformation();
1321 doLayout(NoAnimation
);
1324 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1329 updateVisibleGroupHeaders();
1330 doLayout(NoAnimation
);
1334 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1339 updateVisibleGroupHeaders();
1340 doLayout(NoAnimation
);
1344 void KItemListView::slotCurrentChanged(int current
, int previous
)
1348 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1349 // always the selected item. It is not necessary to highlight the current item then.
1350 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1351 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1352 if (previousWidget
) {
1353 previousWidget
->setCurrent(false);
1356 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1357 if (currentWidget
) {
1358 currentWidget
->setCurrent(true);
1362 QAccessibleEvent
ev(this, QAccessible::Focus
);
1363 ev
.setChild(current
);
1364 QAccessible::updateAccessibility(&ev
);
1367 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1371 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1372 while (it
.hasNext()) {
1374 const int index
= it
.key();
1375 KItemListWidget
* widget
= it
.value();
1376 widget
->setSelected(current
.contains(index
));
1380 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1381 KItemListViewAnimation::AnimationType type
)
1383 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1384 Q_ASSERT(itemListWidget
);
1387 case KItemListViewAnimation::DeleteAnimation
: {
1388 // As we recycle the widget in this case it is important to assure that no
1389 // other animation has been started. This is a convention in KItemListView and
1390 // not a requirement defined by KItemListViewAnimation.
1391 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1393 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1394 // by m_visibleWidgets and must be deleted manually after the animation has
1396 recycleGroupHeaderForWidget(itemListWidget
);
1397 widgetCreator()->recycle(itemListWidget
);
1401 case KItemListViewAnimation::CreateAnimation
:
1402 case KItemListViewAnimation::MovingAnimation
:
1403 case KItemListViewAnimation::ResizeAnimation
: {
1404 const int index
= itemListWidget
->index();
1405 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1406 (index
> m_layouter
->lastVisibleIndex());
1407 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1408 recycleWidget(itemListWidget
);
1417 void KItemListView::slotLayoutTimerFinished()
1419 m_layouter
->setSize(geometry().size());
1420 doLayout(Animation
);
1423 void KItemListView::slotRubberBandPosChanged()
1428 void KItemListView::slotRubberBandActivationChanged(bool active
)
1431 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1432 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1433 m_skipAutoScrollForRubberBand
= true;
1435 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1436 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1437 m_skipAutoScrollForRubberBand
= false;
1443 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1445 qreal previousWidth
)
1448 Q_UNUSED(currentWidth
)
1449 Q_UNUSED(previousWidth
)
1451 m_headerWidget
->setAutomaticColumnResizing(false);
1452 applyColumnWidthsFromHeader();
1453 doLayout(NoAnimation
);
1456 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1460 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1462 const QList
<QByteArray
> previous
= m_visibleRoles
;
1464 QList
<QByteArray
> current
= m_visibleRoles
;
1465 current
.removeAt(previousIndex
);
1466 current
.insert(currentIndex
, role
);
1468 setVisibleRoles(current
);
1470 emit
visibleRolesChanged(current
, previous
);
1473 void KItemListView::triggerAutoScrolling()
1475 if (!m_autoScrollTimer
) {
1480 int visibleSize
= 0;
1481 if (scrollOrientation() == Qt::Vertical
) {
1482 pos
= m_mousePos
.y();
1483 visibleSize
= size().height();
1485 pos
= m_mousePos
.x();
1486 visibleSize
= size().width();
1489 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1490 m_autoScrollIncrement
= 0;
1493 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1494 if (m_autoScrollIncrement
== 0) {
1495 // The mouse position is not above an autoscroll margin (the autoscroll timer
1496 // will be restarted in mouseMoveEvent())
1497 m_autoScrollTimer
->stop();
1501 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1502 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1503 // if the direction of the rubberband is similar to the autoscroll direction. This
1504 // prevents that starting to create a rubberband within the autoscroll margins starts
1505 // an autoscrolling.
1507 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1508 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1509 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1510 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1511 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1512 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1513 // been moved up although the autoscroll direction might be down)
1514 m_autoScrollTimer
->stop();
1519 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1520 // the autoscrolling may not get skipped anymore until a new rubberband is created
1521 m_skipAutoScrollForRubberBand
= false;
1523 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1524 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1525 setScrollOffset(newScrollOffset
);
1527 // Trigger the autoscroll timer which will periodically call
1528 // triggerAutoScrolling()
1529 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1532 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1534 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1536 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1537 Q_ASSERT(groupHeader
);
1538 updateGroupHeaderLayout(widget
);
1541 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1543 disconnectRoleEditingSignals(index
);
1545 emit
roleEditingCanceled(index
, role
, value
);
1546 m_editingRole
= false;
1549 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1551 disconnectRoleEditingSignals(index
);
1553 emit
roleEditingFinished(index
, role
, value
);
1554 m_editingRole
= false;
1557 void KItemListView::setController(KItemListController
* controller
)
1559 if (m_controller
!= controller
) {
1560 KItemListController
* previous
= m_controller
;
1562 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1563 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1564 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1567 m_controller
= controller
;
1570 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1571 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1572 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1575 onControllerChanged(controller
, previous
);
1579 void KItemListView::setModel(KItemModelBase
* model
)
1581 if (m_model
== model
) {
1585 KItemModelBase
* previous
= m_model
;
1588 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1589 this, &KItemListView::slotItemsChanged
);
1590 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1591 this, &KItemListView::slotItemsInserted
);
1592 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1593 this, &KItemListView::slotItemsRemoved
);
1594 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1595 this, &KItemListView::slotItemsMoved
);
1596 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1597 this, &KItemListView::slotGroupsChanged
);
1598 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1599 this, &KItemListView::slotGroupedSortingChanged
);
1600 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1601 this, &KItemListView::slotSortOrderChanged
);
1602 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1603 this, &KItemListView::slotSortRoleChanged
);
1605 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1609 m_layouter
->setModel(model
);
1610 m_grouped
= model
->groupedSorting();
1613 connect(m_model
, &KItemModelBase::itemsChanged
,
1614 this, &KItemListView::slotItemsChanged
);
1615 connect(m_model
, &KItemModelBase::itemsInserted
,
1616 this, &KItemListView::slotItemsInserted
);
1617 connect(m_model
, &KItemModelBase::itemsRemoved
,
1618 this, &KItemListView::slotItemsRemoved
);
1619 connect(m_model
, &KItemModelBase::itemsMoved
,
1620 this, &KItemListView::slotItemsMoved
);
1621 connect(m_model
, &KItemModelBase::groupsChanged
,
1622 this, &KItemListView::slotGroupsChanged
);
1623 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1624 this, &KItemListView::slotGroupedSortingChanged
);
1625 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1626 this, &KItemListView::slotSortOrderChanged
);
1627 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1628 this, &KItemListView::slotSortRoleChanged
);
1630 const int itemCount
= m_model
->count();
1631 if (itemCount
> 0) {
1632 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1636 onModelChanged(model
, previous
);
1639 KItemListRubberBand
* KItemListView::rubberBand() const
1641 return m_rubberBand
;
1644 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1646 if (m_layoutTimer
->isActive()) {
1647 m_layoutTimer
->stop();
1650 if (m_activeTransactions
> 0) {
1651 if (hint
== NoAnimation
) {
1652 // As soon as at least one property change should be done without animation,
1653 // the whole transaction will be marked as not animated.
1654 m_endTransactionAnimationHint
= NoAnimation
;
1659 if (!m_model
|| m_model
->count() < 0) {
1663 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1664 if (firstVisibleIndex
< 0) {
1665 emitOffsetChanges();
1669 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1670 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1671 // is still shown if the maximum offset got decreased.
1672 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1673 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1674 if (scrollOffset() > maxOffsetToShowFullRange
) {
1675 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1676 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1679 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1681 int firstSibblingIndex
= -1;
1682 int lastSibblingIndex
= -1;
1683 const bool supportsExpanding
= supportsItemExpanding();
1685 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1687 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1688 // instances from invisible items are reused. If no reusable items are
1689 // found then new KItemListWidget instances get created.
1690 const bool animate
= (hint
== Animation
);
1691 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1692 bool applyNewPos
= true;
1693 bool wasHidden
= false;
1695 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1696 const QPointF newPos
= itemBounds
.topLeft();
1697 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1700 if (!reusableItems
.isEmpty()) {
1701 // Reuse a KItemListWidget instance from an invisible item
1702 const int oldIndex
= reusableItems
.takeLast();
1703 widget
= m_visibleItems
.value(oldIndex
);
1704 setWidgetIndex(widget
, i
);
1705 updateWidgetProperties(widget
, i
);
1706 initializeItemListWidget(widget
);
1708 // No reusable KItemListWidget instance is available, create a new one
1709 widget
= createWidget(i
);
1711 widget
->resize(itemBounds
.size());
1713 if (animate
&& changedCount
< 0) {
1714 // Items have been deleted.
1715 if (i
>= changedIndex
) {
1716 // The item is located behind the removed range. Move the
1717 // created item to the imaginary old position outside the
1718 // view. It will get animated to the new position later.
1719 const int previousIndex
= i
- changedCount
;
1720 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1721 if (itemRect
.isEmpty()) {
1722 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1723 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1724 widget
->setPos(invisibleOldPos
);
1726 widget
->setPos(itemRect
.topLeft());
1728 applyNewPos
= false;
1732 if (supportsExpanding
&& changedCount
== 0) {
1733 if (firstSibblingIndex
< 0) {
1734 firstSibblingIndex
= i
;
1736 lastSibblingIndex
= i
;
1741 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1742 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1743 applyNewPos
= false;
1746 const bool itemsRemoved
= (changedCount
< 0);
1747 const bool itemsInserted
= (changedCount
> 0);
1748 if (itemsRemoved
&& (i
>= changedIndex
)) {
1749 // The item is located after the removed items. Animate the moving of the position.
1750 applyNewPos
= !moveWidget(widget
, newPos
);
1751 } else if (itemsInserted
&& i
>= changedIndex
) {
1752 // The item is located after the first inserted item
1753 if (i
<= changedIndex
+ changedCount
- 1) {
1754 // The item is an inserted item. Animate the appearing of the item.
1755 // For performance reasons no animation is done when changedCount is equal
1756 // to all available items.
1757 if (changedCount
< m_model
->count()) {
1758 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1760 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1761 // The item was already there before, so animate the moving of the position.
1762 // No moving animation is done if the item is animated by a create animation: This
1763 // prevents a "move animation mess" when inserting several ranges in parallel.
1764 applyNewPos
= !moveWidget(widget
, newPos
);
1766 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1767 // The size of the view might have been changed. Animate the moving of the position.
1768 applyNewPos
= !moveWidget(widget
, newPos
);
1771 m_animation
->stop(widget
);
1775 widget
->setPos(newPos
);
1778 Q_ASSERT(widget
->index() == i
);
1779 widget
->setVisible(true);
1781 if (widget
->size() != itemBounds
.size()) {
1782 // Resize the widget for the item to the changed size.
1784 // If a dynamic item size is used then no animation is done in the direction
1785 // of the dynamic size.
1786 if (m_itemSize
.width() <= 0) {
1787 // The width is dynamic, apply the new width without animation.
1788 widget
->resize(itemBounds
.width(), widget
->size().height());
1789 } else if (m_itemSize
.height() <= 0) {
1790 // The height is dynamic, apply the new height without animation.
1791 widget
->resize(widget
->size().width(), itemBounds
.height());
1793 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1795 widget
->resize(itemBounds
.size());
1799 // Updating the cell-information must be done as last step: The decision whether the
1800 // moving-animation should be started at all is based on the previous cell-information.
1801 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1802 m_visibleCells
.insert(i
, cell
);
1805 // Delete invisible KItemListWidget instances that have not been reused
1806 foreach (int index
, reusableItems
) {
1807 recycleWidget(m_visibleItems
.value(index
));
1810 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1811 Q_ASSERT(lastSibblingIndex
>= 0);
1812 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1816 // Update the layout of all visible group headers
1817 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1818 while (it
.hasNext()) {
1820 updateGroupHeaderLayout(it
.key());
1824 emitOffsetChanges();
1827 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1828 int lastVisibleIndex
,
1829 LayoutAnimationHint hint
)
1831 // Determine all items that are completely invisible and might be
1832 // reused for items that just got (at least partly) visible. If the
1833 // animation hint is set to 'Animation' items that do e.g. an animated
1834 // moving of their position are not marked as invisible: This assures
1835 // that a scrolling inside the view can be done without breaking an animation.
1839 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1840 while (it
.hasNext()) {
1843 KItemListWidget
* widget
= it
.value();
1844 const int index
= widget
->index();
1845 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1848 if (m_animation
->isStarted(widget
)) {
1849 if (hint
== NoAnimation
) {
1850 // Stopping the animation will call KItemListView::slotAnimationFinished()
1851 // and the widget will be recycled if necessary there.
1852 m_animation
->stop(widget
);
1855 widget
->setVisible(false);
1856 items
.append(index
);
1859 recycleGroupHeaderForWidget(widget
);
1868 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1870 if (widget
->pos() == newPos
) {
1874 bool startMovingAnim
= false;
1876 if (m_itemSize
.isEmpty()) {
1877 // The items are not aligned in a grid but either as columns or rows.
1878 startMovingAnim
= true;
1880 // When having a grid the moving-animation should only be started, if it is done within
1881 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1882 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1883 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1884 const int index
= widget
->index();
1885 const Cell cell
= m_visibleCells
.value(index
);
1886 if (cell
.column
>= 0 && cell
.row
>= 0) {
1887 if (scrollOrientation() == Qt::Vertical
) {
1888 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1890 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1895 if (startMovingAnim
) {
1896 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1900 m_animation
->stop(widget
);
1901 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1905 void KItemListView::emitOffsetChanges()
1907 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1908 if (m_oldScrollOffset
!= newScrollOffset
) {
1909 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1910 m_oldScrollOffset
= newScrollOffset
;
1913 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1914 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1915 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1916 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1919 const qreal newItemOffset
= m_layouter
->itemOffset();
1920 if (m_oldItemOffset
!= newItemOffset
) {
1921 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1922 m_oldItemOffset
= newItemOffset
;
1925 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1926 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1927 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1928 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1932 KItemListWidget
* KItemListView::createWidget(int index
)
1934 KItemListWidget
* widget
= widgetCreator()->create(this);
1935 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1937 m_visibleItems
.insert(index
, widget
);
1938 m_visibleCells
.insert(index
, Cell());
1939 updateWidgetProperties(widget
, index
);
1940 initializeItemListWidget(widget
);
1944 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1947 recycleGroupHeaderForWidget(widget
);
1950 const int index
= widget
->index();
1951 m_visibleItems
.remove(index
);
1952 m_visibleCells
.remove(index
);
1954 widgetCreator()->recycle(widget
);
1957 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1959 const int oldIndex
= widget
->index();
1960 m_visibleItems
.remove(oldIndex
);
1961 m_visibleCells
.remove(oldIndex
);
1963 m_visibleItems
.insert(index
, widget
);
1964 m_visibleCells
.insert(index
, Cell());
1966 widget
->setIndex(index
);
1969 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1971 const int oldIndex
= widget
->index();
1972 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1974 setWidgetIndex(widget
, index
);
1976 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1977 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1978 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1979 (!vertical
&& oldCell
.column
== newCell
.column
);
1981 m_visibleCells
.insert(index
, newCell
);
1985 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1988 case LayouterSize
: m_layouter
->setSize(size
); break;
1989 case ItemSize
: m_layouter
->setItemSize(size
); break;
1994 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1996 widget
->setVisibleRoles(m_visibleRoles
);
1997 updateWidgetColumnWidths(widget
);
1998 widget
->setStyleOption(m_styleOption
);
2000 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2002 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2003 // always the selected item. It is not necessary to highlight the current item then.
2004 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2005 widget
->setCurrent(index
== selectionManager
->currentItem());
2007 widget
->setSelected(selectionManager
->isSelected(index
));
2008 widget
->setHovered(false);
2009 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2010 widget
->setIndex(index
);
2011 widget
->setData(m_model
->data(index
));
2012 widget
->setSiblingsInformation(QBitArray());
2013 updateAlternateBackgroundForWidget(widget
);
2016 updateGroupHeaderForWidget(widget
);
2020 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2022 Q_ASSERT(m_grouped
);
2024 const int index
= widget
->index();
2025 if (!m_layouter
->isFirstGroupItem(index
)) {
2026 // The widget does not represent the first item of a group
2027 // and hence requires no header
2028 recycleGroupHeaderForWidget(widget
);
2032 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2033 if (groups
.isEmpty() || !groupHeaderCreator()) {
2037 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2039 groupHeader
= groupHeaderCreator()->create(this);
2040 groupHeader
->setParentItem(widget
);
2041 m_visibleGroups
.insert(widget
, groupHeader
);
2042 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2044 Q_ASSERT(groupHeader
->parentItem() == widget
);
2046 const int groupIndex
= groupIndexForItem(index
);
2047 Q_ASSERT(groupIndex
>= 0);
2048 groupHeader
->setData(groups
.at(groupIndex
).second
);
2049 groupHeader
->setRole(model()->sortRole());
2050 groupHeader
->setStyleOption(m_styleOption
);
2051 groupHeader
->setScrollOrientation(scrollOrientation());
2052 groupHeader
->setItemIndex(index
);
2054 groupHeader
->show();
2057 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2059 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2060 Q_ASSERT(groupHeader
);
2062 const int index
= widget
->index();
2063 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2064 const QRectF itemRect
= m_layouter
->itemRect(index
);
2066 // The group-header is a child of the itemlist widget. Translate the
2067 // group header position to the relative position.
2068 if (scrollOrientation() == Qt::Vertical
) {
2069 // In the vertical scroll orientation the group header should always span
2070 // the whole width no matter which temporary position the parent widget
2071 // has. In this case the x-position and width will be adjusted manually.
2072 const qreal x
= -widget
->x() - itemOffset();
2073 const qreal width
= maximumItemOffset();
2074 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2075 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2077 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2078 groupHeader
->resize(groupHeaderRect
.size());
2082 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2084 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2086 header
->setParentItem(nullptr);
2087 groupHeaderCreator()->recycle(header
);
2088 m_visibleGroups
.remove(widget
);
2089 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2093 void KItemListView::updateVisibleGroupHeaders()
2095 Q_ASSERT(m_grouped
);
2096 m_layouter
->markAsDirty();
2098 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2099 while (it
.hasNext()) {
2101 updateGroupHeaderForWidget(it
.value());
2105 int KItemListView::groupIndexForItem(int index
) const
2107 Q_ASSERT(m_grouped
);
2109 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2110 if (groups
.isEmpty()) {
2115 int max
= groups
.count() - 1;
2118 mid
= (min
+ max
) / 2;
2119 if (index
> groups
[mid
].first
) {
2124 } while (groups
[mid
].first
!= index
&& min
<= max
);
2127 while (groups
[mid
].first
> index
&& mid
> 0) {
2135 void KItemListView::updateAlternateBackgrounds()
2137 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2138 while (it
.hasNext()) {
2140 updateAlternateBackgroundForWidget(it
.value());
2144 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2146 bool enabled
= useAlternateBackgrounds();
2148 const int index
= widget
->index();
2149 enabled
= (index
& 0x1) > 0;
2151 const int groupIndex
= groupIndexForItem(index
);
2152 if (groupIndex
>= 0) {
2153 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2154 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2155 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2156 enabled
= (relativeIndex
& 0x1) > 0;
2160 widget
->setAlternateBackground(enabled
);
2163 bool KItemListView::useAlternateBackgrounds() const
2165 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2168 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2170 QElapsedTimer timer
;
2173 QHash
<QByteArray
, qreal
> widths
;
2175 // Calculate the minimum width for each column that is required
2176 // to show the headline unclipped.
2177 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2178 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2179 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2180 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2181 const QString headerText
= m_model
->roleDescription(visibleRole
);
2182 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2183 widths
.insert(visibleRole
, headerWidth
);
2186 // Calculate the preferred column withs for each item and ignore values
2187 // smaller than the width for showing the headline unclipped.
2188 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2189 int calculatedItemCount
= 0;
2190 bool maxTimeExceeded
= false;
2191 foreach (const KItemRange
& itemRange
, itemRanges
) {
2192 const int startIndex
= itemRange
.index
;
2193 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2195 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2196 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2197 qreal maxWidth
= widths
.value(visibleRole
, 0);
2198 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2199 maxWidth
= qMax(width
, maxWidth
);
2200 widths
.insert(visibleRole
, maxWidth
);
2203 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2204 // When having several thousands of items calculating the sizes can get
2205 // very expensive. We accept a possibly too small role-size in favour
2206 // of having no blocking user interface.
2207 maxTimeExceeded
= true;
2210 ++calculatedItemCount
;
2212 if (maxTimeExceeded
) {
2220 void KItemListView::applyColumnWidthsFromHeader()
2222 // Apply the new size to the layouter
2223 const qreal requiredWidth
= columnWidthsSum();
2224 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2225 m_itemSize
.height());
2226 m_layouter
->setItemSize(dynamicItemSize
);
2228 // Update the role sizes for all visible widgets
2229 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2230 while (it
.hasNext()) {
2232 updateWidgetColumnWidths(it
.value());
2236 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2238 foreach (const QByteArray
& role
, m_visibleRoles
) {
2239 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2243 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2245 Q_ASSERT(m_itemSize
.isEmpty());
2246 const int itemCount
= m_model
->count();
2247 int rangesItemCount
= 0;
2248 foreach (const KItemRange
& range
, itemRanges
) {
2249 rangesItemCount
+= range
.count
;
2252 if (itemCount
== rangesItemCount
) {
2253 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2254 foreach (const QByteArray
& role
, m_visibleRoles
) {
2255 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2258 // Only a sub range of the roles need to be determined.
2259 // The chances are good that the widths of the sub ranges
2260 // already fit into the available widths and hence no
2261 // expensive update might be required.
2262 bool changed
= false;
2264 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2265 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2266 while (it
.hasNext()) {
2268 const QByteArray
& role
= it
.key();
2269 const qreal updatedWidth
= it
.value();
2270 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2271 if (updatedWidth
> currentWidth
) {
2272 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2278 // All the updated sizes are smaller than the current sizes and no change
2279 // of the stretched roles-widths is required
2284 if (m_headerWidget
->automaticColumnResizing()) {
2285 applyAutomaticColumnWidths();
2289 void KItemListView::updatePreferredColumnWidths()
2292 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2296 void KItemListView::applyAutomaticColumnWidths()
2298 Q_ASSERT(m_itemSize
.isEmpty());
2299 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2300 if (m_visibleRoles
.isEmpty()) {
2304 // Calculate the maximum size of an item by considering the
2305 // visible role sizes and apply them to the layouter. If the
2306 // size does not use the available view-size the size of the
2307 // first role will get stretched.
2309 foreach (const QByteArray
& role
, m_visibleRoles
) {
2310 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2311 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2314 const QByteArray firstRole
= m_visibleRoles
.first();
2315 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2316 QSizeF dynamicItemSize
= m_itemSize
;
2318 qreal requiredWidth
= columnWidthsSum();
2319 const qreal availableWidth
= size().width();
2320 if (requiredWidth
< availableWidth
) {
2321 // Stretch the first column to use the whole remaining width
2322 firstColumnWidth
+= availableWidth
- requiredWidth
;
2323 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2324 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2325 // Shrink the first column to be able to show as much other
2326 // columns as possible
2327 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2329 // TODO: A proper calculation of the minimum width depends on the implementation
2330 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2332 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2333 if (shrinkedFirstColumnWidth
< minWidth
) {
2334 shrinkedFirstColumnWidth
= minWidth
;
2337 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2338 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2341 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2343 m_layouter
->setItemSize(dynamicItemSize
);
2345 // Update the role sizes for all visible widgets
2346 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2347 while (it
.hasNext()) {
2349 updateWidgetColumnWidths(it
.value());
2353 qreal
KItemListView::columnWidthsSum() const
2355 qreal widthsSum
= 0;
2356 foreach (const QByteArray
& role
, m_visibleRoles
) {
2357 widthsSum
+= m_headerWidget
->columnWidth(role
);
2362 QRectF
KItemListView::headerBoundaries() const
2364 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2367 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2368 const QSizeF
& newItemSize
,
2369 const QSizeF
& newItemMargin
) const
2371 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2375 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2376 const qreal itemWidth
= m_layouter
->itemSize().width();
2377 if (itemWidth
> 0) {
2378 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2379 newItemSize
.width(),
2380 newItemMargin
.width());
2381 if (m_model
->count() > newColumnCount
) {
2382 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2384 m_layouter
->itemMargin().width());
2385 return oldColumnCount
!= newColumnCount
;
2389 const qreal itemHeight
= m_layouter
->itemSize().height();
2390 if (itemHeight
> 0) {
2391 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2392 newItemSize
.height(),
2393 newItemMargin
.height());
2394 if (m_model
->count() > newRowCount
) {
2395 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2397 m_layouter
->itemMargin().height());
2398 return oldRowCount
!= newRowCount
;
2406 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2408 if (m_itemSize
.isEmpty()) {
2409 // We have only columns or only rows, but no grid: An animation is usually
2410 // welcome when inserting or removing items.
2411 return !supportsItemExpanding();
2414 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2418 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2419 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2420 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2421 // Only animate if up to 2/3 of a row or column are inserted or removed
2422 return changedItemCount
<= maximum
* 2 / 3;
2426 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2428 const QSizeF oldSize
= m_layouter
->size();
2430 m_layouter
->setSize(size
);
2431 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2432 m_layouter
->setSize(oldSize
);
2434 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2435 : maxOffset
> size
.width();
2438 int KItemListView::showDropIndicator(const QPointF
& pos
)
2440 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2441 while (it
.hasNext()) {
2443 const KItemListWidget
* widget
= it
.value();
2445 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2446 const QRectF rect
= itemRect(widget
->index());
2447 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2448 if (m_model
->supportsDropping(widget
->index())) {
2449 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2450 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2451 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2456 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2457 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2459 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2460 if (m_dropIndicator
!= draggingInsertIndicator
) {
2461 m_dropIndicator
= draggingInsertIndicator
;
2465 int index
= widget
->index();
2473 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2474 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2477 void KItemListView::hideDropIndicator()
2479 if (!m_dropIndicator
.isNull()) {
2480 m_dropIndicator
= QRectF();
2485 void KItemListView::updateGroupHeaderHeight()
2487 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2488 qreal groupHeaderMargin
= 0;
2490 if (scrollOrientation() == Qt::Horizontal
) {
2491 // The vertical margin above and below the header should be
2492 // equal to the horizontal margin, not the vertical margin
2493 // from m_styleOption.
2494 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2495 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2496 } else if (m_itemSize
.isEmpty()){
2497 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2498 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2500 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2501 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2503 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2504 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2506 updateVisibleGroupHeaders();
2509 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2511 if (!supportsItemExpanding() || !m_model
) {
2515 if (firstIndex
< 0 || lastIndex
< 0) {
2516 firstIndex
= m_layouter
->firstVisibleIndex();
2517 lastIndex
= m_layouter
->lastVisibleIndex();
2519 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2520 lastIndex
>= m_layouter
->firstVisibleIndex());
2521 if (!isRangeVisible
) {
2526 int previousParents
= 0;
2527 QBitArray previousSiblings
;
2529 // The rootIndex describes the first index where the siblings get
2530 // calculated from. For the calculation the upper most parent item
2531 // is required. For performance reasons it is checked first whether
2532 // the visible items before or after the current range already
2533 // contain a siblings information which can be used as base.
2534 int rootIndex
= firstIndex
;
2536 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2538 // There is no visible widget before the range, check whether there
2539 // is one after the range:
2540 widget
= m_visibleItems
.value(lastIndex
+ 1);
2542 // The sibling information of the widget may only be used if
2543 // all items of the range have the same number of parents.
2544 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2545 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2546 if (m_model
->expandedParentsCount(i
) != parents
) {
2555 // Performance optimization: Use the sibling information of the visible
2556 // widget beside the given range.
2557 previousSiblings
= widget
->siblingsInformation();
2558 if (previousSiblings
.isEmpty()) {
2561 previousParents
= previousSiblings
.count() - 1;
2562 previousSiblings
.truncate(previousParents
);
2564 // Potentially slow path: Go back to the upper most parent of firstIndex
2565 // to be able to calculate the initial value for the siblings.
2566 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2571 Q_ASSERT(previousParents
>= 0);
2572 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2573 // Update the parent-siblings in case if the current item represents
2574 // a child or an upper parent.
2575 const int currentParents
= m_model
->expandedParentsCount(i
);
2576 Q_ASSERT(currentParents
>= 0);
2577 if (previousParents
< currentParents
) {
2578 previousParents
= currentParents
;
2579 previousSiblings
.resize(currentParents
);
2580 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2581 } else if (previousParents
> currentParents
) {
2582 previousParents
= currentParents
;
2583 previousSiblings
.truncate(currentParents
);
2586 if (i
>= firstIndex
) {
2587 // The index represents a visible item. Apply the parent-siblings
2588 // and update the sibling of the current item.
2589 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2594 QBitArray siblings
= previousSiblings
;
2595 siblings
.resize(siblings
.count() + 1);
2596 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2598 widget
->setSiblingsInformation(siblings
);
2603 bool KItemListView::hasSiblingSuccessor(int index
) const
2605 bool hasSuccessor
= false;
2606 const int parentsCount
= m_model
->expandedParentsCount(index
);
2607 int successorIndex
= index
+ 1;
2609 // Search the next sibling
2610 const int itemCount
= m_model
->count();
2611 while (successorIndex
< itemCount
) {
2612 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2613 if (currentParentsCount
== parentsCount
) {
2614 hasSuccessor
= true;
2616 } else if (currentParentsCount
< parentsCount
) {
2622 if (m_grouped
&& hasSuccessor
) {
2623 // If the sibling is part of another group, don't mark it as
2624 // successor as the group header is between the sibling connections.
2625 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2626 if (m_layouter
->isFirstGroupItem(i
)) {
2627 hasSuccessor
= false;
2633 return hasSuccessor
;
2636 void KItemListView::disconnectRoleEditingSignals(int index
)
2638 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2643 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2644 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2645 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2648 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2652 const int minSpeed
= 4;
2653 const int maxSpeed
= 128;
2654 const int speedLimiter
= 96;
2655 const int autoScrollBorder
= 64;
2657 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2658 // This assures that the autoscrolling speed grows gradually.
2659 const int incLimiter
= 1;
2661 if (pos
< autoScrollBorder
) {
2662 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2663 inc
= qMax(inc
, -maxSpeed
);
2664 inc
= qMax(inc
, oldInc
- incLimiter
);
2665 } else if (pos
> range
- autoScrollBorder
) {
2666 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2667 inc
= qMin(inc
, maxSpeed
);
2668 inc
= qMin(inc
, oldInc
+ incLimiter
);
2674 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2676 const qreal availableSize
= size
- itemMargin
;
2677 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2683 KItemListCreatorBase::~KItemListCreatorBase()
2685 qDeleteAll(m_recycleableWidgets
);
2686 qDeleteAll(m_createdWidgets
);
2689 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2691 m_createdWidgets
.insert(widget
);
2694 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2696 Q_ASSERT(m_createdWidgets
.contains(widget
));
2697 m_createdWidgets
.remove(widget
);
2699 if (m_recycleableWidgets
.count() < 100) {
2700 m_recycleableWidgets
.append(widget
);
2701 widget
->setVisible(false);
2707 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2709 if (m_recycleableWidgets
.isEmpty()) {
2713 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2714 m_createdWidgets
.insert(widget
);
2718 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2722 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2724 widget
->setParentItem(nullptr);
2725 widget
->setOpacity(1.0);
2726 pushRecycleableWidget(widget
);
2729 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2733 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2735 header
->setOpacity(1.0);
2736 pushRecycleableWidget(header
);