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 const KItemListStyleOption
& KItemListView::styleOption() const
340 return m_styleOption
;
343 void KItemListView::setGeometry(const QRectF
& rect
)
345 QGraphicsWidget::setGeometry(rect
);
351 const QSizeF newSize
= rect
.size();
352 if (m_itemSize
.isEmpty()) {
353 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
354 if (m_headerWidget
->automaticColumnResizing()) {
355 applyAutomaticColumnWidths();
357 const qreal requiredWidth
= columnWidthsSum();
358 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
359 m_itemSize
.height());
360 m_layouter
->setItemSize(dynamicItemSize
);
363 // Triggering a synchronous layout is fine from a performance point of view,
364 // as with dynamic item sizes no moving animation must be done.
365 m_layouter
->setSize(newSize
);
366 doLayout(NoAnimation
);
368 const bool animate
= !changesItemGridLayout(newSize
,
369 m_layouter
->itemSize(),
370 m_layouter
->itemMargin());
371 m_layouter
->setSize(newSize
);
374 // Trigger an asynchronous relayout with m_layoutTimer to prevent
375 // performance bottlenecks. If the timer is exceeded, an animated layout
376 // will be triggered.
377 if (!m_layoutTimer
->isActive()) {
378 m_layoutTimer
->start();
381 m_layoutTimer
->stop();
382 doLayout(NoAnimation
);
387 qreal
KItemListView::verticalPageStep() const
389 qreal headerHeight
= 0;
390 if (m_headerWidget
->isVisible()) {
391 headerHeight
= m_headerWidget
->size().height();
393 return size().height() - headerHeight
;
396 int KItemListView::itemAt(const QPointF
& pos
) const
398 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
399 while (it
.hasNext()) {
402 const KItemListWidget
* widget
= it
.value();
403 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
404 if (widget
->contains(mappedPos
)) {
412 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
414 if (!m_enabledSelectionToggles
) {
418 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
420 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
421 if (!selectionToggleRect
.isEmpty()) {
422 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
423 return selectionToggleRect
.contains(mappedPos
);
429 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
431 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
433 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
434 if (!expansionToggleRect
.isEmpty()) {
435 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
436 return expansionToggleRect
.contains(mappedPos
);
442 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
444 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
446 const QRectF
&textRect
= widget
->textRect();
447 if (!textRect
.isEmpty()) {
448 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
449 return textRect
.contains(mappedPos
);
455 int KItemListView::firstVisibleIndex() const
457 return m_layouter
->firstVisibleIndex();
460 int KItemListView::lastVisibleIndex() const
462 return m_layouter
->lastVisibleIndex();
465 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
467 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
470 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
472 if (m_supportsItemExpanding
!= supportsExpanding
) {
473 m_supportsItemExpanding
= supportsExpanding
;
474 updateSiblingsInformation();
475 onSupportsItemExpandingChanged(supportsExpanding
);
479 bool KItemListView::supportsItemExpanding() const
481 return m_supportsItemExpanding
;
484 QRectF
KItemListView::itemRect(int index
) const
486 return m_layouter
->itemRect(index
);
489 QRectF
KItemListView::itemContextRect(int index
) const
493 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
495 contextRect
= widget
->iconRect() | widget
->textRect();
496 contextRect
.translate(itemRect(index
).topLeft());
502 void KItemListView::scrollToItem(int index
)
504 QRectF viewGeometry
= geometry();
505 if (m_headerWidget
->isVisible()) {
506 const qreal headerHeight
= m_headerWidget
->size().height();
507 viewGeometry
.adjust(0, headerHeight
, 0, 0);
509 QRectF currentRect
= itemRect(index
);
511 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
512 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
513 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
515 if (!viewGeometry
.contains(currentRect
)) {
516 qreal newOffset
= scrollOffset();
517 if (scrollOrientation() == Qt::Vertical
) {
518 if (currentRect
.top() < viewGeometry
.top()) {
519 newOffset
+= currentRect
.top() - viewGeometry
.top();
520 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
521 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
524 if (currentRect
.left() < viewGeometry
.left()) {
525 newOffset
+= currentRect
.left() - viewGeometry
.left();
526 } else if (currentRect
.right() > viewGeometry
.right()) {
527 newOffset
+= currentRect
.right() - viewGeometry
.right();
531 if (newOffset
!= scrollOffset()) {
532 emit
scrollTo(newOffset
);
537 void KItemListView::beginTransaction()
539 ++m_activeTransactions
;
540 if (m_activeTransactions
== 1) {
541 onTransactionBegin();
545 void KItemListView::endTransaction()
547 --m_activeTransactions
;
548 if (m_activeTransactions
< 0) {
549 m_activeTransactions
= 0;
550 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
553 if (m_activeTransactions
== 0) {
555 doLayout(m_endTransactionAnimationHint
);
556 m_endTransactionAnimationHint
= Animation
;
560 bool KItemListView::isTransactionActive() const
562 return m_activeTransactions
> 0;
565 void KItemListView::setHeaderVisible(bool visible
)
567 if (visible
&& !m_headerWidget
->isVisible()) {
568 QStyleOptionHeader option
;
569 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
572 m_headerWidget
->setPos(0, 0);
573 m_headerWidget
->resize(size().width(), headerSize
.height());
574 m_headerWidget
->setModel(m_model
);
575 m_headerWidget
->setColumns(m_visibleRoles
);
576 m_headerWidget
->setZValue(1);
578 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
579 this, &KItemListView::slotHeaderColumnWidthChanged
);
580 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
581 this, &KItemListView::slotHeaderColumnMoved
);
582 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
583 this, &KItemListView::sortOrderChanged
);
584 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
585 this, &KItemListView::sortRoleChanged
);
587 m_layouter
->setHeaderHeight(headerSize
.height());
588 m_headerWidget
->setVisible(true);
589 } else if (!visible
&& m_headerWidget
->isVisible()) {
590 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
591 this, &KItemListView::slotHeaderColumnWidthChanged
);
592 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
593 this, &KItemListView::slotHeaderColumnMoved
);
594 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
595 this, &KItemListView::sortOrderChanged
);
596 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
597 this, &KItemListView::sortRoleChanged
);
599 m_layouter
->setHeaderHeight(0);
600 m_headerWidget
->setVisible(false);
604 bool KItemListView::isHeaderVisible() const
606 return m_headerWidget
->isVisible();
609 KItemListHeader
* KItemListView::header() const
614 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
618 if (indexes
.count() == 1) {
619 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
620 QGraphicsView
* graphicsView
= scene()->views()[0];
621 if (item
&& graphicsView
) {
622 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
625 // TODO: Not implemented yet. Probably extend the interface
626 // from KItemListWidget::createDragPixmap() to return a pixmap
627 // that can be used for multiple indexes.
633 void KItemListView::editRole(int index
, const QByteArray
& role
)
635 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
636 if (!widget
|| m_editingRole
) {
640 m_editingRole
= true;
641 widget
->setEditedRole(role
);
643 connect(widget
, &KItemListWidget::roleEditingCanceled
,
644 this, &KItemListView::slotRoleEditingCanceled
);
645 connect(widget
, &KItemListWidget::roleEditingFinished
,
646 this, &KItemListView::slotRoleEditingFinished
);
648 connect(this, &KItemListView::scrollOffsetChanged
,
649 widget
, &KStandardItemListWidget::finishRoleEditing
);
652 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
654 QGraphicsWidget::paint(painter
, option
, widget
);
656 if (m_rubberBand
->isActive()) {
657 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
658 m_rubberBand
->endPosition()).normalized();
660 const QPointF topLeft
= rubberBandRect
.topLeft();
661 if (scrollOrientation() == Qt::Vertical
) {
662 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
664 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
667 QStyleOptionRubberBand opt
;
668 initStyleOption(&opt
);
669 opt
.shape
= QRubberBand::Rectangle
;
671 opt
.rect
= rubberBandRect
.toRect();
672 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
675 if (!m_dropIndicator
.isEmpty()) {
676 const QRectF r
= m_dropIndicator
.toRect();
678 QColor color
= palette().brush(QPalette::Normal
, QPalette::Text
).color();
679 painter
->setPen(color
);
681 // TODO: The following implementation works only for a vertical scroll-orientation
682 // and assumes a height of the m_draggingInsertIndicator of 1.
683 Q_ASSERT(r
.height() == 1);
684 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
687 painter
->setPen(color
);
688 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
692 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
694 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
695 if (!scene()->views().isEmpty()) {
696 m_styleOption
.palette
= scene()->views().at(0)->palette();
699 return QGraphicsItem::itemChange(change
, value
);
702 void KItemListView::setItemSize(const QSizeF
& size
)
704 const QSizeF previousSize
= m_itemSize
;
705 if (size
== previousSize
) {
709 // Skip animations when the number of rows or columns
710 // are changed in the grid layout. Although the animation
711 // engine can handle this usecase, it looks obtrusive.
712 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
714 m_layouter
->itemMargin());
716 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
717 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
718 (!m_itemSize
.isEmpty() && size
.isEmpty()));
722 if (alternateBackgroundsChanged
) {
723 // For an empty item size alternate backgrounds are drawn if more than
724 // one role is shown. Assure that the backgrounds for visible items are
725 // updated when changing the size in this context.
726 updateAlternateBackgrounds();
729 if (size
.isEmpty()) {
730 if (m_headerWidget
->automaticColumnResizing()) {
731 updatePreferredColumnWidths();
733 // Only apply the changed height and respect the header widths
735 const qreal currentWidth
= m_layouter
->itemSize().width();
736 const QSizeF
newSize(currentWidth
, size
.height());
737 m_layouter
->setItemSize(newSize
);
740 m_layouter
->setItemSize(size
);
743 m_sizeHintResolver
->clearCache();
744 doLayout(animate
? Animation
: NoAnimation
);
745 onItemSizeChanged(size
, previousSize
);
748 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
750 if (m_styleOption
== option
) {
754 const KItemListStyleOption previousOption
= m_styleOption
;
755 m_styleOption
= option
;
758 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
759 if (margin
!= m_layouter
->itemMargin()) {
760 // Skip animations when the number of rows or columns
761 // are changed in the grid layout. Although the animation
762 // engine can handle this usecase, it looks obtrusive.
763 animate
= !changesItemGridLayout(m_layouter
->size(),
764 m_layouter
->itemSize(),
766 m_layouter
->setItemMargin(margin
);
770 updateGroupHeaderHeight();
774 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
775 // Animating a change of the maximum text size just results in expensive
776 // temporary eliding and clipping operations and does not look good visually.
780 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
781 while (it
.hasNext()) {
783 it
.value()->setStyleOption(option
);
786 m_sizeHintResolver
->clearCache();
787 m_layouter
->markAsDirty();
788 doLayout(animate
? Animation
: NoAnimation
);
790 if (m_itemSize
.isEmpty()) {
791 updatePreferredColumnWidths();
794 onStyleOptionChanged(option
, previousOption
);
797 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
799 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
800 if (orientation
== previousOrientation
) {
804 m_layouter
->setScrollOrientation(orientation
);
805 m_animation
->setScrollOrientation(orientation
);
806 m_sizeHintResolver
->clearCache();
809 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
810 while (it
.hasNext()) {
812 it
.value()->setScrollOrientation(orientation
);
814 updateGroupHeaderHeight();
818 doLayout(NoAnimation
);
820 onScrollOrientationChanged(orientation
, previousOrientation
);
821 emit
scrollOrientationChanged(orientation
, previousOrientation
);
824 Qt::Orientation
KItemListView::scrollOrientation() const
826 return m_layouter
->scrollOrientation();
829 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
834 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
839 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
844 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
846 Q_UNUSED(changedRoles
)
850 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
856 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
862 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
868 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
874 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
880 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
886 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
892 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
894 Q_UNUSED(supportsExpanding
)
897 void KItemListView::onTransactionBegin()
901 void KItemListView::onTransactionEnd()
905 bool KItemListView::event(QEvent
* event
)
907 switch (event
->type()) {
908 case QEvent::PaletteChange
:
912 case QEvent::FontChange
:
917 // Forward all other events to the controller and handle them there
918 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
924 return QGraphicsWidget::event(event
);
927 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
929 m_mousePos
= transform().map(event
->pos());
933 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
935 QGraphicsWidget::mouseMoveEvent(event
);
937 m_mousePos
= transform().map(event
->pos());
938 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
939 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
943 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
945 event
->setAccepted(true);
949 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
951 QGraphicsWidget::dragMoveEvent(event
);
953 m_mousePos
= transform().map(event
->pos());
954 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
955 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
959 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
961 QGraphicsWidget::dragLeaveEvent(event
);
962 setAutoScroll(false);
965 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
967 QGraphicsWidget::dropEvent(event
);
968 setAutoScroll(false);
971 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
973 return m_visibleItems
.values();
976 void KItemListView::updateFont()
978 if (scene() && !scene()->views().isEmpty()) {
979 KItemListStyleOption option
= styleOption();
980 option
.font
= scene()->views().first()->font();
981 option
.fontMetrics
= QFontMetrics(option
.font
);
983 setStyleOption(option
);
987 void KItemListView::updatePalette()
989 if (scene() && !scene()->views().isEmpty()) {
990 KItemListStyleOption option
= styleOption();
991 option
.palette
= scene()->views().first()->palette();
993 setStyleOption(option
);
997 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
999 if (m_itemSize
.isEmpty()) {
1000 updatePreferredColumnWidths(itemRanges
);
1003 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1004 if (hasMultipleRanges
) {
1008 m_layouter
->markAsDirty();
1010 m_sizeHintResolver
->itemsInserted(itemRanges
);
1012 int previouslyInsertedCount
= 0;
1013 foreach (const KItemRange
& range
, itemRanges
) {
1014 // range.index is related to the model before anything has been inserted.
1015 // As in each loop the current item-range gets inserted the index must
1016 // be increased by the already previously inserted items.
1017 const int index
= range
.index
+ previouslyInsertedCount
;
1018 const int count
= range
.count
;
1019 if (index
< 0 || count
<= 0) {
1020 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1023 previouslyInsertedCount
+= count
;
1025 // Determine which visible items must be moved
1026 QList
<int> itemsToMove
;
1027 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1028 while (it
.hasNext()) {
1030 const int visibleItemIndex
= it
.key();
1031 if (visibleItemIndex
>= index
) {
1032 itemsToMove
.append(visibleItemIndex
);
1036 // Update the indexes of all KItemListWidget instances that are located
1037 // after the inserted items. It is important to adjust the indexes in the order
1038 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1039 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1040 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1041 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1043 const int newIndex
= widget
->index() + count
;
1044 if (hasMultipleRanges
) {
1045 setWidgetIndex(widget
, newIndex
);
1047 // Try to animate the moving of the item
1048 moveWidgetToIndex(widget
, newIndex
);
1052 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1053 // Check whether a scrollbar is required to show the inserted items. In this case
1054 // the size of the layouter will be decreased before calling doLayout(): This prevents
1055 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1056 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1057 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1058 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1059 if (decreaseLayouterSize
) {
1060 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1062 int scrollbarSpacing
= 0;
1063 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1064 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1067 QSizeF layouterSize
= m_layouter
->size();
1068 if (verticalScrollOrientation
) {
1069 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1071 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1073 m_layouter
->setSize(layouterSize
);
1077 if (!hasMultipleRanges
) {
1078 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1079 updateSiblingsInformation();
1084 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1087 if (hasMultipleRanges
) {
1088 m_endTransactionAnimationHint
= NoAnimation
;
1091 updateSiblingsInformation();
1094 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1095 // In case if items of the same group have been inserted before an item that
1096 // currently represents the first item of the group, the group header of
1097 // this item must be removed.
1098 updateVisibleGroupHeaders();
1101 if (useAlternateBackgrounds()) {
1102 updateAlternateBackgrounds();
1106 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1108 if (m_itemSize
.isEmpty()) {
1109 // Don't pass the item-range: The preferred column-widths of
1110 // all items must be adjusted when removing items.
1111 updatePreferredColumnWidths();
1114 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1115 if (hasMultipleRanges
) {
1119 m_layouter
->markAsDirty();
1121 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1123 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1124 const KItemRange
& range
= itemRanges
[i
];
1125 const int index
= range
.index
;
1126 const int count
= range
.count
;
1127 if (index
< 0 || count
<= 0) {
1128 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1132 const int firstRemovedIndex
= index
;
1133 const int lastRemovedIndex
= index
+ count
- 1;
1135 // Remember which items have to be moved because they are behind the removed range.
1136 QVector
<int> itemsToMove
;
1138 // Remove all KItemListWidget instances that got deleted
1139 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1140 const int i
= widget
->index();
1141 if (i
< firstRemovedIndex
) {
1143 } else if (i
> lastRemovedIndex
) {
1144 itemsToMove
.append(i
);
1148 m_animation
->stop(widget
);
1149 // Stopping the animation might lead to recycling the widget if
1150 // it is invisible (see slotAnimationFinished()).
1151 // Check again whether it is still visible:
1152 if (!m_visibleItems
.contains(i
)) {
1156 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1157 // Remove the widget without animation
1158 recycleWidget(widget
);
1160 // Animate the removing of the items. Special case: When removing an item there
1161 // is no valid model index available anymore. For the
1162 // remove-animation the item gets removed from m_visibleItems but the widget
1163 // will stay alive until the animation has been finished and will
1164 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1165 m_visibleItems
.remove(i
);
1166 widget
->setIndex(-1);
1167 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1171 // Update the indexes of all KItemListWidget instances that are located
1172 // after the deleted items. It is important to update them in ascending
1173 // order to prevent overlaps when setting the new index.
1174 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1175 foreach (int i
, itemsToMove
) {
1176 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1178 const int newIndex
= i
- count
;
1179 if (hasMultipleRanges
) {
1180 setWidgetIndex(widget
, newIndex
);
1182 // Try to animate the moving of the item
1183 moveWidgetToIndex(widget
, newIndex
);
1187 if (!hasMultipleRanges
) {
1188 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1189 // assumes an updated geometry. If items are removed during an active transaction,
1190 // the transaction will be temporary deactivated so that doLayout() triggers a
1191 // geometry update if necessary.
1192 const int activeTransactions
= m_activeTransactions
;
1193 m_activeTransactions
= 0;
1194 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1195 m_activeTransactions
= activeTransactions
;
1196 updateSiblingsInformation();
1201 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1204 if (hasMultipleRanges
) {
1205 m_endTransactionAnimationHint
= NoAnimation
;
1207 updateSiblingsInformation();
1210 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1211 // In case if the first item of a group has been removed, the group header
1212 // must be applied to the next visible item.
1213 updateVisibleGroupHeaders();
1216 if (useAlternateBackgrounds()) {
1217 updateAlternateBackgrounds();
1221 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1223 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1224 m_layouter
->markAsDirty();
1227 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1230 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1231 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1233 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1234 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1236 updateWidgetProperties(widget
, index
);
1237 initializeItemListWidget(widget
);
1241 doLayout(NoAnimation
);
1242 updateSiblingsInformation();
1245 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1246 const QSet
<QByteArray
>& roles
)
1248 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1249 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1250 updatePreferredColumnWidths(itemRanges
);
1253 foreach (const KItemRange
& itemRange
, itemRanges
) {
1254 const int index
= itemRange
.index
;
1255 const int count
= itemRange
.count
;
1257 if (updateSizeHints
) {
1258 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1259 m_layouter
->markAsDirty();
1261 if (!m_layoutTimer
->isActive()) {
1262 m_layoutTimer
->start();
1266 // Apply the changed roles to the visible item-widgets
1267 const int lastIndex
= index
+ count
- 1;
1268 for (int i
= index
; i
<= lastIndex
; ++i
) {
1269 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1271 widget
->setData(m_model
->data(i
), roles
);
1275 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1276 // The sort-role has been changed which might result
1277 // in modified group headers
1278 updateVisibleGroupHeaders();
1279 doLayout(NoAnimation
);
1282 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1283 ev
.setFirstRow(itemRange
.index
);
1284 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1285 QAccessible::updateAccessibility(&ev
);
1289 void KItemListView::slotGroupsChanged()
1291 updateVisibleGroupHeaders();
1292 doLayout(NoAnimation
);
1293 updateSiblingsInformation();
1296 void KItemListView::slotGroupedSortingChanged(bool current
)
1298 m_grouped
= current
;
1299 m_layouter
->markAsDirty();
1302 updateGroupHeaderHeight();
1304 // Clear all visible headers. Note that the QHashIterator takes a copy of
1305 // m_visibleGroups. Therefore, it remains valid even if items are removed
1306 // from m_visibleGroups in recycleGroupHeaderForWidget().
1307 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1308 while (it
.hasNext()) {
1310 recycleGroupHeaderForWidget(it
.key());
1312 Q_ASSERT(m_visibleGroups
.isEmpty());
1315 if (useAlternateBackgrounds()) {
1316 // Changing the group mode requires to update the alternate backgrounds
1317 // as with the enabled group mode the altering is done on base of the first
1319 updateAlternateBackgrounds();
1321 updateSiblingsInformation();
1322 doLayout(NoAnimation
);
1325 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1330 updateVisibleGroupHeaders();
1331 doLayout(NoAnimation
);
1335 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1340 updateVisibleGroupHeaders();
1341 doLayout(NoAnimation
);
1345 void KItemListView::slotCurrentChanged(int current
, int previous
)
1349 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1350 // always the selected item. It is not necessary to highlight the current item then.
1351 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1352 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1353 if (previousWidget
) {
1354 previousWidget
->setCurrent(false);
1357 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1358 if (currentWidget
) {
1359 currentWidget
->setCurrent(true);
1363 QAccessibleEvent
ev(this, QAccessible::Focus
);
1364 ev
.setChild(current
);
1365 QAccessible::updateAccessibility(&ev
);
1368 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1372 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1373 while (it
.hasNext()) {
1375 const int index
= it
.key();
1376 KItemListWidget
* widget
= it
.value();
1377 widget
->setSelected(current
.contains(index
));
1381 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1382 KItemListViewAnimation::AnimationType type
)
1384 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1385 Q_ASSERT(itemListWidget
);
1388 case KItemListViewAnimation::DeleteAnimation
: {
1389 // As we recycle the widget in this case it is important to assure that no
1390 // other animation has been started. This is a convention in KItemListView and
1391 // not a requirement defined by KItemListViewAnimation.
1392 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1394 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1395 // by m_visibleWidgets and must be deleted manually after the animation has
1397 recycleGroupHeaderForWidget(itemListWidget
);
1398 widgetCreator()->recycle(itemListWidget
);
1402 case KItemListViewAnimation::CreateAnimation
:
1403 case KItemListViewAnimation::MovingAnimation
:
1404 case KItemListViewAnimation::ResizeAnimation
: {
1405 const int index
= itemListWidget
->index();
1406 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1407 (index
> m_layouter
->lastVisibleIndex());
1408 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1409 recycleWidget(itemListWidget
);
1418 void KItemListView::slotLayoutTimerFinished()
1420 m_layouter
->setSize(geometry().size());
1421 doLayout(Animation
);
1424 void KItemListView::slotRubberBandPosChanged()
1429 void KItemListView::slotRubberBandActivationChanged(bool active
)
1432 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1433 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1434 m_skipAutoScrollForRubberBand
= true;
1436 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1437 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1438 m_skipAutoScrollForRubberBand
= false;
1444 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1446 qreal previousWidth
)
1449 Q_UNUSED(currentWidth
)
1450 Q_UNUSED(previousWidth
)
1452 m_headerWidget
->setAutomaticColumnResizing(false);
1453 applyColumnWidthsFromHeader();
1454 doLayout(NoAnimation
);
1457 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1461 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1463 const QList
<QByteArray
> previous
= m_visibleRoles
;
1465 QList
<QByteArray
> current
= m_visibleRoles
;
1466 current
.removeAt(previousIndex
);
1467 current
.insert(currentIndex
, role
);
1469 setVisibleRoles(current
);
1471 emit
visibleRolesChanged(current
, previous
);
1474 void KItemListView::triggerAutoScrolling()
1476 if (!m_autoScrollTimer
) {
1481 int visibleSize
= 0;
1482 if (scrollOrientation() == Qt::Vertical
) {
1483 pos
= m_mousePos
.y();
1484 visibleSize
= size().height();
1486 pos
= m_mousePos
.x();
1487 visibleSize
= size().width();
1490 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1491 m_autoScrollIncrement
= 0;
1494 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1495 if (m_autoScrollIncrement
== 0) {
1496 // The mouse position is not above an autoscroll margin (the autoscroll timer
1497 // will be restarted in mouseMoveEvent())
1498 m_autoScrollTimer
->stop();
1502 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1503 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1504 // if the direction of the rubberband is similar to the autoscroll direction. This
1505 // prevents that starting to create a rubberband within the autoscroll margins starts
1506 // an autoscrolling.
1508 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1509 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1510 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1511 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1512 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1513 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1514 // been moved up although the autoscroll direction might be down)
1515 m_autoScrollTimer
->stop();
1520 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1521 // the autoscrolling may not get skipped anymore until a new rubberband is created
1522 m_skipAutoScrollForRubberBand
= false;
1524 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1525 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1526 setScrollOffset(newScrollOffset
);
1528 // Trigger the autoscroll timer which will periodically call
1529 // triggerAutoScrolling()
1530 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1533 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1535 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1537 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1538 Q_ASSERT(groupHeader
);
1539 updateGroupHeaderLayout(widget
);
1542 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1544 disconnectRoleEditingSignals(index
);
1546 emit
roleEditingCanceled(index
, role
, value
);
1547 m_editingRole
= false;
1550 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1552 disconnectRoleEditingSignals(index
);
1554 emit
roleEditingFinished(index
, role
, value
);
1555 m_editingRole
= false;
1558 void KItemListView::setController(KItemListController
* controller
)
1560 if (m_controller
!= controller
) {
1561 KItemListController
* previous
= m_controller
;
1563 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1564 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1565 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1568 m_controller
= controller
;
1571 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1572 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1573 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1576 onControllerChanged(controller
, previous
);
1580 void KItemListView::setModel(KItemModelBase
* model
)
1582 if (m_model
== model
) {
1586 KItemModelBase
* previous
= m_model
;
1589 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1590 this, &KItemListView::slotItemsChanged
);
1591 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1592 this, &KItemListView::slotItemsInserted
);
1593 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1594 this, &KItemListView::slotItemsRemoved
);
1595 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1596 this, &KItemListView::slotItemsMoved
);
1597 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1598 this, &KItemListView::slotGroupsChanged
);
1599 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1600 this, &KItemListView::slotGroupedSortingChanged
);
1601 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1602 this, &KItemListView::slotSortOrderChanged
);
1603 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1604 this, &KItemListView::slotSortRoleChanged
);
1606 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1610 m_layouter
->setModel(model
);
1611 m_grouped
= model
->groupedSorting();
1614 connect(m_model
, &KItemModelBase::itemsChanged
,
1615 this, &KItemListView::slotItemsChanged
);
1616 connect(m_model
, &KItemModelBase::itemsInserted
,
1617 this, &KItemListView::slotItemsInserted
);
1618 connect(m_model
, &KItemModelBase::itemsRemoved
,
1619 this, &KItemListView::slotItemsRemoved
);
1620 connect(m_model
, &KItemModelBase::itemsMoved
,
1621 this, &KItemListView::slotItemsMoved
);
1622 connect(m_model
, &KItemModelBase::groupsChanged
,
1623 this, &KItemListView::slotGroupsChanged
);
1624 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1625 this, &KItemListView::slotGroupedSortingChanged
);
1626 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1627 this, &KItemListView::slotSortOrderChanged
);
1628 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1629 this, &KItemListView::slotSortRoleChanged
);
1631 const int itemCount
= m_model
->count();
1632 if (itemCount
> 0) {
1633 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1637 onModelChanged(model
, previous
);
1640 KItemListRubberBand
* KItemListView::rubberBand() const
1642 return m_rubberBand
;
1645 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1647 if (m_layoutTimer
->isActive()) {
1648 m_layoutTimer
->stop();
1651 if (m_activeTransactions
> 0) {
1652 if (hint
== NoAnimation
) {
1653 // As soon as at least one property change should be done without animation,
1654 // the whole transaction will be marked as not animated.
1655 m_endTransactionAnimationHint
= NoAnimation
;
1660 if (!m_model
|| m_model
->count() < 0) {
1664 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1665 if (firstVisibleIndex
< 0) {
1666 emitOffsetChanges();
1670 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1671 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1672 // is still shown if the maximum offset got decreased.
1673 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1674 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1675 if (scrollOffset() > maxOffsetToShowFullRange
) {
1676 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1677 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1680 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1682 int firstSibblingIndex
= -1;
1683 int lastSibblingIndex
= -1;
1684 const bool supportsExpanding
= supportsItemExpanding();
1686 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1688 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1689 // instances from invisible items are reused. If no reusable items are
1690 // found then new KItemListWidget instances get created.
1691 const bool animate
= (hint
== Animation
);
1692 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1693 bool applyNewPos
= true;
1694 bool wasHidden
= false;
1696 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1697 const QPointF newPos
= itemBounds
.topLeft();
1698 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1701 if (!reusableItems
.isEmpty()) {
1702 // Reuse a KItemListWidget instance from an invisible item
1703 const int oldIndex
= reusableItems
.takeLast();
1704 widget
= m_visibleItems
.value(oldIndex
);
1705 setWidgetIndex(widget
, i
);
1706 updateWidgetProperties(widget
, i
);
1707 initializeItemListWidget(widget
);
1709 // No reusable KItemListWidget instance is available, create a new one
1710 widget
= createWidget(i
);
1712 widget
->resize(itemBounds
.size());
1714 if (animate
&& changedCount
< 0) {
1715 // Items have been deleted.
1716 if (i
>= changedIndex
) {
1717 // The item is located behind the removed range. Move the
1718 // created item to the imaginary old position outside the
1719 // view. It will get animated to the new position later.
1720 const int previousIndex
= i
- changedCount
;
1721 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1722 if (itemRect
.isEmpty()) {
1723 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1724 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1725 widget
->setPos(invisibleOldPos
);
1727 widget
->setPos(itemRect
.topLeft());
1729 applyNewPos
= false;
1733 if (supportsExpanding
&& changedCount
== 0) {
1734 if (firstSibblingIndex
< 0) {
1735 firstSibblingIndex
= i
;
1737 lastSibblingIndex
= i
;
1742 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1743 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1744 applyNewPos
= false;
1747 const bool itemsRemoved
= (changedCount
< 0);
1748 const bool itemsInserted
= (changedCount
> 0);
1749 if (itemsRemoved
&& (i
>= changedIndex
)) {
1750 // The item is located after the removed items. Animate the moving of the position.
1751 applyNewPos
= !moveWidget(widget
, newPos
);
1752 } else if (itemsInserted
&& i
>= changedIndex
) {
1753 // The item is located after the first inserted item
1754 if (i
<= changedIndex
+ changedCount
- 1) {
1755 // The item is an inserted item. Animate the appearing of the item.
1756 // For performance reasons no animation is done when changedCount is equal
1757 // to all available items.
1758 if (changedCount
< m_model
->count()) {
1759 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1761 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1762 // The item was already there before, so animate the moving of the position.
1763 // No moving animation is done if the item is animated by a create animation: This
1764 // prevents a "move animation mess" when inserting several ranges in parallel.
1765 applyNewPos
= !moveWidget(widget
, newPos
);
1767 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1768 // The size of the view might have been changed. Animate the moving of the position.
1769 applyNewPos
= !moveWidget(widget
, newPos
);
1772 m_animation
->stop(widget
);
1776 widget
->setPos(newPos
);
1779 Q_ASSERT(widget
->index() == i
);
1780 widget
->setVisible(true);
1782 if (widget
->size() != itemBounds
.size()) {
1783 // Resize the widget for the item to the changed size.
1785 // If a dynamic item size is used then no animation is done in the direction
1786 // of the dynamic size.
1787 if (m_itemSize
.width() <= 0) {
1788 // The width is dynamic, apply the new width without animation.
1789 widget
->resize(itemBounds
.width(), widget
->size().height());
1790 } else if (m_itemSize
.height() <= 0) {
1791 // The height is dynamic, apply the new height without animation.
1792 widget
->resize(widget
->size().width(), itemBounds
.height());
1794 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1796 widget
->resize(itemBounds
.size());
1800 // Updating the cell-information must be done as last step: The decision whether the
1801 // moving-animation should be started at all is based on the previous cell-information.
1802 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1803 m_visibleCells
.insert(i
, cell
);
1806 // Delete invisible KItemListWidget instances that have not been reused
1807 foreach (int index
, reusableItems
) {
1808 recycleWidget(m_visibleItems
.value(index
));
1811 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1812 Q_ASSERT(lastSibblingIndex
>= 0);
1813 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1817 // Update the layout of all visible group headers
1818 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1819 while (it
.hasNext()) {
1821 updateGroupHeaderLayout(it
.key());
1825 emitOffsetChanges();
1828 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1829 int lastVisibleIndex
,
1830 LayoutAnimationHint hint
)
1832 // Determine all items that are completely invisible and might be
1833 // reused for items that just got (at least partly) visible. If the
1834 // animation hint is set to 'Animation' items that do e.g. an animated
1835 // moving of their position are not marked as invisible: This assures
1836 // that a scrolling inside the view can be done without breaking an animation.
1840 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1841 while (it
.hasNext()) {
1844 KItemListWidget
* widget
= it
.value();
1845 const int index
= widget
->index();
1846 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1849 if (m_animation
->isStarted(widget
)) {
1850 if (hint
== NoAnimation
) {
1851 // Stopping the animation will call KItemListView::slotAnimationFinished()
1852 // and the widget will be recycled if necessary there.
1853 m_animation
->stop(widget
);
1856 widget
->setVisible(false);
1857 items
.append(index
);
1860 recycleGroupHeaderForWidget(widget
);
1869 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1871 if (widget
->pos() == newPos
) {
1875 bool startMovingAnim
= false;
1877 if (m_itemSize
.isEmpty()) {
1878 // The items are not aligned in a grid but either as columns or rows.
1879 startMovingAnim
= true;
1881 // When having a grid the moving-animation should only be started, if it is done within
1882 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1883 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1884 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1885 const int index
= widget
->index();
1886 const Cell cell
= m_visibleCells
.value(index
);
1887 if (cell
.column
>= 0 && cell
.row
>= 0) {
1888 if (scrollOrientation() == Qt::Vertical
) {
1889 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1891 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1896 if (startMovingAnim
) {
1897 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1901 m_animation
->stop(widget
);
1902 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1906 void KItemListView::emitOffsetChanges()
1908 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1909 if (m_oldScrollOffset
!= newScrollOffset
) {
1910 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1911 m_oldScrollOffset
= newScrollOffset
;
1914 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1915 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1916 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1917 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1920 const qreal newItemOffset
= m_layouter
->itemOffset();
1921 if (m_oldItemOffset
!= newItemOffset
) {
1922 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1923 m_oldItemOffset
= newItemOffset
;
1926 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1927 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1928 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1929 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1933 KItemListWidget
* KItemListView::createWidget(int index
)
1935 KItemListWidget
* widget
= widgetCreator()->create(this);
1936 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1938 m_visibleItems
.insert(index
, widget
);
1939 m_visibleCells
.insert(index
, Cell());
1940 updateWidgetProperties(widget
, index
);
1941 initializeItemListWidget(widget
);
1945 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1948 recycleGroupHeaderForWidget(widget
);
1951 const int index
= widget
->index();
1952 m_visibleItems
.remove(index
);
1953 m_visibleCells
.remove(index
);
1955 widgetCreator()->recycle(widget
);
1958 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1960 const int oldIndex
= widget
->index();
1961 m_visibleItems
.remove(oldIndex
);
1962 m_visibleCells
.remove(oldIndex
);
1964 m_visibleItems
.insert(index
, widget
);
1965 m_visibleCells
.insert(index
, Cell());
1967 widget
->setIndex(index
);
1970 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1972 const int oldIndex
= widget
->index();
1973 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1975 setWidgetIndex(widget
, index
);
1977 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1978 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1979 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1980 (!vertical
&& oldCell
.column
== newCell
.column
);
1982 m_visibleCells
.insert(index
, newCell
);
1986 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1989 case LayouterSize
: m_layouter
->setSize(size
); break;
1990 case ItemSize
: m_layouter
->setItemSize(size
); break;
1995 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1997 widget
->setVisibleRoles(m_visibleRoles
);
1998 updateWidgetColumnWidths(widget
);
1999 widget
->setStyleOption(m_styleOption
);
2001 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2003 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2004 // always the selected item. It is not necessary to highlight the current item then.
2005 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2006 widget
->setCurrent(index
== selectionManager
->currentItem());
2008 widget
->setSelected(selectionManager
->isSelected(index
));
2009 widget
->setHovered(false);
2010 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2011 widget
->setIndex(index
);
2012 widget
->setData(m_model
->data(index
));
2013 widget
->setSiblingsInformation(QBitArray());
2014 updateAlternateBackgroundForWidget(widget
);
2017 updateGroupHeaderForWidget(widget
);
2021 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2023 Q_ASSERT(m_grouped
);
2025 const int index
= widget
->index();
2026 if (!m_layouter
->isFirstGroupItem(index
)) {
2027 // The widget does not represent the first item of a group
2028 // and hence requires no header
2029 recycleGroupHeaderForWidget(widget
);
2033 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2034 if (groups
.isEmpty() || !groupHeaderCreator()) {
2038 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2040 groupHeader
= groupHeaderCreator()->create(this);
2041 groupHeader
->setParentItem(widget
);
2042 m_visibleGroups
.insert(widget
, groupHeader
);
2043 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2045 Q_ASSERT(groupHeader
->parentItem() == widget
);
2047 const int groupIndex
= groupIndexForItem(index
);
2048 Q_ASSERT(groupIndex
>= 0);
2049 groupHeader
->setData(groups
.at(groupIndex
).second
);
2050 groupHeader
->setRole(model()->sortRole());
2051 groupHeader
->setStyleOption(m_styleOption
);
2052 groupHeader
->setScrollOrientation(scrollOrientation());
2053 groupHeader
->setItemIndex(index
);
2055 groupHeader
->show();
2058 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2060 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2061 Q_ASSERT(groupHeader
);
2063 const int index
= widget
->index();
2064 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2065 const QRectF itemRect
= m_layouter
->itemRect(index
);
2067 // The group-header is a child of the itemlist widget. Translate the
2068 // group header position to the relative position.
2069 if (scrollOrientation() == Qt::Vertical
) {
2070 // In the vertical scroll orientation the group header should always span
2071 // the whole width no matter which temporary position the parent widget
2072 // has. In this case the x-position and width will be adjusted manually.
2073 const qreal x
= -widget
->x() - itemOffset();
2074 const qreal width
= maximumItemOffset();
2075 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2076 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2078 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2079 groupHeader
->resize(groupHeaderRect
.size());
2083 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2085 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2087 header
->setParentItem(nullptr);
2088 groupHeaderCreator()->recycle(header
);
2089 m_visibleGroups
.remove(widget
);
2090 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2094 void KItemListView::updateVisibleGroupHeaders()
2096 Q_ASSERT(m_grouped
);
2097 m_layouter
->markAsDirty();
2099 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2100 while (it
.hasNext()) {
2102 updateGroupHeaderForWidget(it
.value());
2106 int KItemListView::groupIndexForItem(int index
) const
2108 Q_ASSERT(m_grouped
);
2110 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2111 if (groups
.isEmpty()) {
2116 int max
= groups
.count() - 1;
2119 mid
= (min
+ max
) / 2;
2120 if (index
> groups
[mid
].first
) {
2125 } while (groups
[mid
].first
!= index
&& min
<= max
);
2128 while (groups
[mid
].first
> index
&& mid
> 0) {
2136 void KItemListView::updateAlternateBackgrounds()
2138 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2139 while (it
.hasNext()) {
2141 updateAlternateBackgroundForWidget(it
.value());
2145 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2147 bool enabled
= useAlternateBackgrounds();
2149 const int index
= widget
->index();
2150 enabled
= (index
& 0x1) > 0;
2152 const int groupIndex
= groupIndexForItem(index
);
2153 if (groupIndex
>= 0) {
2154 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2155 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2156 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2157 enabled
= (relativeIndex
& 0x1) > 0;
2161 widget
->setAlternateBackground(enabled
);
2164 bool KItemListView::useAlternateBackgrounds() const
2166 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2169 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2171 QElapsedTimer timer
;
2174 QHash
<QByteArray
, qreal
> widths
;
2176 // Calculate the minimum width for each column that is required
2177 // to show the headline unclipped.
2178 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2179 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2180 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2181 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2182 const QString headerText
= m_model
->roleDescription(visibleRole
);
2183 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2184 widths
.insert(visibleRole
, headerWidth
);
2187 // Calculate the preferred column withs for each item and ignore values
2188 // smaller than the width for showing the headline unclipped.
2189 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2190 int calculatedItemCount
= 0;
2191 bool maxTimeExceeded
= false;
2192 foreach (const KItemRange
& itemRange
, itemRanges
) {
2193 const int startIndex
= itemRange
.index
;
2194 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2196 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2197 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2198 qreal maxWidth
= widths
.value(visibleRole
, 0);
2199 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2200 maxWidth
= qMax(width
, maxWidth
);
2201 widths
.insert(visibleRole
, maxWidth
);
2204 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2205 // When having several thousands of items calculating the sizes can get
2206 // very expensive. We accept a possibly too small role-size in favour
2207 // of having no blocking user interface.
2208 maxTimeExceeded
= true;
2211 ++calculatedItemCount
;
2213 if (maxTimeExceeded
) {
2221 void KItemListView::applyColumnWidthsFromHeader()
2223 // Apply the new size to the layouter
2224 const qreal requiredWidth
= columnWidthsSum();
2225 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2226 m_itemSize
.height());
2227 m_layouter
->setItemSize(dynamicItemSize
);
2229 // Update the role sizes for all visible widgets
2230 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2231 while (it
.hasNext()) {
2233 updateWidgetColumnWidths(it
.value());
2237 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2239 foreach (const QByteArray
& role
, m_visibleRoles
) {
2240 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2244 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2246 Q_ASSERT(m_itemSize
.isEmpty());
2247 const int itemCount
= m_model
->count();
2248 int rangesItemCount
= 0;
2249 foreach (const KItemRange
& range
, itemRanges
) {
2250 rangesItemCount
+= range
.count
;
2253 if (itemCount
== rangesItemCount
) {
2254 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2255 foreach (const QByteArray
& role
, m_visibleRoles
) {
2256 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2259 // Only a sub range of the roles need to be determined.
2260 // The chances are good that the widths of the sub ranges
2261 // already fit into the available widths and hence no
2262 // expensive update might be required.
2263 bool changed
= false;
2265 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2266 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2267 while (it
.hasNext()) {
2269 const QByteArray
& role
= it
.key();
2270 const qreal updatedWidth
= it
.value();
2271 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2272 if (updatedWidth
> currentWidth
) {
2273 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2279 // All the updated sizes are smaller than the current sizes and no change
2280 // of the stretched roles-widths is required
2285 if (m_headerWidget
->automaticColumnResizing()) {
2286 applyAutomaticColumnWidths();
2290 void KItemListView::updatePreferredColumnWidths()
2293 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2297 void KItemListView::applyAutomaticColumnWidths()
2299 Q_ASSERT(m_itemSize
.isEmpty());
2300 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2301 if (m_visibleRoles
.isEmpty()) {
2305 // Calculate the maximum size of an item by considering the
2306 // visible role sizes and apply them to the layouter. If the
2307 // size does not use the available view-size the size of the
2308 // first role will get stretched.
2310 foreach (const QByteArray
& role
, m_visibleRoles
) {
2311 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2312 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2315 const QByteArray firstRole
= m_visibleRoles
.first();
2316 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2317 QSizeF dynamicItemSize
= m_itemSize
;
2319 qreal requiredWidth
= columnWidthsSum();
2320 const qreal availableWidth
= size().width();
2321 if (requiredWidth
< availableWidth
) {
2322 // Stretch the first column to use the whole remaining width
2323 firstColumnWidth
+= availableWidth
- requiredWidth
;
2324 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2325 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2326 // Shrink the first column to be able to show as much other
2327 // columns as possible
2328 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2330 // TODO: A proper calculation of the minimum width depends on the implementation
2331 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2333 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2334 if (shrinkedFirstColumnWidth
< minWidth
) {
2335 shrinkedFirstColumnWidth
= minWidth
;
2338 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2339 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2342 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2344 m_layouter
->setItemSize(dynamicItemSize
);
2346 // Update the role sizes for all visible widgets
2347 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2348 while (it
.hasNext()) {
2350 updateWidgetColumnWidths(it
.value());
2354 qreal
KItemListView::columnWidthsSum() const
2356 qreal widthsSum
= 0;
2357 foreach (const QByteArray
& role
, m_visibleRoles
) {
2358 widthsSum
+= m_headerWidget
->columnWidth(role
);
2363 QRectF
KItemListView::headerBoundaries() const
2365 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2368 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2369 const QSizeF
& newItemSize
,
2370 const QSizeF
& newItemMargin
) const
2372 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2376 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2377 const qreal itemWidth
= m_layouter
->itemSize().width();
2378 if (itemWidth
> 0) {
2379 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2380 newItemSize
.width(),
2381 newItemMargin
.width());
2382 if (m_model
->count() > newColumnCount
) {
2383 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2385 m_layouter
->itemMargin().width());
2386 return oldColumnCount
!= newColumnCount
;
2390 const qreal itemHeight
= m_layouter
->itemSize().height();
2391 if (itemHeight
> 0) {
2392 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2393 newItemSize
.height(),
2394 newItemMargin
.height());
2395 if (m_model
->count() > newRowCount
) {
2396 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2398 m_layouter
->itemMargin().height());
2399 return oldRowCount
!= newRowCount
;
2407 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2409 if (m_itemSize
.isEmpty()) {
2410 // We have only columns or only rows, but no grid: An animation is usually
2411 // welcome when inserting or removing items.
2412 return !supportsItemExpanding();
2415 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2419 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2420 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2421 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2422 // Only animate if up to 2/3 of a row or column are inserted or removed
2423 return changedItemCount
<= maximum
* 2 / 3;
2427 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2429 const QSizeF oldSize
= m_layouter
->size();
2431 m_layouter
->setSize(size
);
2432 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2433 m_layouter
->setSize(oldSize
);
2435 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2436 : maxOffset
> size
.width();
2439 int KItemListView::showDropIndicator(const QPointF
& pos
)
2441 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2442 while (it
.hasNext()) {
2444 const KItemListWidget
* widget
= it
.value();
2446 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2447 const QRectF rect
= itemRect(widget
->index());
2448 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2449 if (m_model
->supportsDropping(widget
->index())) {
2450 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2451 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2452 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2457 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2458 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2460 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2461 if (m_dropIndicator
!= draggingInsertIndicator
) {
2462 m_dropIndicator
= draggingInsertIndicator
;
2466 int index
= widget
->index();
2474 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2475 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2478 void KItemListView::hideDropIndicator()
2480 if (!m_dropIndicator
.isNull()) {
2481 m_dropIndicator
= QRectF();
2486 void KItemListView::updateGroupHeaderHeight()
2488 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2489 qreal groupHeaderMargin
= 0;
2491 if (scrollOrientation() == Qt::Horizontal
) {
2492 // The vertical margin above and below the header should be
2493 // equal to the horizontal margin, not the vertical margin
2494 // from m_styleOption.
2495 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2496 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2497 } else if (m_itemSize
.isEmpty()){
2498 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2499 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2501 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2502 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2504 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2505 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2507 updateVisibleGroupHeaders();
2510 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2512 if (!supportsItemExpanding() || !m_model
) {
2516 if (firstIndex
< 0 || lastIndex
< 0) {
2517 firstIndex
= m_layouter
->firstVisibleIndex();
2518 lastIndex
= m_layouter
->lastVisibleIndex();
2520 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2521 lastIndex
>= m_layouter
->firstVisibleIndex());
2522 if (!isRangeVisible
) {
2527 int previousParents
= 0;
2528 QBitArray previousSiblings
;
2530 // The rootIndex describes the first index where the siblings get
2531 // calculated from. For the calculation the upper most parent item
2532 // is required. For performance reasons it is checked first whether
2533 // the visible items before or after the current range already
2534 // contain a siblings information which can be used as base.
2535 int rootIndex
= firstIndex
;
2537 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2539 // There is no visible widget before the range, check whether there
2540 // is one after the range:
2541 widget
= m_visibleItems
.value(lastIndex
+ 1);
2543 // The sibling information of the widget may only be used if
2544 // all items of the range have the same number of parents.
2545 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2546 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2547 if (m_model
->expandedParentsCount(i
) != parents
) {
2556 // Performance optimization: Use the sibling information of the visible
2557 // widget beside the given range.
2558 previousSiblings
= widget
->siblingsInformation();
2559 if (previousSiblings
.isEmpty()) {
2562 previousParents
= previousSiblings
.count() - 1;
2563 previousSiblings
.truncate(previousParents
);
2565 // Potentially slow path: Go back to the upper most parent of firstIndex
2566 // to be able to calculate the initial value for the siblings.
2567 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2572 Q_ASSERT(previousParents
>= 0);
2573 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2574 // Update the parent-siblings in case if the current item represents
2575 // a child or an upper parent.
2576 const int currentParents
= m_model
->expandedParentsCount(i
);
2577 Q_ASSERT(currentParents
>= 0);
2578 if (previousParents
< currentParents
) {
2579 previousParents
= currentParents
;
2580 previousSiblings
.resize(currentParents
);
2581 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2582 } else if (previousParents
> currentParents
) {
2583 previousParents
= currentParents
;
2584 previousSiblings
.truncate(currentParents
);
2587 if (i
>= firstIndex
) {
2588 // The index represents a visible item. Apply the parent-siblings
2589 // and update the sibling of the current item.
2590 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2595 QBitArray siblings
= previousSiblings
;
2596 siblings
.resize(siblings
.count() + 1);
2597 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2599 widget
->setSiblingsInformation(siblings
);
2604 bool KItemListView::hasSiblingSuccessor(int index
) const
2606 bool hasSuccessor
= false;
2607 const int parentsCount
= m_model
->expandedParentsCount(index
);
2608 int successorIndex
= index
+ 1;
2610 // Search the next sibling
2611 const int itemCount
= m_model
->count();
2612 while (successorIndex
< itemCount
) {
2613 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2614 if (currentParentsCount
== parentsCount
) {
2615 hasSuccessor
= true;
2617 } else if (currentParentsCount
< parentsCount
) {
2623 if (m_grouped
&& hasSuccessor
) {
2624 // If the sibling is part of another group, don't mark it as
2625 // successor as the group header is between the sibling connections.
2626 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2627 if (m_layouter
->isFirstGroupItem(i
)) {
2628 hasSuccessor
= false;
2634 return hasSuccessor
;
2637 void KItemListView::disconnectRoleEditingSignals(int index
)
2639 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2644 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2645 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2646 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2649 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2653 const int minSpeed
= 4;
2654 const int maxSpeed
= 128;
2655 const int speedLimiter
= 96;
2656 const int autoScrollBorder
= 64;
2658 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2659 // This assures that the autoscrolling speed grows gradually.
2660 const int incLimiter
= 1;
2662 if (pos
< autoScrollBorder
) {
2663 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2664 inc
= qMax(inc
, -maxSpeed
);
2665 inc
= qMax(inc
, oldInc
- incLimiter
);
2666 } else if (pos
> range
- autoScrollBorder
) {
2667 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2668 inc
= qMin(inc
, maxSpeed
);
2669 inc
= qMin(inc
, oldInc
+ incLimiter
);
2675 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2677 const qreal availableSize
= size
- itemMargin
;
2678 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2684 KItemListCreatorBase::~KItemListCreatorBase()
2686 qDeleteAll(m_recycleableWidgets
);
2687 qDeleteAll(m_createdWidgets
);
2690 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2692 m_createdWidgets
.insert(widget
);
2695 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2697 Q_ASSERT(m_createdWidgets
.contains(widget
));
2698 m_createdWidgets
.remove(widget
);
2700 if (m_recycleableWidgets
.count() < 100) {
2701 m_recycleableWidgets
.append(widget
);
2702 widget
->setVisible(false);
2708 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2710 if (m_recycleableWidgets
.isEmpty()) {
2714 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2715 m_createdWidgets
.insert(widget
);
2719 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2723 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2725 widget
->setParentItem(nullptr);
2726 widget
->setOpacity(1.0);
2727 pushRecycleableWidget(widget
);
2730 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2734 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2736 header
->setOpacity(1.0);
2737 pushRecycleableWidget(header
);