1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "dolphindebug.h"
26 #include "kitemlistcontainer.h"
27 #include "kitemlistcontroller.h"
28 #include "kitemlistheader.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistviewaccessible.h"
31 #include "kstandarditemlistwidget.h"
33 #include "private/kitemlistheaderwidget.h"
34 #include "private/kitemlistrubberband.h"
35 #include "private/kitemlistsizehintresolver.h"
36 #include "private/kitemlistviewlayouter.h"
38 #include <QElapsedTimer>
39 #include <QGraphicsSceneMouseEvent>
40 #include <QGraphicsView>
41 #include <QStyleOptionRubberBand>
46 // Time in ms until reaching the autoscroll margin triggers
47 // an initial autoscrolling
48 const int InitialAutoScrollDelay
= 700;
50 // Delay in ms for triggering the next autoscroll
51 const int RepeatingAutoScrollDelay
= 1000 / 60;
54 #ifndef QT_NO_ACCESSIBILITY
55 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
59 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
60 return new KItemListContainerAccessible(container
);
61 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
62 return new KItemListViewAccessible(view
);
69 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
70 QGraphicsWidget(parent
),
71 m_enabledSelectionToggles(false),
73 m_supportsItemExpanding(false),
75 m_activeTransactions(0),
76 m_endTransactionAnimationHint(Animation
),
78 m_controller(nullptr),
81 m_widgetCreator(nullptr),
82 m_groupHeaderCreator(nullptr),
87 m_sizeHintResolver(nullptr),
90 m_layoutTimer(nullptr),
92 m_oldMaximumScrollOffset(0),
94 m_oldMaximumItemOffset(0),
95 m_skipAutoScrollForRubberBand(false),
96 m_rubberBand(nullptr),
98 m_autoScrollIncrement(0),
99 m_autoScrollTimer(nullptr),
101 m_headerWidget(nullptr),
104 setAcceptHoverEvents(true);
106 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
108 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
110 m_animation
= new KItemListViewAnimation(this);
111 connect(m_animation
, &KItemListViewAnimation::finished
,
112 this, &KItemListView::slotAnimationFinished
);
114 m_layoutTimer
= new QTimer(this);
115 m_layoutTimer
->setInterval(300);
116 m_layoutTimer
->setSingleShot(true);
117 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
119 m_rubberBand
= new KItemListRubberBand(this);
120 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
122 m_headerWidget
= new KItemListHeaderWidget(this);
123 m_headerWidget
->setVisible(false);
125 m_header
= new KItemListHeader(this);
127 #ifndef QT_NO_ACCESSIBILITY
128 QAccessible::installFactory(accessibleInterfaceFactory
);
133 KItemListView::~KItemListView()
135 // The group headers are children of the widgets created by
136 // widgetCreator(). So it is mandatory to delete the group headers
138 delete m_groupHeaderCreator
;
139 m_groupHeaderCreator
= nullptr;
141 delete m_widgetCreator
;
142 m_widgetCreator
= nullptr;
144 delete m_sizeHintResolver
;
145 m_sizeHintResolver
= nullptr;
148 void KItemListView::setScrollOffset(qreal offset
)
154 const qreal previousOffset
= m_layouter
->scrollOffset();
155 if (offset
== previousOffset
) {
159 m_layouter
->setScrollOffset(offset
);
160 m_animation
->setScrollOffset(offset
);
162 // Don't check whether the m_layoutTimer is active: Changing the
163 // scroll offset must always trigger a synchronous layout, otherwise
164 // the smooth-scrolling might get jerky.
165 doLayout(NoAnimation
);
166 onScrollOffsetChanged(offset
, previousOffset
);
169 qreal
KItemListView::scrollOffset() const
171 return m_layouter
->scrollOffset();
174 qreal
KItemListView::maximumScrollOffset() const
176 return m_layouter
->maximumScrollOffset();
179 void KItemListView::setItemOffset(qreal offset
)
181 if (m_layouter
->itemOffset() == offset
) {
185 m_layouter
->setItemOffset(offset
);
186 if (m_headerWidget
->isVisible()) {
187 m_headerWidget
->setOffset(offset
);
190 // Don't check whether the m_layoutTimer is active: Changing the
191 // item offset must always trigger a synchronous layout, otherwise
192 // the smooth-scrolling might get jerky.
193 doLayout(NoAnimation
);
196 qreal
KItemListView::itemOffset() const
198 return m_layouter
->itemOffset();
201 qreal
KItemListView::maximumItemOffset() const
203 return m_layouter
->maximumItemOffset();
206 int KItemListView::maximumVisibleItems() const
208 return m_layouter
->maximumVisibleItems();
211 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
213 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
214 m_visibleRoles
= roles
;
215 onVisibleRolesChanged(roles
, previousRoles
);
217 m_sizeHintResolver
->clearCache();
218 m_layouter
->markAsDirty();
220 if (m_itemSize
.isEmpty()) {
221 m_headerWidget
->setColumns(roles
);
222 updatePreferredColumnWidths();
223 if (!m_headerWidget
->automaticColumnResizing()) {
224 // The column-width of new roles are still 0. Apply the preferred
225 // column-width as default with.
226 foreach (const QByteArray
& role
, m_visibleRoles
) {
227 if (m_headerWidget
->columnWidth(role
) == 0) {
228 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
229 m_headerWidget
->setColumnWidth(role
, width
);
233 applyColumnWidthsFromHeader();
237 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
238 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
239 (roles
.count() <= 1 && previousRoles
.count() > 1));
241 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
242 while (it
.hasNext()) {
244 KItemListWidget
* widget
= it
.value();
245 widget
->setVisibleRoles(roles
);
246 if (alternateBackgroundsChanged
) {
247 updateAlternateBackgroundForWidget(widget
);
251 doLayout(NoAnimation
);
254 QList
<QByteArray
> KItemListView::visibleRoles() const
256 return m_visibleRoles
;
259 void KItemListView::setAutoScroll(bool enabled
)
261 if (enabled
&& !m_autoScrollTimer
) {
262 m_autoScrollTimer
= new QTimer(this);
263 m_autoScrollTimer
->setSingleShot(true);
264 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
265 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
266 } else if (!enabled
&& m_autoScrollTimer
) {
267 delete m_autoScrollTimer
;
268 m_autoScrollTimer
= nullptr;
272 bool KItemListView::autoScroll() const
274 return m_autoScrollTimer
!= nullptr;
277 void KItemListView::setEnabledSelectionToggles(bool enabled
)
279 if (m_enabledSelectionToggles
!= enabled
) {
280 m_enabledSelectionToggles
= enabled
;
282 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
283 while (it
.hasNext()) {
285 it
.value()->setEnabledSelectionToggle(enabled
);
290 bool KItemListView::enabledSelectionToggles() const
292 return m_enabledSelectionToggles
;
295 KItemListController
* KItemListView::controller() const
300 KItemModelBase
* KItemListView::model() const
305 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
307 delete m_widgetCreator
;
308 m_widgetCreator
= widgetCreator
;
311 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
313 if (!m_widgetCreator
) {
314 m_widgetCreator
= defaultWidgetCreator();
316 return m_widgetCreator
;
319 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
321 delete m_groupHeaderCreator
;
322 m_groupHeaderCreator
= groupHeaderCreator
;
325 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
327 if (!m_groupHeaderCreator
) {
328 m_groupHeaderCreator
= defaultGroupHeaderCreator();
330 return m_groupHeaderCreator
;
333 QSizeF
KItemListView::itemSize() const
338 QSizeF
KItemListView::itemSizeHint() const
340 return m_sizeHintResolver
->minSizeHint();
343 const KItemListStyleOption
& KItemListView::styleOption() const
345 return m_styleOption
;
348 void KItemListView::setGeometry(const QRectF
& rect
)
350 QGraphicsWidget::setGeometry(rect
);
356 const QSizeF newSize
= rect
.size();
357 if (m_itemSize
.isEmpty()) {
358 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
359 if (m_headerWidget
->automaticColumnResizing()) {
360 applyAutomaticColumnWidths();
362 const qreal requiredWidth
= columnWidthsSum();
363 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
364 m_itemSize
.height());
365 m_layouter
->setItemSize(dynamicItemSize
);
368 // Triggering a synchronous layout is fine from a performance point of view,
369 // as with dynamic item sizes no moving animation must be done.
370 m_layouter
->setSize(newSize
);
371 doLayout(NoAnimation
);
373 const bool animate
= !changesItemGridLayout(newSize
,
374 m_layouter
->itemSize(),
375 m_layouter
->itemMargin());
376 m_layouter
->setSize(newSize
);
379 // Trigger an asynchronous relayout with m_layoutTimer to prevent
380 // performance bottlenecks. If the timer is exceeded, an animated layout
381 // will be triggered.
382 if (!m_layoutTimer
->isActive()) {
383 m_layoutTimer
->start();
386 m_layoutTimer
->stop();
387 doLayout(NoAnimation
);
392 qreal
KItemListView::verticalPageStep() const
394 qreal headerHeight
= 0;
395 if (m_headerWidget
->isVisible()) {
396 headerHeight
= m_headerWidget
->size().height();
398 return size().height() - headerHeight
;
401 int KItemListView::itemAt(const QPointF
& pos
) const
403 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
404 while (it
.hasNext()) {
407 const KItemListWidget
* widget
= it
.value();
408 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
409 if (widget
->contains(mappedPos
)) {
417 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
419 if (!m_enabledSelectionToggles
) {
423 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
425 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
426 if (!selectionToggleRect
.isEmpty()) {
427 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
428 return selectionToggleRect
.contains(mappedPos
);
434 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
436 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
438 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
439 if (!expansionToggleRect
.isEmpty()) {
440 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
441 return expansionToggleRect
.contains(mappedPos
);
447 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
449 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
451 const QRectF
&textRect
= widget
->textRect();
452 if (!textRect
.isEmpty()) {
453 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
454 return textRect
.contains(mappedPos
);
460 int KItemListView::firstVisibleIndex() const
462 return m_layouter
->firstVisibleIndex();
465 int KItemListView::lastVisibleIndex() const
467 return m_layouter
->lastVisibleIndex();
470 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
472 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
475 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
477 if (m_supportsItemExpanding
!= supportsExpanding
) {
478 m_supportsItemExpanding
= supportsExpanding
;
479 updateSiblingsInformation();
480 onSupportsItemExpandingChanged(supportsExpanding
);
484 bool KItemListView::supportsItemExpanding() const
486 return m_supportsItemExpanding
;
489 QRectF
KItemListView::itemRect(int index
) const
491 return m_layouter
->itemRect(index
);
494 QRectF
KItemListView::itemContextRect(int index
) const
498 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
500 contextRect
= widget
->iconRect() | widget
->textRect();
501 contextRect
.translate(itemRect(index
).topLeft());
507 void KItemListView::scrollToItem(int index
)
509 QRectF viewGeometry
= geometry();
510 if (m_headerWidget
->isVisible()) {
511 const qreal headerHeight
= m_headerWidget
->size().height();
512 viewGeometry
.adjust(0, headerHeight
, 0, 0);
514 QRectF currentRect
= itemRect(index
);
516 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
517 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
518 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
520 if (!viewGeometry
.contains(currentRect
)) {
521 qreal newOffset
= scrollOffset();
522 if (scrollOrientation() == Qt::Vertical
) {
523 if (currentRect
.top() < viewGeometry
.top()) {
524 newOffset
+= currentRect
.top() - viewGeometry
.top();
525 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
526 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
529 if (currentRect
.left() < viewGeometry
.left()) {
530 newOffset
+= currentRect
.left() - viewGeometry
.left();
531 } else if (currentRect
.right() > viewGeometry
.right()) {
532 newOffset
+= currentRect
.right() - viewGeometry
.right();
536 if (newOffset
!= scrollOffset()) {
537 emit
scrollTo(newOffset
);
542 void KItemListView::beginTransaction()
544 ++m_activeTransactions
;
545 if (m_activeTransactions
== 1) {
546 onTransactionBegin();
550 void KItemListView::endTransaction()
552 --m_activeTransactions
;
553 if (m_activeTransactions
< 0) {
554 m_activeTransactions
= 0;
555 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
558 if (m_activeTransactions
== 0) {
560 doLayout(m_endTransactionAnimationHint
);
561 m_endTransactionAnimationHint
= Animation
;
565 bool KItemListView::isTransactionActive() const
567 return m_activeTransactions
> 0;
570 void KItemListView::setHeaderVisible(bool visible
)
572 if (visible
&& !m_headerWidget
->isVisible()) {
573 QStyleOptionHeader option
;
574 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
577 m_headerWidget
->setPos(0, 0);
578 m_headerWidget
->resize(size().width(), headerSize
.height());
579 m_headerWidget
->setModel(m_model
);
580 m_headerWidget
->setColumns(m_visibleRoles
);
581 m_headerWidget
->setZValue(1);
583 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
584 this, &KItemListView::slotHeaderColumnWidthChanged
);
585 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
586 this, &KItemListView::slotHeaderColumnMoved
);
587 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
588 this, &KItemListView::sortOrderChanged
);
589 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
590 this, &KItemListView::sortRoleChanged
);
592 m_layouter
->setHeaderHeight(headerSize
.height());
593 m_headerWidget
->setVisible(true);
594 } else if (!visible
&& m_headerWidget
->isVisible()) {
595 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
596 this, &KItemListView::slotHeaderColumnWidthChanged
);
597 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
598 this, &KItemListView::slotHeaderColumnMoved
);
599 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
600 this, &KItemListView::sortOrderChanged
);
601 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
602 this, &KItemListView::sortRoleChanged
);
604 m_layouter
->setHeaderHeight(0);
605 m_headerWidget
->setVisible(false);
609 bool KItemListView::isHeaderVisible() const
611 return m_headerWidget
->isVisible();
614 KItemListHeader
* KItemListView::header() const
619 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
623 if (indexes
.count() == 1) {
624 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
625 QGraphicsView
* graphicsView
= scene()->views()[0];
626 if (item
&& graphicsView
) {
627 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
630 // TODO: Not implemented yet. Probably extend the interface
631 // from KItemListWidget::createDragPixmap() to return a pixmap
632 // that can be used for multiple indexes.
638 void KItemListView::editRole(int index
, const QByteArray
& role
)
640 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
641 if (!widget
|| m_editingRole
) {
645 m_editingRole
= true;
646 widget
->setEditedRole(role
);
648 connect(widget
, &KItemListWidget::roleEditingCanceled
,
649 this, &KItemListView::slotRoleEditingCanceled
);
650 connect(widget
, &KItemListWidget::roleEditingFinished
,
651 this, &KItemListView::slotRoleEditingFinished
);
653 connect(this, &KItemListView::scrollOffsetChanged
,
654 widget
, &KStandardItemListWidget::finishRoleEditing
);
657 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
659 QGraphicsWidget::paint(painter
, option
, widget
);
661 if (m_rubberBand
->isActive()) {
662 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
663 m_rubberBand
->endPosition()).normalized();
665 const QPointF topLeft
= rubberBandRect
.topLeft();
666 if (scrollOrientation() == Qt::Vertical
) {
667 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
669 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
672 QStyleOptionRubberBand opt
;
673 initStyleOption(&opt
);
674 opt
.shape
= QRubberBand::Rectangle
;
676 opt
.rect
= rubberBandRect
.toRect();
677 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
680 if (!m_dropIndicator
.isEmpty()) {
681 const QRectF r
= m_dropIndicator
.toRect();
683 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
684 painter
->setPen(color
);
686 // TODO: The following implementation works only for a vertical scroll-orientation
687 // and assumes a height of the m_draggingInsertIndicator of 1.
688 Q_ASSERT(r
.height() == 1);
689 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
692 painter
->setPen(color
);
693 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
697 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
699 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
700 if (!scene()->views().isEmpty()) {
701 m_styleOption
.palette
= scene()->views().at(0)->palette();
704 return QGraphicsItem::itemChange(change
, value
);
707 void KItemListView::setItemSize(const QSizeF
& size
)
709 const QSizeF previousSize
= m_itemSize
;
710 if (size
== previousSize
) {
714 // Skip animations when the number of rows or columns
715 // are changed in the grid layout. Although the animation
716 // engine can handle this usecase, it looks obtrusive.
717 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
719 m_layouter
->itemMargin());
721 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
722 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
723 (!m_itemSize
.isEmpty() && size
.isEmpty()));
727 if (alternateBackgroundsChanged
) {
728 // For an empty item size alternate backgrounds are drawn if more than
729 // one role is shown. Assure that the backgrounds for visible items are
730 // updated when changing the size in this context.
731 updateAlternateBackgrounds();
734 if (size
.isEmpty()) {
735 if (m_headerWidget
->automaticColumnResizing()) {
736 updatePreferredColumnWidths();
738 // Only apply the changed height and respect the header widths
740 const qreal currentWidth
= m_layouter
->itemSize().width();
741 const QSizeF
newSize(currentWidth
, size
.height());
742 m_layouter
->setItemSize(newSize
);
745 m_layouter
->setItemSize(size
);
748 m_sizeHintResolver
->clearCache();
749 doLayout(animate
? Animation
: NoAnimation
);
750 onItemSizeChanged(size
, previousSize
);
753 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
755 if (m_styleOption
== option
) {
759 const KItemListStyleOption previousOption
= m_styleOption
;
760 m_styleOption
= option
;
763 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
764 if (margin
!= m_layouter
->itemMargin()) {
765 // Skip animations when the number of rows or columns
766 // are changed in the grid layout. Although the animation
767 // engine can handle this usecase, it looks obtrusive.
768 animate
= !changesItemGridLayout(m_layouter
->size(),
769 m_layouter
->itemSize(),
771 m_layouter
->setItemMargin(margin
);
775 updateGroupHeaderHeight();
779 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
780 // Animating a change of the maximum text size just results in expensive
781 // temporary eliding and clipping operations and does not look good visually.
785 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
786 while (it
.hasNext()) {
788 it
.value()->setStyleOption(option
);
791 m_sizeHintResolver
->clearCache();
792 m_layouter
->markAsDirty();
793 doLayout(animate
? Animation
: NoAnimation
);
795 if (m_itemSize
.isEmpty()) {
796 updatePreferredColumnWidths();
799 onStyleOptionChanged(option
, previousOption
);
802 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
804 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
805 if (orientation
== previousOrientation
) {
809 m_layouter
->setScrollOrientation(orientation
);
810 m_animation
->setScrollOrientation(orientation
);
811 m_sizeHintResolver
->clearCache();
814 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
815 while (it
.hasNext()) {
817 it
.value()->setScrollOrientation(orientation
);
819 updateGroupHeaderHeight();
823 doLayout(NoAnimation
);
825 onScrollOrientationChanged(orientation
, previousOrientation
);
826 emit
scrollOrientationChanged(orientation
, previousOrientation
);
829 Qt::Orientation
KItemListView::scrollOrientation() const
831 return m_layouter
->scrollOrientation();
834 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
839 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
844 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
849 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
851 Q_UNUSED(changedRoles
)
855 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
861 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
867 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
873 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
879 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
885 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
891 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
897 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
899 Q_UNUSED(supportsExpanding
)
902 void KItemListView::onTransactionBegin()
906 void KItemListView::onTransactionEnd()
910 bool KItemListView::event(QEvent
* event
)
912 switch (event
->type()) {
913 case QEvent::PaletteChange
:
917 case QEvent::FontChange
:
922 // Forward all other events to the controller and handle them there
923 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
929 return QGraphicsWidget::event(event
);
932 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
934 m_mousePos
= transform().map(event
->pos());
938 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
940 QGraphicsWidget::mouseMoveEvent(event
);
942 m_mousePos
= transform().map(event
->pos());
943 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
944 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
948 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
950 event
->setAccepted(true);
954 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
956 QGraphicsWidget::dragMoveEvent(event
);
958 m_mousePos
= transform().map(event
->pos());
959 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
960 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
964 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
966 QGraphicsWidget::dragLeaveEvent(event
);
967 setAutoScroll(false);
970 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
972 QGraphicsWidget::dropEvent(event
);
973 setAutoScroll(false);
976 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
978 return m_visibleItems
.values();
981 void KItemListView::updateFont()
983 if (scene() && !scene()->views().isEmpty()) {
984 KItemListStyleOption option
= styleOption();
985 option
.font
= scene()->views().first()->font();
986 option
.fontMetrics
= QFontMetrics(option
.font
);
988 setStyleOption(option
);
992 void KItemListView::updatePalette()
994 if (scene() && !scene()->views().isEmpty()) {
995 KItemListStyleOption option
= styleOption();
996 option
.palette
= scene()->views().first()->palette();
998 setStyleOption(option
);
1002 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1004 if (m_itemSize
.isEmpty()) {
1005 updatePreferredColumnWidths(itemRanges
);
1008 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1009 if (hasMultipleRanges
) {
1013 m_layouter
->markAsDirty();
1015 m_sizeHintResolver
->itemsInserted(itemRanges
);
1017 int previouslyInsertedCount
= 0;
1018 foreach (const KItemRange
& range
, itemRanges
) {
1019 // range.index is related to the model before anything has been inserted.
1020 // As in each loop the current item-range gets inserted the index must
1021 // be increased by the already previously inserted items.
1022 const int index
= range
.index
+ previouslyInsertedCount
;
1023 const int count
= range
.count
;
1024 if (index
< 0 || count
<= 0) {
1025 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1028 previouslyInsertedCount
+= count
;
1030 // Determine which visible items must be moved
1031 QList
<int> itemsToMove
;
1032 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1033 while (it
.hasNext()) {
1035 const int visibleItemIndex
= it
.key();
1036 if (visibleItemIndex
>= index
) {
1037 itemsToMove
.append(visibleItemIndex
);
1041 // Update the indexes of all KItemListWidget instances that are located
1042 // after the inserted items. It is important to adjust the indexes in the order
1043 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1044 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1045 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1046 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1048 const int newIndex
= widget
->index() + count
;
1049 if (hasMultipleRanges
) {
1050 setWidgetIndex(widget
, newIndex
);
1052 // Try to animate the moving of the item
1053 moveWidgetToIndex(widget
, newIndex
);
1057 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1058 // Check whether a scrollbar is required to show the inserted items. In this case
1059 // the size of the layouter will be decreased before calling doLayout(): This prevents
1060 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1061 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1062 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1063 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1064 if (decreaseLayouterSize
) {
1065 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1067 int scrollbarSpacing
= 0;
1068 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1069 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1072 QSizeF layouterSize
= m_layouter
->size();
1073 if (verticalScrollOrientation
) {
1074 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1076 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1078 m_layouter
->setSize(layouterSize
);
1082 if (!hasMultipleRanges
) {
1083 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1084 updateSiblingsInformation();
1089 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1092 if (hasMultipleRanges
) {
1093 m_endTransactionAnimationHint
= NoAnimation
;
1096 updateSiblingsInformation();
1099 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1100 // In case if items of the same group have been inserted before an item that
1101 // currently represents the first item of the group, the group header of
1102 // this item must be removed.
1103 updateVisibleGroupHeaders();
1106 if (useAlternateBackgrounds()) {
1107 updateAlternateBackgrounds();
1111 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1113 if (m_itemSize
.isEmpty()) {
1114 // Don't pass the item-range: The preferred column-widths of
1115 // all items must be adjusted when removing items.
1116 updatePreferredColumnWidths();
1119 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1120 if (hasMultipleRanges
) {
1124 m_layouter
->markAsDirty();
1126 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1128 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1129 const KItemRange
& range
= itemRanges
[i
];
1130 const int index
= range
.index
;
1131 const int count
= range
.count
;
1132 if (index
< 0 || count
<= 0) {
1133 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1137 const int firstRemovedIndex
= index
;
1138 const int lastRemovedIndex
= index
+ count
- 1;
1140 // Remember which items have to be moved because they are behind the removed range.
1141 QVector
<int> itemsToMove
;
1143 // Remove all KItemListWidget instances that got deleted
1144 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1145 const int i
= widget
->index();
1146 if (i
< firstRemovedIndex
) {
1148 } else if (i
> lastRemovedIndex
) {
1149 itemsToMove
.append(i
);
1153 m_animation
->stop(widget
);
1154 // Stopping the animation might lead to recycling the widget if
1155 // it is invisible (see slotAnimationFinished()).
1156 // Check again whether it is still visible:
1157 if (!m_visibleItems
.contains(i
)) {
1161 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1162 // Remove the widget without animation
1163 recycleWidget(widget
);
1165 // Animate the removing of the items. Special case: When removing an item there
1166 // is no valid model index available anymore. For the
1167 // remove-animation the item gets removed from m_visibleItems but the widget
1168 // will stay alive until the animation has been finished and will
1169 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1170 m_visibleItems
.remove(i
);
1171 widget
->setIndex(-1);
1172 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1176 // Update the indexes of all KItemListWidget instances that are located
1177 // after the deleted items. It is important to update them in ascending
1178 // order to prevent overlaps when setting the new index.
1179 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1180 foreach (int i
, itemsToMove
) {
1181 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1183 const int newIndex
= i
- count
;
1184 if (hasMultipleRanges
) {
1185 setWidgetIndex(widget
, newIndex
);
1187 // Try to animate the moving of the item
1188 moveWidgetToIndex(widget
, newIndex
);
1192 if (!hasMultipleRanges
) {
1193 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1194 // assumes an updated geometry. If items are removed during an active transaction,
1195 // the transaction will be temporary deactivated so that doLayout() triggers a
1196 // geometry update if necessary.
1197 const int activeTransactions
= m_activeTransactions
;
1198 m_activeTransactions
= 0;
1199 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1200 m_activeTransactions
= activeTransactions
;
1201 updateSiblingsInformation();
1206 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1209 if (hasMultipleRanges
) {
1210 m_endTransactionAnimationHint
= NoAnimation
;
1212 updateSiblingsInformation();
1215 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1216 // In case if the first item of a group has been removed, the group header
1217 // must be applied to the next visible item.
1218 updateVisibleGroupHeaders();
1221 if (useAlternateBackgrounds()) {
1222 updateAlternateBackgrounds();
1226 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1228 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1229 m_layouter
->markAsDirty();
1232 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1235 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1236 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1238 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1239 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1241 updateWidgetProperties(widget
, index
);
1242 initializeItemListWidget(widget
);
1246 doLayout(NoAnimation
);
1247 updateSiblingsInformation();
1250 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1251 const QSet
<QByteArray
>& roles
)
1253 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1254 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1255 updatePreferredColumnWidths(itemRanges
);
1258 foreach (const KItemRange
& itemRange
, itemRanges
) {
1259 const int index
= itemRange
.index
;
1260 const int count
= itemRange
.count
;
1262 if (updateSizeHints
) {
1263 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1264 m_layouter
->markAsDirty();
1266 if (!m_layoutTimer
->isActive()) {
1267 m_layoutTimer
->start();
1271 // Apply the changed roles to the visible item-widgets
1272 const int lastIndex
= index
+ count
- 1;
1273 for (int i
= index
; i
<= lastIndex
; ++i
) {
1274 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1276 widget
->setData(m_model
->data(i
), roles
);
1280 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1281 // The sort-role has been changed which might result
1282 // in modified group headers
1283 updateVisibleGroupHeaders();
1284 doLayout(NoAnimation
);
1287 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1288 ev
.setFirstRow(itemRange
.index
);
1289 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1290 QAccessible::updateAccessibility(&ev
);
1294 void KItemListView::slotGroupsChanged()
1296 updateVisibleGroupHeaders();
1297 doLayout(NoAnimation
);
1298 updateSiblingsInformation();
1301 void KItemListView::slotGroupedSortingChanged(bool current
)
1303 m_grouped
= current
;
1304 m_layouter
->markAsDirty();
1307 updateGroupHeaderHeight();
1309 // Clear all visible headers. Note that the QHashIterator takes a copy of
1310 // m_visibleGroups. Therefore, it remains valid even if items are removed
1311 // from m_visibleGroups in recycleGroupHeaderForWidget().
1312 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1313 while (it
.hasNext()) {
1315 recycleGroupHeaderForWidget(it
.key());
1317 Q_ASSERT(m_visibleGroups
.isEmpty());
1320 if (useAlternateBackgrounds()) {
1321 // Changing the group mode requires to update the alternate backgrounds
1322 // as with the enabled group mode the altering is done on base of the first
1324 updateAlternateBackgrounds();
1326 updateSiblingsInformation();
1327 doLayout(NoAnimation
);
1330 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1335 updateVisibleGroupHeaders();
1336 doLayout(NoAnimation
);
1340 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1345 updateVisibleGroupHeaders();
1346 doLayout(NoAnimation
);
1350 void KItemListView::slotCurrentChanged(int current
, int previous
)
1354 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1355 // always the selected item. It is not necessary to highlight the current item then.
1356 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1357 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1358 if (previousWidget
) {
1359 previousWidget
->setCurrent(false);
1362 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1363 if (currentWidget
) {
1364 currentWidget
->setCurrent(true);
1368 QAccessibleEvent
ev(this, QAccessible::Focus
);
1369 ev
.setChild(current
);
1370 QAccessible::updateAccessibility(&ev
);
1373 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1377 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1378 while (it
.hasNext()) {
1380 const int index
= it
.key();
1381 KItemListWidget
* widget
= it
.value();
1382 widget
->setSelected(current
.contains(index
));
1386 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1387 KItemListViewAnimation::AnimationType type
)
1389 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1390 Q_ASSERT(itemListWidget
);
1393 case KItemListViewAnimation::DeleteAnimation
: {
1394 // As we recycle the widget in this case it is important to assure that no
1395 // other animation has been started. This is a convention in KItemListView and
1396 // not a requirement defined by KItemListViewAnimation.
1397 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1399 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1400 // by m_visibleWidgets and must be deleted manually after the animation has
1402 recycleGroupHeaderForWidget(itemListWidget
);
1403 widgetCreator()->recycle(itemListWidget
);
1407 case KItemListViewAnimation::CreateAnimation
:
1408 case KItemListViewAnimation::MovingAnimation
:
1409 case KItemListViewAnimation::ResizeAnimation
: {
1410 const int index
= itemListWidget
->index();
1411 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1412 (index
> m_layouter
->lastVisibleIndex());
1413 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1414 recycleWidget(itemListWidget
);
1423 void KItemListView::slotLayoutTimerFinished()
1425 m_layouter
->setSize(geometry().size());
1426 doLayout(Animation
);
1429 void KItemListView::slotRubberBandPosChanged()
1434 void KItemListView::slotRubberBandActivationChanged(bool active
)
1437 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1438 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1439 m_skipAutoScrollForRubberBand
= true;
1441 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1442 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1443 m_skipAutoScrollForRubberBand
= false;
1449 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1451 qreal previousWidth
)
1454 Q_UNUSED(currentWidth
)
1455 Q_UNUSED(previousWidth
)
1457 m_headerWidget
->setAutomaticColumnResizing(false);
1458 applyColumnWidthsFromHeader();
1459 doLayout(NoAnimation
);
1462 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1466 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1468 const QList
<QByteArray
> previous
= m_visibleRoles
;
1470 QList
<QByteArray
> current
= m_visibleRoles
;
1471 current
.removeAt(previousIndex
);
1472 current
.insert(currentIndex
, role
);
1474 setVisibleRoles(current
);
1476 emit
visibleRolesChanged(current
, previous
);
1479 void KItemListView::triggerAutoScrolling()
1481 if (!m_autoScrollTimer
) {
1486 int visibleSize
= 0;
1487 if (scrollOrientation() == Qt::Vertical
) {
1488 pos
= m_mousePos
.y();
1489 visibleSize
= size().height();
1491 pos
= m_mousePos
.x();
1492 visibleSize
= size().width();
1495 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1496 m_autoScrollIncrement
= 0;
1499 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1500 if (m_autoScrollIncrement
== 0) {
1501 // The mouse position is not above an autoscroll margin (the autoscroll timer
1502 // will be restarted in mouseMoveEvent())
1503 m_autoScrollTimer
->stop();
1507 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1508 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1509 // if the direction of the rubberband is similar to the autoscroll direction. This
1510 // prevents that starting to create a rubberband within the autoscroll margins starts
1511 // an autoscrolling.
1513 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1514 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1515 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1516 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1517 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1518 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1519 // been moved up although the autoscroll direction might be down)
1520 m_autoScrollTimer
->stop();
1525 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1526 // the autoscrolling may not get skipped anymore until a new rubberband is created
1527 m_skipAutoScrollForRubberBand
= false;
1529 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1530 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1531 setScrollOffset(newScrollOffset
);
1533 // Trigger the autoscroll timer which will periodically call
1534 // triggerAutoScrolling()
1535 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1538 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1540 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1542 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1543 Q_ASSERT(groupHeader
);
1544 updateGroupHeaderLayout(widget
);
1547 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1549 disconnectRoleEditingSignals(index
);
1551 emit
roleEditingCanceled(index
, role
, value
);
1552 m_editingRole
= false;
1555 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1557 disconnectRoleEditingSignals(index
);
1559 emit
roleEditingFinished(index
, role
, value
);
1560 m_editingRole
= false;
1563 void KItemListView::setController(KItemListController
* controller
)
1565 if (m_controller
!= controller
) {
1566 KItemListController
* previous
= m_controller
;
1568 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1569 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1570 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1573 m_controller
= controller
;
1576 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1577 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1578 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1581 onControllerChanged(controller
, previous
);
1585 void KItemListView::setModel(KItemModelBase
* model
)
1587 if (m_model
== model
) {
1591 KItemModelBase
* previous
= m_model
;
1594 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1595 this, &KItemListView::slotItemsChanged
);
1596 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1597 this, &KItemListView::slotItemsInserted
);
1598 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1599 this, &KItemListView::slotItemsRemoved
);
1600 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1601 this, &KItemListView::slotItemsMoved
);
1602 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1603 this, &KItemListView::slotGroupsChanged
);
1604 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1605 this, &KItemListView::slotGroupedSortingChanged
);
1606 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1607 this, &KItemListView::slotSortOrderChanged
);
1608 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1609 this, &KItemListView::slotSortRoleChanged
);
1611 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1615 m_layouter
->setModel(model
);
1616 m_grouped
= model
->groupedSorting();
1619 connect(m_model
, &KItemModelBase::itemsChanged
,
1620 this, &KItemListView::slotItemsChanged
);
1621 connect(m_model
, &KItemModelBase::itemsInserted
,
1622 this, &KItemListView::slotItemsInserted
);
1623 connect(m_model
, &KItemModelBase::itemsRemoved
,
1624 this, &KItemListView::slotItemsRemoved
);
1625 connect(m_model
, &KItemModelBase::itemsMoved
,
1626 this, &KItemListView::slotItemsMoved
);
1627 connect(m_model
, &KItemModelBase::groupsChanged
,
1628 this, &KItemListView::slotGroupsChanged
);
1629 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1630 this, &KItemListView::slotGroupedSortingChanged
);
1631 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1632 this, &KItemListView::slotSortOrderChanged
);
1633 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1634 this, &KItemListView::slotSortRoleChanged
);
1636 const int itemCount
= m_model
->count();
1637 if (itemCount
> 0) {
1638 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1642 onModelChanged(model
, previous
);
1645 KItemListRubberBand
* KItemListView::rubberBand() const
1647 return m_rubberBand
;
1650 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1652 if (m_layoutTimer
->isActive()) {
1653 m_layoutTimer
->stop();
1656 if (m_activeTransactions
> 0) {
1657 if (hint
== NoAnimation
) {
1658 // As soon as at least one property change should be done without animation,
1659 // the whole transaction will be marked as not animated.
1660 m_endTransactionAnimationHint
= NoAnimation
;
1665 if (!m_model
|| m_model
->count() < 0) {
1669 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1670 if (firstVisibleIndex
< 0) {
1671 emitOffsetChanges();
1675 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1676 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1677 // is still shown if the maximum offset got decreased.
1678 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1679 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1680 if (scrollOffset() > maxOffsetToShowFullRange
) {
1681 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1682 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1685 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1687 int firstSibblingIndex
= -1;
1688 int lastSibblingIndex
= -1;
1689 const bool supportsExpanding
= supportsItemExpanding();
1691 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1693 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1694 // instances from invisible items are reused. If no reusable items are
1695 // found then new KItemListWidget instances get created.
1696 const bool animate
= (hint
== Animation
);
1697 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1698 bool applyNewPos
= true;
1699 bool wasHidden
= false;
1701 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1702 const QPointF newPos
= itemBounds
.topLeft();
1703 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1706 if (!reusableItems
.isEmpty()) {
1707 // Reuse a KItemListWidget instance from an invisible item
1708 const int oldIndex
= reusableItems
.takeLast();
1709 widget
= m_visibleItems
.value(oldIndex
);
1710 setWidgetIndex(widget
, i
);
1711 updateWidgetProperties(widget
, i
);
1712 initializeItemListWidget(widget
);
1714 // No reusable KItemListWidget instance is available, create a new one
1715 widget
= createWidget(i
);
1717 widget
->resize(itemBounds
.size());
1719 if (animate
&& changedCount
< 0) {
1720 // Items have been deleted.
1721 if (i
>= changedIndex
) {
1722 // The item is located behind the removed range. Move the
1723 // created item to the imaginary old position outside the
1724 // view. It will get animated to the new position later.
1725 const int previousIndex
= i
- changedCount
;
1726 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1727 if (itemRect
.isEmpty()) {
1728 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1729 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1730 widget
->setPos(invisibleOldPos
);
1732 widget
->setPos(itemRect
.topLeft());
1734 applyNewPos
= false;
1738 if (supportsExpanding
&& changedCount
== 0) {
1739 if (firstSibblingIndex
< 0) {
1740 firstSibblingIndex
= i
;
1742 lastSibblingIndex
= i
;
1747 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1748 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1749 applyNewPos
= false;
1752 const bool itemsRemoved
= (changedCount
< 0);
1753 const bool itemsInserted
= (changedCount
> 0);
1754 if (itemsRemoved
&& (i
>= changedIndex
)) {
1755 // The item is located after the removed items. Animate the moving of the position.
1756 applyNewPos
= !moveWidget(widget
, newPos
);
1757 } else if (itemsInserted
&& i
>= changedIndex
) {
1758 // The item is located after the first inserted item
1759 if (i
<= changedIndex
+ changedCount
- 1) {
1760 // The item is an inserted item. Animate the appearing of the item.
1761 // For performance reasons no animation is done when changedCount is equal
1762 // to all available items.
1763 if (changedCount
< m_model
->count()) {
1764 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1766 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1767 // The item was already there before, so animate the moving of the position.
1768 // No moving animation is done if the item is animated by a create animation: This
1769 // prevents a "move animation mess" when inserting several ranges in parallel.
1770 applyNewPos
= !moveWidget(widget
, newPos
);
1772 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1773 // The size of the view might have been changed. Animate the moving of the position.
1774 applyNewPos
= !moveWidget(widget
, newPos
);
1777 m_animation
->stop(widget
);
1781 widget
->setPos(newPos
);
1784 Q_ASSERT(widget
->index() == i
);
1785 widget
->setVisible(true);
1787 if (widget
->size() != itemBounds
.size()) {
1788 // Resize the widget for the item to the changed size.
1790 // If a dynamic item size is used then no animation is done in the direction
1791 // of the dynamic size.
1792 if (m_itemSize
.width() <= 0) {
1793 // The width is dynamic, apply the new width without animation.
1794 widget
->resize(itemBounds
.width(), widget
->size().height());
1795 } else if (m_itemSize
.height() <= 0) {
1796 // The height is dynamic, apply the new height without animation.
1797 widget
->resize(widget
->size().width(), itemBounds
.height());
1799 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1801 widget
->resize(itemBounds
.size());
1805 // Updating the cell-information must be done as last step: The decision whether the
1806 // moving-animation should be started at all is based on the previous cell-information.
1807 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1808 m_visibleCells
.insert(i
, cell
);
1811 // Delete invisible KItemListWidget instances that have not been reused
1812 foreach (int index
, reusableItems
) {
1813 recycleWidget(m_visibleItems
.value(index
));
1816 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1817 Q_ASSERT(lastSibblingIndex
>= 0);
1818 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1822 // Update the layout of all visible group headers
1823 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1824 while (it
.hasNext()) {
1826 updateGroupHeaderLayout(it
.key());
1830 emitOffsetChanges();
1833 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1834 int lastVisibleIndex
,
1835 LayoutAnimationHint hint
)
1837 // Determine all items that are completely invisible and might be
1838 // reused for items that just got (at least partly) visible. If the
1839 // animation hint is set to 'Animation' items that do e.g. an animated
1840 // moving of their position are not marked as invisible: This assures
1841 // that a scrolling inside the view can be done without breaking an animation.
1845 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1846 while (it
.hasNext()) {
1849 KItemListWidget
* widget
= it
.value();
1850 const int index
= widget
->index();
1851 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1854 if (m_animation
->isStarted(widget
)) {
1855 if (hint
== NoAnimation
) {
1856 // Stopping the animation will call KItemListView::slotAnimationFinished()
1857 // and the widget will be recycled if necessary there.
1858 m_animation
->stop(widget
);
1861 widget
->setVisible(false);
1862 items
.append(index
);
1865 recycleGroupHeaderForWidget(widget
);
1874 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1876 if (widget
->pos() == newPos
) {
1880 bool startMovingAnim
= false;
1882 if (m_itemSize
.isEmpty()) {
1883 // The items are not aligned in a grid but either as columns or rows.
1884 startMovingAnim
= true;
1886 // When having a grid the moving-animation should only be started, if it is done within
1887 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1888 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1889 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1890 const int index
= widget
->index();
1891 const Cell cell
= m_visibleCells
.value(index
);
1892 if (cell
.column
>= 0 && cell
.row
>= 0) {
1893 if (scrollOrientation() == Qt::Vertical
) {
1894 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1896 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1901 if (startMovingAnim
) {
1902 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1906 m_animation
->stop(widget
);
1907 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1911 void KItemListView::emitOffsetChanges()
1913 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1914 if (m_oldScrollOffset
!= newScrollOffset
) {
1915 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1916 m_oldScrollOffset
= newScrollOffset
;
1919 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1920 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1921 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1922 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1925 const qreal newItemOffset
= m_layouter
->itemOffset();
1926 if (m_oldItemOffset
!= newItemOffset
) {
1927 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1928 m_oldItemOffset
= newItemOffset
;
1931 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1932 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1933 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1934 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1938 KItemListWidget
* KItemListView::createWidget(int index
)
1940 KItemListWidget
* widget
= widgetCreator()->create(this);
1941 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1943 m_visibleItems
.insert(index
, widget
);
1944 m_visibleCells
.insert(index
, Cell());
1945 updateWidgetProperties(widget
, index
);
1946 initializeItemListWidget(widget
);
1950 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1953 recycleGroupHeaderForWidget(widget
);
1956 const int index
= widget
->index();
1957 m_visibleItems
.remove(index
);
1958 m_visibleCells
.remove(index
);
1960 widgetCreator()->recycle(widget
);
1963 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1965 const int oldIndex
= widget
->index();
1966 m_visibleItems
.remove(oldIndex
);
1967 m_visibleCells
.remove(oldIndex
);
1969 m_visibleItems
.insert(index
, widget
);
1970 m_visibleCells
.insert(index
, Cell());
1972 widget
->setIndex(index
);
1975 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1977 const int oldIndex
= widget
->index();
1978 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1980 setWidgetIndex(widget
, index
);
1982 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1983 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1984 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1985 (!vertical
&& oldCell
.column
== newCell
.column
);
1987 m_visibleCells
.insert(index
, newCell
);
1991 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1994 case LayouterSize
: m_layouter
->setSize(size
); break;
1995 case ItemSize
: m_layouter
->setItemSize(size
); break;
2000 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2002 widget
->setVisibleRoles(m_visibleRoles
);
2003 updateWidgetColumnWidths(widget
);
2004 widget
->setStyleOption(m_styleOption
);
2006 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2008 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2009 // always the selected item. It is not necessary to highlight the current item then.
2010 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2011 widget
->setCurrent(index
== selectionManager
->currentItem());
2013 widget
->setSelected(selectionManager
->isSelected(index
));
2014 widget
->setHovered(false);
2015 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2016 widget
->setIndex(index
);
2017 widget
->setData(m_model
->data(index
));
2018 widget
->setSiblingsInformation(QBitArray());
2019 updateAlternateBackgroundForWidget(widget
);
2022 updateGroupHeaderForWidget(widget
);
2026 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2028 Q_ASSERT(m_grouped
);
2030 const int index
= widget
->index();
2031 if (!m_layouter
->isFirstGroupItem(index
)) {
2032 // The widget does not represent the first item of a group
2033 // and hence requires no header
2034 recycleGroupHeaderForWidget(widget
);
2038 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2039 if (groups
.isEmpty() || !groupHeaderCreator()) {
2043 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2045 groupHeader
= groupHeaderCreator()->create(this);
2046 groupHeader
->setParentItem(widget
);
2047 m_visibleGroups
.insert(widget
, groupHeader
);
2048 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2050 Q_ASSERT(groupHeader
->parentItem() == widget
);
2052 const int groupIndex
= groupIndexForItem(index
);
2053 Q_ASSERT(groupIndex
>= 0);
2054 groupHeader
->setData(groups
.at(groupIndex
).second
);
2055 groupHeader
->setRole(model()->sortRole());
2056 groupHeader
->setStyleOption(m_styleOption
);
2057 groupHeader
->setScrollOrientation(scrollOrientation());
2058 groupHeader
->setItemIndex(index
);
2060 groupHeader
->show();
2063 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2065 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2066 Q_ASSERT(groupHeader
);
2068 const int index
= widget
->index();
2069 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2070 const QRectF itemRect
= m_layouter
->itemRect(index
);
2072 // The group-header is a child of the itemlist widget. Translate the
2073 // group header position to the relative position.
2074 if (scrollOrientation() == Qt::Vertical
) {
2075 // In the vertical scroll orientation the group header should always span
2076 // the whole width no matter which temporary position the parent widget
2077 // has. In this case the x-position and width will be adjusted manually.
2078 const qreal x
= -widget
->x() - itemOffset();
2079 const qreal width
= maximumItemOffset();
2080 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2081 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2083 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2084 groupHeader
->resize(groupHeaderRect
.size());
2088 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2090 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2092 header
->setParentItem(nullptr);
2093 groupHeaderCreator()->recycle(header
);
2094 m_visibleGroups
.remove(widget
);
2095 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2099 void KItemListView::updateVisibleGroupHeaders()
2101 Q_ASSERT(m_grouped
);
2102 m_layouter
->markAsDirty();
2104 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2105 while (it
.hasNext()) {
2107 updateGroupHeaderForWidget(it
.value());
2111 int KItemListView::groupIndexForItem(int index
) const
2113 Q_ASSERT(m_grouped
);
2115 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2116 if (groups
.isEmpty()) {
2121 int max
= groups
.count() - 1;
2124 mid
= (min
+ max
) / 2;
2125 if (index
> groups
[mid
].first
) {
2130 } while (groups
[mid
].first
!= index
&& min
<= max
);
2133 while (groups
[mid
].first
> index
&& mid
> 0) {
2141 void KItemListView::updateAlternateBackgrounds()
2143 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2144 while (it
.hasNext()) {
2146 updateAlternateBackgroundForWidget(it
.value());
2150 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2152 bool enabled
= useAlternateBackgrounds();
2154 const int index
= widget
->index();
2155 enabled
= (index
& 0x1) > 0;
2157 const int groupIndex
= groupIndexForItem(index
);
2158 if (groupIndex
>= 0) {
2159 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2160 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2161 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2162 enabled
= (relativeIndex
& 0x1) > 0;
2166 widget
->setAlternateBackground(enabled
);
2169 bool KItemListView::useAlternateBackgrounds() const
2171 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2174 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2176 QElapsedTimer timer
;
2179 QHash
<QByteArray
, qreal
> widths
;
2181 // Calculate the minimum width for each column that is required
2182 // to show the headline unclipped.
2183 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2184 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2185 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2186 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2187 const QString headerText
= m_model
->roleDescription(visibleRole
);
2188 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2189 widths
.insert(visibleRole
, headerWidth
);
2192 // Calculate the preferred column withs for each item and ignore values
2193 // smaller than the width for showing the headline unclipped.
2194 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2195 int calculatedItemCount
= 0;
2196 bool maxTimeExceeded
= false;
2197 foreach (const KItemRange
& itemRange
, itemRanges
) {
2198 const int startIndex
= itemRange
.index
;
2199 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2201 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2202 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2203 qreal maxWidth
= widths
.value(visibleRole
, 0);
2204 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2205 maxWidth
= qMax(width
, maxWidth
);
2206 widths
.insert(visibleRole
, maxWidth
);
2209 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2210 // When having several thousands of items calculating the sizes can get
2211 // very expensive. We accept a possibly too small role-size in favour
2212 // of having no blocking user interface.
2213 maxTimeExceeded
= true;
2216 ++calculatedItemCount
;
2218 if (maxTimeExceeded
) {
2226 void KItemListView::applyColumnWidthsFromHeader()
2228 // Apply the new size to the layouter
2229 const qreal requiredWidth
= columnWidthsSum();
2230 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2231 m_itemSize
.height());
2232 m_layouter
->setItemSize(dynamicItemSize
);
2234 // Update the role sizes for all visible widgets
2235 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2236 while (it
.hasNext()) {
2238 updateWidgetColumnWidths(it
.value());
2242 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2244 foreach (const QByteArray
& role
, m_visibleRoles
) {
2245 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2249 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2251 Q_ASSERT(m_itemSize
.isEmpty());
2252 const int itemCount
= m_model
->count();
2253 int rangesItemCount
= 0;
2254 foreach (const KItemRange
& range
, itemRanges
) {
2255 rangesItemCount
+= range
.count
;
2258 if (itemCount
== rangesItemCount
) {
2259 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2260 foreach (const QByteArray
& role
, m_visibleRoles
) {
2261 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2264 // Only a sub range of the roles need to be determined.
2265 // The chances are good that the widths of the sub ranges
2266 // already fit into the available widths and hence no
2267 // expensive update might be required.
2268 bool changed
= false;
2270 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2271 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2272 while (it
.hasNext()) {
2274 const QByteArray
& role
= it
.key();
2275 const qreal updatedWidth
= it
.value();
2276 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2277 if (updatedWidth
> currentWidth
) {
2278 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2284 // All the updated sizes are smaller than the current sizes and no change
2285 // of the stretched roles-widths is required
2290 if (m_headerWidget
->automaticColumnResizing()) {
2291 applyAutomaticColumnWidths();
2295 void KItemListView::updatePreferredColumnWidths()
2298 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2302 void KItemListView::applyAutomaticColumnWidths()
2304 Q_ASSERT(m_itemSize
.isEmpty());
2305 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2306 if (m_visibleRoles
.isEmpty()) {
2310 // Calculate the maximum size of an item by considering the
2311 // visible role sizes and apply them to the layouter. If the
2312 // size does not use the available view-size the size of the
2313 // first role will get stretched.
2315 foreach (const QByteArray
& role
, m_visibleRoles
) {
2316 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2317 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2320 const QByteArray firstRole
= m_visibleRoles
.first();
2321 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2322 QSizeF dynamicItemSize
= m_itemSize
;
2324 qreal requiredWidth
= columnWidthsSum();
2325 const qreal availableWidth
= size().width();
2326 if (requiredWidth
< availableWidth
) {
2327 // Stretch the first column to use the whole remaining width
2328 firstColumnWidth
+= availableWidth
- requiredWidth
;
2329 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2330 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2331 // Shrink the first column to be able to show as much other
2332 // columns as possible
2333 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2335 // TODO: A proper calculation of the minimum width depends on the implementation
2336 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2338 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2339 if (shrinkedFirstColumnWidth
< minWidth
) {
2340 shrinkedFirstColumnWidth
= minWidth
;
2343 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2344 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2347 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2349 m_layouter
->setItemSize(dynamicItemSize
);
2351 // Update the role sizes for all visible widgets
2352 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2353 while (it
.hasNext()) {
2355 updateWidgetColumnWidths(it
.value());
2359 qreal
KItemListView::columnWidthsSum() const
2361 qreal widthsSum
= 0;
2362 foreach (const QByteArray
& role
, m_visibleRoles
) {
2363 widthsSum
+= m_headerWidget
->columnWidth(role
);
2368 QRectF
KItemListView::headerBoundaries() const
2370 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2373 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2374 const QSizeF
& newItemSize
,
2375 const QSizeF
& newItemMargin
) const
2377 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2381 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2382 const qreal itemWidth
= m_layouter
->itemSize().width();
2383 if (itemWidth
> 0) {
2384 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2385 newItemSize
.width(),
2386 newItemMargin
.width());
2387 if (m_model
->count() > newColumnCount
) {
2388 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2390 m_layouter
->itemMargin().width());
2391 return oldColumnCount
!= newColumnCount
;
2395 const qreal itemHeight
= m_layouter
->itemSize().height();
2396 if (itemHeight
> 0) {
2397 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2398 newItemSize
.height(),
2399 newItemMargin
.height());
2400 if (m_model
->count() > newRowCount
) {
2401 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2403 m_layouter
->itemMargin().height());
2404 return oldRowCount
!= newRowCount
;
2412 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2414 if (m_itemSize
.isEmpty()) {
2415 // We have only columns or only rows, but no grid: An animation is usually
2416 // welcome when inserting or removing items.
2417 return !supportsItemExpanding();
2420 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2424 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2425 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2426 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2427 // Only animate if up to 2/3 of a row or column are inserted or removed
2428 return changedItemCount
<= maximum
* 2 / 3;
2432 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2434 const QSizeF oldSize
= m_layouter
->size();
2436 m_layouter
->setSize(size
);
2437 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2438 m_layouter
->setSize(oldSize
);
2440 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2441 : maxOffset
> size
.width();
2444 int KItemListView::showDropIndicator(const QPointF
& pos
)
2446 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2447 while (it
.hasNext()) {
2449 const KItemListWidget
* widget
= it
.value();
2451 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2452 const QRectF rect
= itemRect(widget
->index());
2453 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2454 if (m_model
->supportsDropping(widget
->index())) {
2455 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2456 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2457 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2462 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2463 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2465 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2466 if (m_dropIndicator
!= draggingInsertIndicator
) {
2467 m_dropIndicator
= draggingInsertIndicator
;
2471 int index
= widget
->index();
2479 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2480 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2483 void KItemListView::hideDropIndicator()
2485 if (!m_dropIndicator
.isNull()) {
2486 m_dropIndicator
= QRectF();
2491 void KItemListView::updateGroupHeaderHeight()
2493 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2494 qreal groupHeaderMargin
= 0;
2496 if (scrollOrientation() == Qt::Horizontal
) {
2497 // The vertical margin above and below the header should be
2498 // equal to the horizontal margin, not the vertical margin
2499 // from m_styleOption.
2500 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2501 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2502 } else if (m_itemSize
.isEmpty()){
2503 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2504 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2506 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2507 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2509 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2510 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2512 updateVisibleGroupHeaders();
2515 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2517 if (!supportsItemExpanding() || !m_model
) {
2521 if (firstIndex
< 0 || lastIndex
< 0) {
2522 firstIndex
= m_layouter
->firstVisibleIndex();
2523 lastIndex
= m_layouter
->lastVisibleIndex();
2525 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2526 lastIndex
>= m_layouter
->firstVisibleIndex());
2527 if (!isRangeVisible
) {
2532 int previousParents
= 0;
2533 QBitArray previousSiblings
;
2535 // The rootIndex describes the first index where the siblings get
2536 // calculated from. For the calculation the upper most parent item
2537 // is required. For performance reasons it is checked first whether
2538 // the visible items before or after the current range already
2539 // contain a siblings information which can be used as base.
2540 int rootIndex
= firstIndex
;
2542 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2544 // There is no visible widget before the range, check whether there
2545 // is one after the range:
2546 widget
= m_visibleItems
.value(lastIndex
+ 1);
2548 // The sibling information of the widget may only be used if
2549 // all items of the range have the same number of parents.
2550 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2551 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2552 if (m_model
->expandedParentsCount(i
) != parents
) {
2561 // Performance optimization: Use the sibling information of the visible
2562 // widget beside the given range.
2563 previousSiblings
= widget
->siblingsInformation();
2564 if (previousSiblings
.isEmpty()) {
2567 previousParents
= previousSiblings
.count() - 1;
2568 previousSiblings
.truncate(previousParents
);
2570 // Potentially slow path: Go back to the upper most parent of firstIndex
2571 // to be able to calculate the initial value for the siblings.
2572 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2577 Q_ASSERT(previousParents
>= 0);
2578 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2579 // Update the parent-siblings in case if the current item represents
2580 // a child or an upper parent.
2581 const int currentParents
= m_model
->expandedParentsCount(i
);
2582 Q_ASSERT(currentParents
>= 0);
2583 if (previousParents
< currentParents
) {
2584 previousParents
= currentParents
;
2585 previousSiblings
.resize(currentParents
);
2586 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2587 } else if (previousParents
> currentParents
) {
2588 previousParents
= currentParents
;
2589 previousSiblings
.truncate(currentParents
);
2592 if (i
>= firstIndex
) {
2593 // The index represents a visible item. Apply the parent-siblings
2594 // and update the sibling of the current item.
2595 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2600 QBitArray siblings
= previousSiblings
;
2601 siblings
.resize(siblings
.count() + 1);
2602 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2604 widget
->setSiblingsInformation(siblings
);
2609 bool KItemListView::hasSiblingSuccessor(int index
) const
2611 bool hasSuccessor
= false;
2612 const int parentsCount
= m_model
->expandedParentsCount(index
);
2613 int successorIndex
= index
+ 1;
2615 // Search the next sibling
2616 const int itemCount
= m_model
->count();
2617 while (successorIndex
< itemCount
) {
2618 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2619 if (currentParentsCount
== parentsCount
) {
2620 hasSuccessor
= true;
2622 } else if (currentParentsCount
< parentsCount
) {
2628 if (m_grouped
&& hasSuccessor
) {
2629 // If the sibling is part of another group, don't mark it as
2630 // successor as the group header is between the sibling connections.
2631 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2632 if (m_layouter
->isFirstGroupItem(i
)) {
2633 hasSuccessor
= false;
2639 return hasSuccessor
;
2642 void KItemListView::disconnectRoleEditingSignals(int index
)
2644 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2649 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2650 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2651 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2654 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2658 const int minSpeed
= 4;
2659 const int maxSpeed
= 128;
2660 const int speedLimiter
= 96;
2661 const int autoScrollBorder
= 64;
2663 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2664 // This assures that the autoscrolling speed grows gradually.
2665 const int incLimiter
= 1;
2667 if (pos
< autoScrollBorder
) {
2668 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2669 inc
= qMax(inc
, -maxSpeed
);
2670 inc
= qMax(inc
, oldInc
- incLimiter
);
2671 } else if (pos
> range
- autoScrollBorder
) {
2672 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2673 inc
= qMin(inc
, maxSpeed
);
2674 inc
= qMin(inc
, oldInc
+ incLimiter
);
2680 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2682 const qreal availableSize
= size
- itemMargin
;
2683 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2689 KItemListCreatorBase::~KItemListCreatorBase()
2691 qDeleteAll(m_recycleableWidgets
);
2692 qDeleteAll(m_createdWidgets
);
2695 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2697 m_createdWidgets
.insert(widget
);
2700 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2702 Q_ASSERT(m_createdWidgets
.contains(widget
));
2703 m_createdWidgets
.remove(widget
);
2705 if (m_recycleableWidgets
.count() < 100) {
2706 m_recycleableWidgets
.append(widget
);
2707 widget
->setVisible(false);
2713 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2715 if (m_recycleableWidgets
.isEmpty()) {
2719 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2720 m_createdWidgets
.insert(widget
);
2724 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2728 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2730 widget
->setParentItem(nullptr);
2731 widget
->setOpacity(1.0);
2732 pushRecycleableWidget(widget
);
2735 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2739 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2741 header
->setOpacity(1.0);
2742 pushRecycleableWidget(header
);