1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 ***************************************************************************/
22 #include "kitemlistview.h"
24 #include "dolphindebug.h"
25 #include "kitemlistcontainer.h"
26 #include "kitemlistcontroller.h"
27 #include "kitemlistheader.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistviewaccessible.h"
30 #include "kstandarditemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
37 #include <QElapsedTimer>
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
40 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 #ifndef QT_NO_ACCESSIBILITY
54 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
58 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
59 return new KItemListContainerAccessible(container
);
60 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
61 return new KItemListViewAccessible(view
);
68 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
69 QGraphicsWidget(parent
),
70 m_enabledSelectionToggles(false),
72 m_supportsItemExpanding(false),
74 m_activeTransactions(0),
75 m_endTransactionAnimationHint(Animation
),
77 m_controller(nullptr),
80 m_widgetCreator(nullptr),
81 m_groupHeaderCreator(nullptr),
86 m_sizeHintResolver(nullptr),
89 m_layoutTimer(nullptr),
91 m_oldMaximumScrollOffset(0),
93 m_oldMaximumItemOffset(0),
94 m_skipAutoScrollForRubberBand(false),
95 m_rubberBand(nullptr),
97 m_autoScrollIncrement(0),
98 m_autoScrollTimer(nullptr),
100 m_headerWidget(nullptr),
103 setAcceptHoverEvents(true);
105 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
107 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
109 m_animation
= new KItemListViewAnimation(this);
110 connect(m_animation
, &KItemListViewAnimation::finished
,
111 this, &KItemListView::slotAnimationFinished
);
113 m_layoutTimer
= new QTimer(this);
114 m_layoutTimer
->setInterval(300);
115 m_layoutTimer
->setSingleShot(true);
116 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
118 m_rubberBand
= new KItemListRubberBand(this);
119 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
121 m_headerWidget
= new KItemListHeaderWidget(this);
122 m_headerWidget
->setVisible(false);
124 m_header
= new KItemListHeader(this);
126 #ifndef QT_NO_ACCESSIBILITY
127 QAccessible::installFactory(accessibleInterfaceFactory
);
132 KItemListView::~KItemListView()
134 // The group headers are children of the widgets created by
135 // widgetCreator(). So it is mandatory to delete the group headers
137 delete m_groupHeaderCreator
;
138 m_groupHeaderCreator
= nullptr;
140 delete m_widgetCreator
;
141 m_widgetCreator
= nullptr;
143 delete m_sizeHintResolver
;
144 m_sizeHintResolver
= nullptr;
147 void KItemListView::setScrollOffset(qreal offset
)
153 const qreal previousOffset
= m_layouter
->scrollOffset();
154 if (offset
== previousOffset
) {
158 m_layouter
->setScrollOffset(offset
);
159 m_animation
->setScrollOffset(offset
);
161 // Don't check whether the m_layoutTimer is active: Changing the
162 // scroll offset must always trigger a synchronous layout, otherwise
163 // the smooth-scrolling might get jerky.
164 doLayout(NoAnimation
);
165 onScrollOffsetChanged(offset
, previousOffset
);
168 qreal
KItemListView::scrollOffset() const
170 return m_layouter
->scrollOffset();
173 qreal
KItemListView::maximumScrollOffset() const
175 return m_layouter
->maximumScrollOffset();
178 void KItemListView::setItemOffset(qreal offset
)
180 if (m_layouter
->itemOffset() == offset
) {
184 m_layouter
->setItemOffset(offset
);
185 if (m_headerWidget
->isVisible()) {
186 m_headerWidget
->setOffset(offset
);
189 // Don't check whether the m_layoutTimer is active: Changing the
190 // item offset must always trigger a synchronous layout, otherwise
191 // the smooth-scrolling might get jerky.
192 doLayout(NoAnimation
);
195 qreal
KItemListView::itemOffset() const
197 return m_layouter
->itemOffset();
200 qreal
KItemListView::maximumItemOffset() const
202 return m_layouter
->maximumItemOffset();
205 int KItemListView::maximumVisibleItems() const
207 return m_layouter
->maximumVisibleItems();
210 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
212 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
213 m_visibleRoles
= roles
;
214 onVisibleRolesChanged(roles
, previousRoles
);
216 m_sizeHintResolver
->clearCache();
217 m_layouter
->markAsDirty();
219 if (m_itemSize
.isEmpty()) {
220 m_headerWidget
->setColumns(roles
);
221 updatePreferredColumnWidths();
222 if (!m_headerWidget
->automaticColumnResizing()) {
223 // The column-width of new roles are still 0. Apply the preferred
224 // column-width as default with.
225 foreach (const QByteArray
& role
, m_visibleRoles
) {
226 if (m_headerWidget
->columnWidth(role
) == 0) {
227 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
228 m_headerWidget
->setColumnWidth(role
, width
);
232 applyColumnWidthsFromHeader();
236 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
237 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
238 (roles
.count() <= 1 && previousRoles
.count() > 1));
240 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
241 while (it
.hasNext()) {
243 KItemListWidget
* widget
= it
.value();
244 widget
->setVisibleRoles(roles
);
245 if (alternateBackgroundsChanged
) {
246 updateAlternateBackgroundForWidget(widget
);
250 doLayout(NoAnimation
);
253 QList
<QByteArray
> KItemListView::visibleRoles() const
255 return m_visibleRoles
;
258 void KItemListView::setAutoScroll(bool enabled
)
260 if (enabled
&& !m_autoScrollTimer
) {
261 m_autoScrollTimer
= new QTimer(this);
262 m_autoScrollTimer
->setSingleShot(true);
263 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
264 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
265 } else if (!enabled
&& m_autoScrollTimer
) {
266 delete m_autoScrollTimer
;
267 m_autoScrollTimer
= nullptr;
271 bool KItemListView::autoScroll() const
273 return m_autoScrollTimer
!= nullptr;
276 void KItemListView::setEnabledSelectionToggles(bool enabled
)
278 if (m_enabledSelectionToggles
!= enabled
) {
279 m_enabledSelectionToggles
= enabled
;
281 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
282 while (it
.hasNext()) {
284 it
.value()->setEnabledSelectionToggle(enabled
);
289 bool KItemListView::enabledSelectionToggles() const
291 return m_enabledSelectionToggles
;
294 KItemListController
* KItemListView::controller() const
299 KItemModelBase
* KItemListView::model() const
304 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
306 delete m_widgetCreator
;
307 m_widgetCreator
= widgetCreator
;
310 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
312 if (!m_widgetCreator
) {
313 m_widgetCreator
= defaultWidgetCreator();
315 return m_widgetCreator
;
318 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
320 delete m_groupHeaderCreator
;
321 m_groupHeaderCreator
= groupHeaderCreator
;
324 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
326 if (!m_groupHeaderCreator
) {
327 m_groupHeaderCreator
= defaultGroupHeaderCreator();
329 return m_groupHeaderCreator
;
332 QSizeF
KItemListView::itemSize() const
337 QSizeF
KItemListView::itemSizeHint() const
339 return m_sizeHintResolver
->minSizeHint();
342 const KItemListStyleOption
& KItemListView::styleOption() const
344 return m_styleOption
;
347 void KItemListView::setGeometry(const QRectF
& rect
)
349 QGraphicsWidget::setGeometry(rect
);
355 const QSizeF newSize
= rect
.size();
356 if (m_itemSize
.isEmpty()) {
357 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
358 if (m_headerWidget
->automaticColumnResizing()) {
359 applyAutomaticColumnWidths();
361 const qreal requiredWidth
= columnWidthsSum();
362 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
363 m_itemSize
.height());
364 m_layouter
->setItemSize(dynamicItemSize
);
367 // Triggering a synchronous layout is fine from a performance point of view,
368 // as with dynamic item sizes no moving animation must be done.
369 m_layouter
->setSize(newSize
);
370 doLayout(NoAnimation
);
372 const bool animate
= !changesItemGridLayout(newSize
,
373 m_layouter
->itemSize(),
374 m_layouter
->itemMargin());
375 m_layouter
->setSize(newSize
);
378 // Trigger an asynchronous relayout with m_layoutTimer to prevent
379 // performance bottlenecks. If the timer is exceeded, an animated layout
380 // will be triggered.
381 if (!m_layoutTimer
->isActive()) {
382 m_layoutTimer
->start();
385 m_layoutTimer
->stop();
386 doLayout(NoAnimation
);
391 qreal
KItemListView::verticalPageStep() const
393 qreal headerHeight
= 0;
394 if (m_headerWidget
->isVisible()) {
395 headerHeight
= m_headerWidget
->size().height();
397 return size().height() - headerHeight
;
400 int KItemListView::itemAt(const QPointF
& pos
) const
402 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
403 while (it
.hasNext()) {
406 const KItemListWidget
* widget
= it
.value();
407 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
408 if (widget
->contains(mappedPos
)) {
416 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
418 if (!m_enabledSelectionToggles
) {
422 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
424 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
425 if (!selectionToggleRect
.isEmpty()) {
426 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
427 return selectionToggleRect
.contains(mappedPos
);
433 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
435 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
437 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
438 if (!expansionToggleRect
.isEmpty()) {
439 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
440 return expansionToggleRect
.contains(mappedPos
);
446 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
448 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
450 const QRectF
&textRect
= widget
->textRect();
451 if (!textRect
.isEmpty()) {
452 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
453 return textRect
.contains(mappedPos
);
459 int KItemListView::firstVisibleIndex() const
461 return m_layouter
->firstVisibleIndex();
464 int KItemListView::lastVisibleIndex() const
466 return m_layouter
->lastVisibleIndex();
469 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
471 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
474 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
476 if (m_supportsItemExpanding
!= supportsExpanding
) {
477 m_supportsItemExpanding
= supportsExpanding
;
478 updateSiblingsInformation();
479 onSupportsItemExpandingChanged(supportsExpanding
);
483 bool KItemListView::supportsItemExpanding() const
485 return m_supportsItemExpanding
;
488 QRectF
KItemListView::itemRect(int index
) const
490 return m_layouter
->itemRect(index
);
493 QRectF
KItemListView::itemContextRect(int index
) const
497 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
499 contextRect
= widget
->iconRect() | widget
->textRect();
500 contextRect
.translate(itemRect(index
).topLeft());
506 void KItemListView::scrollToItem(int index
)
508 QRectF viewGeometry
= geometry();
509 if (m_headerWidget
->isVisible()) {
510 const qreal headerHeight
= m_headerWidget
->size().height();
511 viewGeometry
.adjust(0, headerHeight
, 0, 0);
513 QRectF currentRect
= itemRect(index
);
515 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
516 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
517 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
519 if (!viewGeometry
.contains(currentRect
)) {
520 qreal newOffset
= scrollOffset();
521 if (scrollOrientation() == Qt::Vertical
) {
522 if (currentRect
.top() < viewGeometry
.top()) {
523 newOffset
+= currentRect
.top() - viewGeometry
.top();
524 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
525 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
528 if (currentRect
.left() < viewGeometry
.left()) {
529 newOffset
+= currentRect
.left() - viewGeometry
.left();
530 } else if (currentRect
.right() > viewGeometry
.right()) {
531 newOffset
+= currentRect
.right() - viewGeometry
.right();
535 if (newOffset
!= scrollOffset()) {
536 emit
scrollTo(newOffset
);
541 void KItemListView::beginTransaction()
543 ++m_activeTransactions
;
544 if (m_activeTransactions
== 1) {
545 onTransactionBegin();
549 void KItemListView::endTransaction()
551 --m_activeTransactions
;
552 if (m_activeTransactions
< 0) {
553 m_activeTransactions
= 0;
554 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
557 if (m_activeTransactions
== 0) {
559 doLayout(m_endTransactionAnimationHint
);
560 m_endTransactionAnimationHint
= Animation
;
564 bool KItemListView::isTransactionActive() const
566 return m_activeTransactions
> 0;
569 void KItemListView::setHeaderVisible(bool visible
)
571 if (visible
&& !m_headerWidget
->isVisible()) {
572 QStyleOptionHeader option
;
573 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
576 m_headerWidget
->setPos(0, 0);
577 m_headerWidget
->resize(size().width(), headerSize
.height());
578 m_headerWidget
->setModel(m_model
);
579 m_headerWidget
->setColumns(m_visibleRoles
);
580 m_headerWidget
->setZValue(1);
582 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
583 this, &KItemListView::slotHeaderColumnWidthChanged
);
584 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
585 this, &KItemListView::slotHeaderColumnMoved
);
586 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
587 this, &KItemListView::sortOrderChanged
);
588 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
589 this, &KItemListView::sortRoleChanged
);
591 m_layouter
->setHeaderHeight(headerSize
.height());
592 m_headerWidget
->setVisible(true);
593 } else if (!visible
&& m_headerWidget
->isVisible()) {
594 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
595 this, &KItemListView::slotHeaderColumnWidthChanged
);
596 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
597 this, &KItemListView::slotHeaderColumnMoved
);
598 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
599 this, &KItemListView::sortOrderChanged
);
600 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
601 this, &KItemListView::sortRoleChanged
);
603 m_layouter
->setHeaderHeight(0);
604 m_headerWidget
->setVisible(false);
608 bool KItemListView::isHeaderVisible() const
610 return m_headerWidget
->isVisible();
613 KItemListHeader
* KItemListView::header() const
618 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
622 if (indexes
.count() == 1) {
623 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
624 QGraphicsView
* graphicsView
= scene()->views()[0];
625 if (item
&& graphicsView
) {
626 pixmap
= item
->createDragPixmap(nullptr, graphicsView
);
629 // TODO: Not implemented yet. Probably extend the interface
630 // from KItemListWidget::createDragPixmap() to return a pixmap
631 // that can be used for multiple indexes.
637 void KItemListView::editRole(int index
, const QByteArray
& role
)
639 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
640 if (!widget
|| m_editingRole
) {
644 m_editingRole
= true;
645 widget
->setEditedRole(role
);
647 connect(widget
, &KItemListWidget::roleEditingCanceled
,
648 this, &KItemListView::slotRoleEditingCanceled
);
649 connect(widget
, &KItemListWidget::roleEditingFinished
,
650 this, &KItemListView::slotRoleEditingFinished
);
652 connect(this, &KItemListView::scrollOffsetChanged
,
653 widget
, &KStandardItemListWidget::finishRoleEditing
);
656 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
658 QGraphicsWidget::paint(painter
, option
, widget
);
660 if (m_rubberBand
->isActive()) {
661 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
662 m_rubberBand
->endPosition()).normalized();
664 const QPointF topLeft
= rubberBandRect
.topLeft();
665 if (scrollOrientation() == Qt::Vertical
) {
666 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
668 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
671 QStyleOptionRubberBand opt
;
672 initStyleOption(&opt
);
673 opt
.shape
= QRubberBand::Rectangle
;
675 opt
.rect
= rubberBandRect
.toRect();
676 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
679 if (!m_dropIndicator
.isEmpty()) {
680 const QRectF r
= m_dropIndicator
.toRect();
682 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
683 painter
->setPen(color
);
685 // TODO: The following implementation works only for a vertical scroll-orientation
686 // and assumes a height of the m_draggingInsertIndicator of 1.
687 Q_ASSERT(r
.height() == 1);
688 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
691 painter
->setPen(color
);
692 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
696 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
698 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
699 if (!scene()->views().isEmpty()) {
700 m_styleOption
.palette
= scene()->views().at(0)->palette();
703 return QGraphicsItem::itemChange(change
, value
);
706 void KItemListView::setItemSize(const QSizeF
& size
)
708 const QSizeF previousSize
= m_itemSize
;
709 if (size
== previousSize
) {
713 // Skip animations when the number of rows or columns
714 // are changed in the grid layout. Although the animation
715 // engine can handle this usecase, it looks obtrusive.
716 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
718 m_layouter
->itemMargin());
720 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
721 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
722 (!m_itemSize
.isEmpty() && size
.isEmpty()));
726 if (alternateBackgroundsChanged
) {
727 // For an empty item size alternate backgrounds are drawn if more than
728 // one role is shown. Assure that the backgrounds for visible items are
729 // updated when changing the size in this context.
730 updateAlternateBackgrounds();
733 if (size
.isEmpty()) {
734 if (m_headerWidget
->automaticColumnResizing()) {
735 updatePreferredColumnWidths();
737 // Only apply the changed height and respect the header widths
739 const qreal currentWidth
= m_layouter
->itemSize().width();
740 const QSizeF
newSize(currentWidth
, size
.height());
741 m_layouter
->setItemSize(newSize
);
744 m_layouter
->setItemSize(size
);
747 m_sizeHintResolver
->clearCache();
748 doLayout(animate
? Animation
: NoAnimation
);
749 onItemSizeChanged(size
, previousSize
);
752 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
754 if (m_styleOption
== option
) {
758 const KItemListStyleOption previousOption
= m_styleOption
;
759 m_styleOption
= option
;
762 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
763 if (margin
!= m_layouter
->itemMargin()) {
764 // Skip animations when the number of rows or columns
765 // are changed in the grid layout. Although the animation
766 // engine can handle this usecase, it looks obtrusive.
767 animate
= !changesItemGridLayout(m_layouter
->size(),
768 m_layouter
->itemSize(),
770 m_layouter
->setItemMargin(margin
);
774 updateGroupHeaderHeight();
778 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
779 // Animating a change of the maximum text size just results in expensive
780 // temporary eliding and clipping operations and does not look good visually.
784 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
785 while (it
.hasNext()) {
787 it
.value()->setStyleOption(option
);
790 m_sizeHintResolver
->clearCache();
791 m_layouter
->markAsDirty();
792 doLayout(animate
? Animation
: NoAnimation
);
794 if (m_itemSize
.isEmpty()) {
795 updatePreferredColumnWidths();
798 onStyleOptionChanged(option
, previousOption
);
801 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
803 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
804 if (orientation
== previousOrientation
) {
808 m_layouter
->setScrollOrientation(orientation
);
809 m_animation
->setScrollOrientation(orientation
);
810 m_sizeHintResolver
->clearCache();
813 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
814 while (it
.hasNext()) {
816 it
.value()->setScrollOrientation(orientation
);
818 updateGroupHeaderHeight();
822 doLayout(NoAnimation
);
824 onScrollOrientationChanged(orientation
, previousOrientation
);
825 emit
scrollOrientationChanged(orientation
, previousOrientation
);
828 Qt::Orientation
KItemListView::scrollOrientation() const
830 return m_layouter
->scrollOrientation();
833 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
838 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
843 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
848 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
850 Q_UNUSED(changedRoles
)
854 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
860 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
866 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
872 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
878 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
884 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
890 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
896 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
898 Q_UNUSED(supportsExpanding
)
901 void KItemListView::onTransactionBegin()
905 void KItemListView::onTransactionEnd()
909 bool KItemListView::event(QEvent
* event
)
911 switch (event
->type()) {
912 case QEvent::PaletteChange
:
916 case QEvent::FontChange
:
921 // Forward all other events to the controller and handle them there
922 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
928 return QGraphicsWidget::event(event
);
931 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
933 m_mousePos
= transform().map(event
->pos());
937 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
939 QGraphicsWidget::mouseMoveEvent(event
);
941 m_mousePos
= transform().map(event
->pos());
942 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
943 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
947 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
949 event
->setAccepted(true);
953 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
955 QGraphicsWidget::dragMoveEvent(event
);
957 m_mousePos
= transform().map(event
->pos());
958 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
959 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
963 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
965 QGraphicsWidget::dragLeaveEvent(event
);
966 setAutoScroll(false);
969 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
971 QGraphicsWidget::dropEvent(event
);
972 setAutoScroll(false);
975 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
977 return m_visibleItems
.values();
980 void KItemListView::updateFont()
982 if (scene() && !scene()->views().isEmpty()) {
983 KItemListStyleOption option
= styleOption();
984 option
.font
= scene()->views().first()->font();
985 option
.fontMetrics
= QFontMetrics(option
.font
);
987 setStyleOption(option
);
991 void KItemListView::updatePalette()
993 if (scene() && !scene()->views().isEmpty()) {
994 KItemListStyleOption option
= styleOption();
995 option
.palette
= scene()->views().first()->palette();
997 setStyleOption(option
);
1001 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1003 if (m_itemSize
.isEmpty()) {
1004 updatePreferredColumnWidths(itemRanges
);
1007 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1008 if (hasMultipleRanges
) {
1012 m_layouter
->markAsDirty();
1014 m_sizeHintResolver
->itemsInserted(itemRanges
);
1016 int previouslyInsertedCount
= 0;
1017 foreach (const KItemRange
& range
, itemRanges
) {
1018 // range.index is related to the model before anything has been inserted.
1019 // As in each loop the current item-range gets inserted the index must
1020 // be increased by the already previously inserted items.
1021 const int index
= range
.index
+ previouslyInsertedCount
;
1022 const int count
= range
.count
;
1023 if (index
< 0 || count
<= 0) {
1024 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1027 previouslyInsertedCount
+= count
;
1029 // Determine which visible items must be moved
1030 QList
<int> itemsToMove
;
1031 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1032 while (it
.hasNext()) {
1034 const int visibleItemIndex
= it
.key();
1035 if (visibleItemIndex
>= index
) {
1036 itemsToMove
.append(visibleItemIndex
);
1040 // Update the indexes of all KItemListWidget instances that are located
1041 // after the inserted items. It is important to adjust the indexes in the order
1042 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1043 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1044 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1045 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1047 const int newIndex
= widget
->index() + count
;
1048 if (hasMultipleRanges
) {
1049 setWidgetIndex(widget
, newIndex
);
1051 // Try to animate the moving of the item
1052 moveWidgetToIndex(widget
, newIndex
);
1056 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1057 // Check whether a scrollbar is required to show the inserted items. In this case
1058 // the size of the layouter will be decreased before calling doLayout(): This prevents
1059 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1060 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1061 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1062 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1063 if (decreaseLayouterSize
) {
1064 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1066 int scrollbarSpacing
= 0;
1067 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1068 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1071 QSizeF layouterSize
= m_layouter
->size();
1072 if (verticalScrollOrientation
) {
1073 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1075 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1077 m_layouter
->setSize(layouterSize
);
1081 if (!hasMultipleRanges
) {
1082 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1083 updateSiblingsInformation();
1088 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1091 if (hasMultipleRanges
) {
1092 m_endTransactionAnimationHint
= NoAnimation
;
1095 updateSiblingsInformation();
1098 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1099 // In case if items of the same group have been inserted before an item that
1100 // currently represents the first item of the group, the group header of
1101 // this item must be removed.
1102 updateVisibleGroupHeaders();
1105 if (useAlternateBackgrounds()) {
1106 updateAlternateBackgrounds();
1110 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1112 if (m_itemSize
.isEmpty()) {
1113 // Don't pass the item-range: The preferred column-widths of
1114 // all items must be adjusted when removing items.
1115 updatePreferredColumnWidths();
1118 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1119 if (hasMultipleRanges
) {
1123 m_layouter
->markAsDirty();
1125 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1127 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1128 const KItemRange
& range
= itemRanges
[i
];
1129 const int index
= range
.index
;
1130 const int count
= range
.count
;
1131 if (index
< 0 || count
<= 0) {
1132 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1136 const int firstRemovedIndex
= index
;
1137 const int lastRemovedIndex
= index
+ count
- 1;
1139 // Remember which items have to be moved because they are behind the removed range.
1140 QVector
<int> itemsToMove
;
1142 // Remove all KItemListWidget instances that got deleted
1143 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1144 const int i
= widget
->index();
1145 if (i
< firstRemovedIndex
) {
1147 } else if (i
> lastRemovedIndex
) {
1148 itemsToMove
.append(i
);
1152 m_animation
->stop(widget
);
1153 // Stopping the animation might lead to recycling the widget if
1154 // it is invisible (see slotAnimationFinished()).
1155 // Check again whether it is still visible:
1156 if (!m_visibleItems
.contains(i
)) {
1160 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1161 // Remove the widget without animation
1162 recycleWidget(widget
);
1164 // Animate the removing of the items. Special case: When removing an item there
1165 // is no valid model index available anymore. For the
1166 // remove-animation the item gets removed from m_visibleItems but the widget
1167 // will stay alive until the animation has been finished and will
1168 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1169 m_visibleItems
.remove(i
);
1170 widget
->setIndex(-1);
1171 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1175 // Update the indexes of all KItemListWidget instances that are located
1176 // after the deleted items. It is important to update them in ascending
1177 // order to prevent overlaps when setting the new index.
1178 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1179 foreach (int i
, itemsToMove
) {
1180 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1182 const int newIndex
= i
- count
;
1183 if (hasMultipleRanges
) {
1184 setWidgetIndex(widget
, newIndex
);
1186 // Try to animate the moving of the item
1187 moveWidgetToIndex(widget
, newIndex
);
1191 if (!hasMultipleRanges
) {
1192 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1193 // assumes an updated geometry. If items are removed during an active transaction,
1194 // the transaction will be temporary deactivated so that doLayout() triggers a
1195 // geometry update if necessary.
1196 const int activeTransactions
= m_activeTransactions
;
1197 m_activeTransactions
= 0;
1198 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1199 m_activeTransactions
= activeTransactions
;
1200 updateSiblingsInformation();
1205 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1208 if (hasMultipleRanges
) {
1209 m_endTransactionAnimationHint
= NoAnimation
;
1211 updateSiblingsInformation();
1214 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1215 // In case if the first item of a group has been removed, the group header
1216 // must be applied to the next visible item.
1217 updateVisibleGroupHeaders();
1220 if (useAlternateBackgrounds()) {
1221 updateAlternateBackgrounds();
1225 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1227 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1228 m_layouter
->markAsDirty();
1231 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1234 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1235 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1237 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1238 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1240 updateWidgetProperties(widget
, index
);
1241 initializeItemListWidget(widget
);
1245 doLayout(NoAnimation
);
1246 updateSiblingsInformation();
1249 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1250 const QSet
<QByteArray
>& roles
)
1252 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1253 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1254 updatePreferredColumnWidths(itemRanges
);
1257 foreach (const KItemRange
& itemRange
, itemRanges
) {
1258 const int index
= itemRange
.index
;
1259 const int count
= itemRange
.count
;
1261 if (updateSizeHints
) {
1262 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1263 m_layouter
->markAsDirty();
1265 if (!m_layoutTimer
->isActive()) {
1266 m_layoutTimer
->start();
1270 // Apply the changed roles to the visible item-widgets
1271 const int lastIndex
= index
+ count
- 1;
1272 for (int i
= index
; i
<= lastIndex
; ++i
) {
1273 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1275 widget
->setData(m_model
->data(i
), roles
);
1279 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1280 // The sort-role has been changed which might result
1281 // in modified group headers
1282 updateVisibleGroupHeaders();
1283 doLayout(NoAnimation
);
1286 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1287 ev
.setFirstRow(itemRange
.index
);
1288 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1289 QAccessible::updateAccessibility(&ev
);
1293 void KItemListView::slotGroupsChanged()
1295 updateVisibleGroupHeaders();
1296 doLayout(NoAnimation
);
1297 updateSiblingsInformation();
1300 void KItemListView::slotGroupedSortingChanged(bool current
)
1302 m_grouped
= current
;
1303 m_layouter
->markAsDirty();
1306 updateGroupHeaderHeight();
1308 // Clear all visible headers. Note that the QHashIterator takes a copy of
1309 // m_visibleGroups. Therefore, it remains valid even if items are removed
1310 // from m_visibleGroups in recycleGroupHeaderForWidget().
1311 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1312 while (it
.hasNext()) {
1314 recycleGroupHeaderForWidget(it
.key());
1316 Q_ASSERT(m_visibleGroups
.isEmpty());
1319 if (useAlternateBackgrounds()) {
1320 // Changing the group mode requires to update the alternate backgrounds
1321 // as with the enabled group mode the altering is done on base of the first
1323 updateAlternateBackgrounds();
1325 updateSiblingsInformation();
1326 doLayout(NoAnimation
);
1329 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1334 updateVisibleGroupHeaders();
1335 doLayout(NoAnimation
);
1339 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1344 updateVisibleGroupHeaders();
1345 doLayout(NoAnimation
);
1349 void KItemListView::slotCurrentChanged(int current
, int previous
)
1353 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1354 // always the selected item. It is not necessary to highlight the current item then.
1355 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1356 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, nullptr);
1357 if (previousWidget
) {
1358 previousWidget
->setCurrent(false);
1361 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, nullptr);
1362 if (currentWidget
) {
1363 currentWidget
->setCurrent(true);
1367 QAccessibleEvent
ev(this, QAccessible::Focus
);
1368 ev
.setChild(current
);
1369 QAccessible::updateAccessibility(&ev
);
1372 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1376 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1377 while (it
.hasNext()) {
1379 const int index
= it
.key();
1380 KItemListWidget
* widget
= it
.value();
1381 widget
->setSelected(current
.contains(index
));
1385 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1386 KItemListViewAnimation::AnimationType type
)
1388 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1389 Q_ASSERT(itemListWidget
);
1392 case KItemListViewAnimation::DeleteAnimation
: {
1393 // As we recycle the widget in this case it is important to assure that no
1394 // other animation has been started. This is a convention in KItemListView and
1395 // not a requirement defined by KItemListViewAnimation.
1396 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1398 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1399 // by m_visibleWidgets and must be deleted manually after the animation has
1401 recycleGroupHeaderForWidget(itemListWidget
);
1402 widgetCreator()->recycle(itemListWidget
);
1406 case KItemListViewAnimation::CreateAnimation
:
1407 case KItemListViewAnimation::MovingAnimation
:
1408 case KItemListViewAnimation::ResizeAnimation
: {
1409 const int index
= itemListWidget
->index();
1410 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1411 (index
> m_layouter
->lastVisibleIndex());
1412 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1413 recycleWidget(itemListWidget
);
1422 void KItemListView::slotLayoutTimerFinished()
1424 m_layouter
->setSize(geometry().size());
1425 doLayout(Animation
);
1428 void KItemListView::slotRubberBandPosChanged()
1433 void KItemListView::slotRubberBandActivationChanged(bool active
)
1436 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1437 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1438 m_skipAutoScrollForRubberBand
= true;
1440 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1441 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1442 m_skipAutoScrollForRubberBand
= false;
1448 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1450 qreal previousWidth
)
1453 Q_UNUSED(currentWidth
)
1454 Q_UNUSED(previousWidth
)
1456 m_headerWidget
->setAutomaticColumnResizing(false);
1457 applyColumnWidthsFromHeader();
1458 doLayout(NoAnimation
);
1461 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1465 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1467 const QList
<QByteArray
> previous
= m_visibleRoles
;
1469 QList
<QByteArray
> current
= m_visibleRoles
;
1470 current
.removeAt(previousIndex
);
1471 current
.insert(currentIndex
, role
);
1473 setVisibleRoles(current
);
1475 emit
visibleRolesChanged(current
, previous
);
1478 void KItemListView::triggerAutoScrolling()
1480 if (!m_autoScrollTimer
) {
1485 int visibleSize
= 0;
1486 if (scrollOrientation() == Qt::Vertical
) {
1487 pos
= m_mousePos
.y();
1488 visibleSize
= size().height();
1490 pos
= m_mousePos
.x();
1491 visibleSize
= size().width();
1494 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1495 m_autoScrollIncrement
= 0;
1498 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1499 if (m_autoScrollIncrement
== 0) {
1500 // The mouse position is not above an autoscroll margin (the autoscroll timer
1501 // will be restarted in mouseMoveEvent())
1502 m_autoScrollTimer
->stop();
1506 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1507 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1508 // if the direction of the rubberband is similar to the autoscroll direction. This
1509 // prevents that starting to create a rubberband within the autoscroll margins starts
1510 // an autoscrolling.
1512 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1513 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1514 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1515 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1516 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1517 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1518 // been moved up although the autoscroll direction might be down)
1519 m_autoScrollTimer
->stop();
1524 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1525 // the autoscrolling may not get skipped anymore until a new rubberband is created
1526 m_skipAutoScrollForRubberBand
= false;
1528 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1529 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1530 setScrollOffset(newScrollOffset
);
1532 // Trigger the autoscroll timer which will periodically call
1533 // triggerAutoScrolling()
1534 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1537 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1539 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1541 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1542 Q_ASSERT(groupHeader
);
1543 updateGroupHeaderLayout(widget
);
1546 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1548 disconnectRoleEditingSignals(index
);
1550 emit
roleEditingCanceled(index
, role
, value
);
1551 m_editingRole
= false;
1554 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1556 disconnectRoleEditingSignals(index
);
1558 emit
roleEditingFinished(index
, role
, value
);
1559 m_editingRole
= false;
1562 void KItemListView::setController(KItemListController
* controller
)
1564 if (m_controller
!= controller
) {
1565 KItemListController
* previous
= m_controller
;
1567 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1568 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1569 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1572 m_controller
= controller
;
1575 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1576 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1577 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1580 onControllerChanged(controller
, previous
);
1584 void KItemListView::setModel(KItemModelBase
* model
)
1586 if (m_model
== model
) {
1590 KItemModelBase
* previous
= m_model
;
1593 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1594 this, &KItemListView::slotItemsChanged
);
1595 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1596 this, &KItemListView::slotItemsInserted
);
1597 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1598 this, &KItemListView::slotItemsRemoved
);
1599 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1600 this, &KItemListView::slotItemsMoved
);
1601 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1602 this, &KItemListView::slotGroupsChanged
);
1603 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1604 this, &KItemListView::slotGroupedSortingChanged
);
1605 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1606 this, &KItemListView::slotSortOrderChanged
);
1607 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1608 this, &KItemListView::slotSortRoleChanged
);
1610 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1614 m_layouter
->setModel(model
);
1615 m_grouped
= model
->groupedSorting();
1618 connect(m_model
, &KItemModelBase::itemsChanged
,
1619 this, &KItemListView::slotItemsChanged
);
1620 connect(m_model
, &KItemModelBase::itemsInserted
,
1621 this, &KItemListView::slotItemsInserted
);
1622 connect(m_model
, &KItemModelBase::itemsRemoved
,
1623 this, &KItemListView::slotItemsRemoved
);
1624 connect(m_model
, &KItemModelBase::itemsMoved
,
1625 this, &KItemListView::slotItemsMoved
);
1626 connect(m_model
, &KItemModelBase::groupsChanged
,
1627 this, &KItemListView::slotGroupsChanged
);
1628 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1629 this, &KItemListView::slotGroupedSortingChanged
);
1630 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1631 this, &KItemListView::slotSortOrderChanged
);
1632 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1633 this, &KItemListView::slotSortRoleChanged
);
1635 const int itemCount
= m_model
->count();
1636 if (itemCount
> 0) {
1637 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1641 onModelChanged(model
, previous
);
1644 KItemListRubberBand
* KItemListView::rubberBand() const
1646 return m_rubberBand
;
1649 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1651 if (m_layoutTimer
->isActive()) {
1652 m_layoutTimer
->stop();
1655 if (m_activeTransactions
> 0) {
1656 if (hint
== NoAnimation
) {
1657 // As soon as at least one property change should be done without animation,
1658 // the whole transaction will be marked as not animated.
1659 m_endTransactionAnimationHint
= NoAnimation
;
1664 if (!m_model
|| m_model
->count() < 0) {
1668 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1669 if (firstVisibleIndex
< 0) {
1670 emitOffsetChanges();
1674 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1675 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1676 // is still shown if the maximum offset got decreased.
1677 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1678 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1679 if (scrollOffset() > maxOffsetToShowFullRange
) {
1680 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1681 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1684 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1686 int firstSibblingIndex
= -1;
1687 int lastSibblingIndex
= -1;
1688 const bool supportsExpanding
= supportsItemExpanding();
1690 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1692 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1693 // instances from invisible items are reused. If no reusable items are
1694 // found then new KItemListWidget instances get created.
1695 const bool animate
= (hint
== Animation
);
1696 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1697 bool applyNewPos
= true;
1698 bool wasHidden
= false;
1700 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1701 const QPointF newPos
= itemBounds
.topLeft();
1702 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1705 if (!reusableItems
.isEmpty()) {
1706 // Reuse a KItemListWidget instance from an invisible item
1707 const int oldIndex
= reusableItems
.takeLast();
1708 widget
= m_visibleItems
.value(oldIndex
);
1709 setWidgetIndex(widget
, i
);
1710 updateWidgetProperties(widget
, i
);
1711 initializeItemListWidget(widget
);
1713 // No reusable KItemListWidget instance is available, create a new one
1714 widget
= createWidget(i
);
1716 widget
->resize(itemBounds
.size());
1718 if (animate
&& changedCount
< 0) {
1719 // Items have been deleted.
1720 if (i
>= changedIndex
) {
1721 // The item is located behind the removed range. Move the
1722 // created item to the imaginary old position outside the
1723 // view. It will get animated to the new position later.
1724 const int previousIndex
= i
- changedCount
;
1725 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1726 if (itemRect
.isEmpty()) {
1727 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1728 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1729 widget
->setPos(invisibleOldPos
);
1731 widget
->setPos(itemRect
.topLeft());
1733 applyNewPos
= false;
1737 if (supportsExpanding
&& changedCount
== 0) {
1738 if (firstSibblingIndex
< 0) {
1739 firstSibblingIndex
= i
;
1741 lastSibblingIndex
= i
;
1746 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1747 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1748 applyNewPos
= false;
1751 const bool itemsRemoved
= (changedCount
< 0);
1752 const bool itemsInserted
= (changedCount
> 0);
1753 if (itemsRemoved
&& (i
>= changedIndex
)) {
1754 // The item is located after the removed items. Animate the moving of the position.
1755 applyNewPos
= !moveWidget(widget
, newPos
);
1756 } else if (itemsInserted
&& i
>= changedIndex
) {
1757 // The item is located after the first inserted item
1758 if (i
<= changedIndex
+ changedCount
- 1) {
1759 // The item is an inserted item. Animate the appearing of the item.
1760 // For performance reasons no animation is done when changedCount is equal
1761 // to all available items.
1762 if (changedCount
< m_model
->count()) {
1763 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1765 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1766 // The item was already there before, so animate the moving of the position.
1767 // No moving animation is done if the item is animated by a create animation: This
1768 // prevents a "move animation mess" when inserting several ranges in parallel.
1769 applyNewPos
= !moveWidget(widget
, newPos
);
1771 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1772 // The size of the view might have been changed. Animate the moving of the position.
1773 applyNewPos
= !moveWidget(widget
, newPos
);
1776 m_animation
->stop(widget
);
1780 widget
->setPos(newPos
);
1783 Q_ASSERT(widget
->index() == i
);
1784 widget
->setVisible(true);
1786 if (widget
->size() != itemBounds
.size()) {
1787 // Resize the widget for the item to the changed size.
1789 // If a dynamic item size is used then no animation is done in the direction
1790 // of the dynamic size.
1791 if (m_itemSize
.width() <= 0) {
1792 // The width is dynamic, apply the new width without animation.
1793 widget
->resize(itemBounds
.width(), widget
->size().height());
1794 } else if (m_itemSize
.height() <= 0) {
1795 // The height is dynamic, apply the new height without animation.
1796 widget
->resize(widget
->size().width(), itemBounds
.height());
1798 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1800 widget
->resize(itemBounds
.size());
1804 // Updating the cell-information must be done as last step: The decision whether the
1805 // moving-animation should be started at all is based on the previous cell-information.
1806 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1807 m_visibleCells
.insert(i
, cell
);
1810 // Delete invisible KItemListWidget instances that have not been reused
1811 foreach (int index
, reusableItems
) {
1812 recycleWidget(m_visibleItems
.value(index
));
1815 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1816 Q_ASSERT(lastSibblingIndex
>= 0);
1817 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1821 // Update the layout of all visible group headers
1822 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1823 while (it
.hasNext()) {
1825 updateGroupHeaderLayout(it
.key());
1829 emitOffsetChanges();
1832 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1833 int lastVisibleIndex
,
1834 LayoutAnimationHint hint
)
1836 // Determine all items that are completely invisible and might be
1837 // reused for items that just got (at least partly) visible. If the
1838 // animation hint is set to 'Animation' items that do e.g. an animated
1839 // moving of their position are not marked as invisible: This assures
1840 // that a scrolling inside the view can be done without breaking an animation.
1844 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1845 while (it
.hasNext()) {
1848 KItemListWidget
* widget
= it
.value();
1849 const int index
= widget
->index();
1850 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1853 if (m_animation
->isStarted(widget
)) {
1854 if (hint
== NoAnimation
) {
1855 // Stopping the animation will call KItemListView::slotAnimationFinished()
1856 // and the widget will be recycled if necessary there.
1857 m_animation
->stop(widget
);
1860 widget
->setVisible(false);
1861 items
.append(index
);
1864 recycleGroupHeaderForWidget(widget
);
1873 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1875 if (widget
->pos() == newPos
) {
1879 bool startMovingAnim
= false;
1881 if (m_itemSize
.isEmpty()) {
1882 // The items are not aligned in a grid but either as columns or rows.
1883 startMovingAnim
= true;
1885 // When having a grid the moving-animation should only be started, if it is done within
1886 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1887 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1888 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1889 const int index
= widget
->index();
1890 const Cell cell
= m_visibleCells
.value(index
);
1891 if (cell
.column
>= 0 && cell
.row
>= 0) {
1892 if (scrollOrientation() == Qt::Vertical
) {
1893 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1895 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1900 if (startMovingAnim
) {
1901 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1905 m_animation
->stop(widget
);
1906 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1910 void KItemListView::emitOffsetChanges()
1912 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1913 if (m_oldScrollOffset
!= newScrollOffset
) {
1914 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1915 m_oldScrollOffset
= newScrollOffset
;
1918 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1919 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1920 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1921 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1924 const qreal newItemOffset
= m_layouter
->itemOffset();
1925 if (m_oldItemOffset
!= newItemOffset
) {
1926 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1927 m_oldItemOffset
= newItemOffset
;
1930 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1931 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1932 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1933 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1937 KItemListWidget
* KItemListView::createWidget(int index
)
1939 KItemListWidget
* widget
= widgetCreator()->create(this);
1940 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1942 m_visibleItems
.insert(index
, widget
);
1943 m_visibleCells
.insert(index
, Cell());
1944 updateWidgetProperties(widget
, index
);
1945 initializeItemListWidget(widget
);
1949 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1952 recycleGroupHeaderForWidget(widget
);
1955 const int index
= widget
->index();
1956 m_visibleItems
.remove(index
);
1957 m_visibleCells
.remove(index
);
1959 widgetCreator()->recycle(widget
);
1962 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1964 const int oldIndex
= widget
->index();
1965 m_visibleItems
.remove(oldIndex
);
1966 m_visibleCells
.remove(oldIndex
);
1968 m_visibleItems
.insert(index
, widget
);
1969 m_visibleCells
.insert(index
, Cell());
1971 widget
->setIndex(index
);
1974 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1976 const int oldIndex
= widget
->index();
1977 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1979 setWidgetIndex(widget
, index
);
1981 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1982 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1983 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1984 (!vertical
&& oldCell
.column
== newCell
.column
);
1986 m_visibleCells
.insert(index
, newCell
);
1990 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1993 case LayouterSize
: m_layouter
->setSize(size
); break;
1994 case ItemSize
: m_layouter
->setItemSize(size
); break;
1999 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2001 widget
->setVisibleRoles(m_visibleRoles
);
2002 updateWidgetColumnWidths(widget
);
2003 widget
->setStyleOption(m_styleOption
);
2005 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2007 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2008 // always the selected item. It is not necessary to highlight the current item then.
2009 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2010 widget
->setCurrent(index
== selectionManager
->currentItem());
2012 widget
->setSelected(selectionManager
->isSelected(index
));
2013 widget
->setHovered(false);
2014 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2015 widget
->setIndex(index
);
2016 widget
->setData(m_model
->data(index
));
2017 widget
->setSiblingsInformation(QBitArray());
2018 updateAlternateBackgroundForWidget(widget
);
2021 updateGroupHeaderForWidget(widget
);
2025 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2027 Q_ASSERT(m_grouped
);
2029 const int index
= widget
->index();
2030 if (!m_layouter
->isFirstGroupItem(index
)) {
2031 // The widget does not represent the first item of a group
2032 // and hence requires no header
2033 recycleGroupHeaderForWidget(widget
);
2037 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2038 if (groups
.isEmpty() || !groupHeaderCreator()) {
2042 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2044 groupHeader
= groupHeaderCreator()->create(this);
2045 groupHeader
->setParentItem(widget
);
2046 m_visibleGroups
.insert(widget
, groupHeader
);
2047 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2049 Q_ASSERT(groupHeader
->parentItem() == widget
);
2051 const int groupIndex
= groupIndexForItem(index
);
2052 Q_ASSERT(groupIndex
>= 0);
2053 groupHeader
->setData(groups
.at(groupIndex
).second
);
2054 groupHeader
->setRole(model()->sortRole());
2055 groupHeader
->setStyleOption(m_styleOption
);
2056 groupHeader
->setScrollOrientation(scrollOrientation());
2057 groupHeader
->setItemIndex(index
);
2059 groupHeader
->show();
2062 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2064 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2065 Q_ASSERT(groupHeader
);
2067 const int index
= widget
->index();
2068 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2069 const QRectF itemRect
= m_layouter
->itemRect(index
);
2071 // The group-header is a child of the itemlist widget. Translate the
2072 // group header position to the relative position.
2073 if (scrollOrientation() == Qt::Vertical
) {
2074 // In the vertical scroll orientation the group header should always span
2075 // the whole width no matter which temporary position the parent widget
2076 // has. In this case the x-position and width will be adjusted manually.
2077 const qreal x
= -widget
->x() - itemOffset();
2078 const qreal width
= maximumItemOffset();
2079 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2080 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2082 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2083 groupHeader
->resize(groupHeaderRect
.size());
2087 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2089 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2091 header
->setParentItem(nullptr);
2092 groupHeaderCreator()->recycle(header
);
2093 m_visibleGroups
.remove(widget
);
2094 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2098 void KItemListView::updateVisibleGroupHeaders()
2100 Q_ASSERT(m_grouped
);
2101 m_layouter
->markAsDirty();
2103 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2104 while (it
.hasNext()) {
2106 updateGroupHeaderForWidget(it
.value());
2110 int KItemListView::groupIndexForItem(int index
) const
2112 Q_ASSERT(m_grouped
);
2114 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2115 if (groups
.isEmpty()) {
2120 int max
= groups
.count() - 1;
2123 mid
= (min
+ max
) / 2;
2124 if (index
> groups
[mid
].first
) {
2129 } while (groups
[mid
].first
!= index
&& min
<= max
);
2132 while (groups
[mid
].first
> index
&& mid
> 0) {
2140 void KItemListView::updateAlternateBackgrounds()
2142 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2143 while (it
.hasNext()) {
2145 updateAlternateBackgroundForWidget(it
.value());
2149 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2151 bool enabled
= useAlternateBackgrounds();
2153 const int index
= widget
->index();
2154 enabled
= (index
& 0x1) > 0;
2156 const int groupIndex
= groupIndexForItem(index
);
2157 if (groupIndex
>= 0) {
2158 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2159 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2160 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2161 enabled
= (relativeIndex
& 0x1) > 0;
2165 widget
->setAlternateBackground(enabled
);
2168 bool KItemListView::useAlternateBackgrounds() const
2170 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2173 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2175 QElapsedTimer timer
;
2178 QHash
<QByteArray
, qreal
> widths
;
2180 // Calculate the minimum width for each column that is required
2181 // to show the headline unclipped.
2182 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2183 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2184 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2185 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2186 const QString headerText
= m_model
->roleDescription(visibleRole
);
2187 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2188 widths
.insert(visibleRole
, headerWidth
);
2191 // Calculate the preferred column withs for each item and ignore values
2192 // smaller than the width for showing the headline unclipped.
2193 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2194 int calculatedItemCount
= 0;
2195 bool maxTimeExceeded
= false;
2196 foreach (const KItemRange
& itemRange
, itemRanges
) {
2197 const int startIndex
= itemRange
.index
;
2198 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2200 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2201 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2202 qreal maxWidth
= widths
.value(visibleRole
, 0);
2203 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2204 maxWidth
= qMax(width
, maxWidth
);
2205 widths
.insert(visibleRole
, maxWidth
);
2208 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2209 // When having several thousands of items calculating the sizes can get
2210 // very expensive. We accept a possibly too small role-size in favour
2211 // of having no blocking user interface.
2212 maxTimeExceeded
= true;
2215 ++calculatedItemCount
;
2217 if (maxTimeExceeded
) {
2225 void KItemListView::applyColumnWidthsFromHeader()
2227 // Apply the new size to the layouter
2228 const qreal requiredWidth
= columnWidthsSum();
2229 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2230 m_itemSize
.height());
2231 m_layouter
->setItemSize(dynamicItemSize
);
2233 // Update the role sizes for all visible widgets
2234 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2235 while (it
.hasNext()) {
2237 updateWidgetColumnWidths(it
.value());
2241 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2243 foreach (const QByteArray
& role
, m_visibleRoles
) {
2244 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2248 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2250 Q_ASSERT(m_itemSize
.isEmpty());
2251 const int itemCount
= m_model
->count();
2252 int rangesItemCount
= 0;
2253 foreach (const KItemRange
& range
, itemRanges
) {
2254 rangesItemCount
+= range
.count
;
2257 if (itemCount
== rangesItemCount
) {
2258 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2259 foreach (const QByteArray
& role
, m_visibleRoles
) {
2260 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2263 // Only a sub range of the roles need to be determined.
2264 // The chances are good that the widths of the sub ranges
2265 // already fit into the available widths and hence no
2266 // expensive update might be required.
2267 bool changed
= false;
2269 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2270 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2271 while (it
.hasNext()) {
2273 const QByteArray
& role
= it
.key();
2274 const qreal updatedWidth
= it
.value();
2275 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2276 if (updatedWidth
> currentWidth
) {
2277 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2283 // All the updated sizes are smaller than the current sizes and no change
2284 // of the stretched roles-widths is required
2289 if (m_headerWidget
->automaticColumnResizing()) {
2290 applyAutomaticColumnWidths();
2294 void KItemListView::updatePreferredColumnWidths()
2297 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2301 void KItemListView::applyAutomaticColumnWidths()
2303 Q_ASSERT(m_itemSize
.isEmpty());
2304 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2305 if (m_visibleRoles
.isEmpty()) {
2309 // Calculate the maximum size of an item by considering the
2310 // visible role sizes and apply them to the layouter. If the
2311 // size does not use the available view-size the size of the
2312 // first role will get stretched.
2314 foreach (const QByteArray
& role
, m_visibleRoles
) {
2315 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2316 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2319 const QByteArray firstRole
= m_visibleRoles
.first();
2320 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2321 QSizeF dynamicItemSize
= m_itemSize
;
2323 qreal requiredWidth
= columnWidthsSum();
2324 const qreal availableWidth
= size().width();
2325 if (requiredWidth
< availableWidth
) {
2326 // Stretch the first column to use the whole remaining width
2327 firstColumnWidth
+= availableWidth
- requiredWidth
;
2328 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2329 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2330 // Shrink the first column to be able to show as much other
2331 // columns as possible
2332 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2334 // TODO: A proper calculation of the minimum width depends on the implementation
2335 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2337 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2338 if (shrinkedFirstColumnWidth
< minWidth
) {
2339 shrinkedFirstColumnWidth
= minWidth
;
2342 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2343 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2346 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2348 m_layouter
->setItemSize(dynamicItemSize
);
2350 // Update the role sizes for all visible widgets
2351 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2352 while (it
.hasNext()) {
2354 updateWidgetColumnWidths(it
.value());
2358 qreal
KItemListView::columnWidthsSum() const
2360 qreal widthsSum
= 0;
2361 foreach (const QByteArray
& role
, m_visibleRoles
) {
2362 widthsSum
+= m_headerWidget
->columnWidth(role
);
2367 QRectF
KItemListView::headerBoundaries() const
2369 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2372 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2373 const QSizeF
& newItemSize
,
2374 const QSizeF
& newItemMargin
) const
2376 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2380 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2381 const qreal itemWidth
= m_layouter
->itemSize().width();
2382 if (itemWidth
> 0) {
2383 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2384 newItemSize
.width(),
2385 newItemMargin
.width());
2386 if (m_model
->count() > newColumnCount
) {
2387 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2389 m_layouter
->itemMargin().width());
2390 return oldColumnCount
!= newColumnCount
;
2394 const qreal itemHeight
= m_layouter
->itemSize().height();
2395 if (itemHeight
> 0) {
2396 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2397 newItemSize
.height(),
2398 newItemMargin
.height());
2399 if (m_model
->count() > newRowCount
) {
2400 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2402 m_layouter
->itemMargin().height());
2403 return oldRowCount
!= newRowCount
;
2411 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2413 if (m_itemSize
.isEmpty()) {
2414 // We have only columns or only rows, but no grid: An animation is usually
2415 // welcome when inserting or removing items.
2416 return !supportsItemExpanding();
2419 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2423 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2424 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2425 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2426 // Only animate if up to 2/3 of a row or column are inserted or removed
2427 return changedItemCount
<= maximum
* 2 / 3;
2431 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2433 const QSizeF oldSize
= m_layouter
->size();
2435 m_layouter
->setSize(size
);
2436 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2437 m_layouter
->setSize(oldSize
);
2439 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2440 : maxOffset
> size
.width();
2443 int KItemListView::showDropIndicator(const QPointF
& pos
)
2445 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2446 while (it
.hasNext()) {
2448 const KItemListWidget
* widget
= it
.value();
2450 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2451 const QRectF rect
= itemRect(widget
->index());
2452 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2453 if (m_model
->supportsDropping(widget
->index())) {
2454 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2455 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2456 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2461 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2462 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2464 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2465 if (m_dropIndicator
!= draggingInsertIndicator
) {
2466 m_dropIndicator
= draggingInsertIndicator
;
2470 int index
= widget
->index();
2478 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2479 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2482 void KItemListView::hideDropIndicator()
2484 if (!m_dropIndicator
.isNull()) {
2485 m_dropIndicator
= QRectF();
2490 void KItemListView::updateGroupHeaderHeight()
2492 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2493 qreal groupHeaderMargin
= 0;
2495 if (scrollOrientation() == Qt::Horizontal
) {
2496 // The vertical margin above and below the header should be
2497 // equal to the horizontal margin, not the vertical margin
2498 // from m_styleOption.
2499 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2500 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2501 } else if (m_itemSize
.isEmpty()){
2502 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2503 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2505 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2506 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2508 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2509 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2511 updateVisibleGroupHeaders();
2514 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2516 if (!supportsItemExpanding() || !m_model
) {
2520 if (firstIndex
< 0 || lastIndex
< 0) {
2521 firstIndex
= m_layouter
->firstVisibleIndex();
2522 lastIndex
= m_layouter
->lastVisibleIndex();
2524 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2525 lastIndex
>= m_layouter
->firstVisibleIndex());
2526 if (!isRangeVisible
) {
2531 int previousParents
= 0;
2532 QBitArray previousSiblings
;
2534 // The rootIndex describes the first index where the siblings get
2535 // calculated from. For the calculation the upper most parent item
2536 // is required. For performance reasons it is checked first whether
2537 // the visible items before or after the current range already
2538 // contain a siblings information which can be used as base.
2539 int rootIndex
= firstIndex
;
2541 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2543 // There is no visible widget before the range, check whether there
2544 // is one after the range:
2545 widget
= m_visibleItems
.value(lastIndex
+ 1);
2547 // The sibling information of the widget may only be used if
2548 // all items of the range have the same number of parents.
2549 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2550 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2551 if (m_model
->expandedParentsCount(i
) != parents
) {
2560 // Performance optimization: Use the sibling information of the visible
2561 // widget beside the given range.
2562 previousSiblings
= widget
->siblingsInformation();
2563 if (previousSiblings
.isEmpty()) {
2566 previousParents
= previousSiblings
.count() - 1;
2567 previousSiblings
.truncate(previousParents
);
2569 // Potentially slow path: Go back to the upper most parent of firstIndex
2570 // to be able to calculate the initial value for the siblings.
2571 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2576 Q_ASSERT(previousParents
>= 0);
2577 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2578 // Update the parent-siblings in case if the current item represents
2579 // a child or an upper parent.
2580 const int currentParents
= m_model
->expandedParentsCount(i
);
2581 Q_ASSERT(currentParents
>= 0);
2582 if (previousParents
< currentParents
) {
2583 previousParents
= currentParents
;
2584 previousSiblings
.resize(currentParents
);
2585 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2586 } else if (previousParents
> currentParents
) {
2587 previousParents
= currentParents
;
2588 previousSiblings
.truncate(currentParents
);
2591 if (i
>= firstIndex
) {
2592 // The index represents a visible item. Apply the parent-siblings
2593 // and update the sibling of the current item.
2594 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2599 QBitArray siblings
= previousSiblings
;
2600 siblings
.resize(siblings
.count() + 1);
2601 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2603 widget
->setSiblingsInformation(siblings
);
2608 bool KItemListView::hasSiblingSuccessor(int index
) const
2610 bool hasSuccessor
= false;
2611 const int parentsCount
= m_model
->expandedParentsCount(index
);
2612 int successorIndex
= index
+ 1;
2614 // Search the next sibling
2615 const int itemCount
= m_model
->count();
2616 while (successorIndex
< itemCount
) {
2617 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2618 if (currentParentsCount
== parentsCount
) {
2619 hasSuccessor
= true;
2621 } else if (currentParentsCount
< parentsCount
) {
2627 if (m_grouped
&& hasSuccessor
) {
2628 // If the sibling is part of another group, don't mark it as
2629 // successor as the group header is between the sibling connections.
2630 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2631 if (m_layouter
->isFirstGroupItem(i
)) {
2632 hasSuccessor
= false;
2638 return hasSuccessor
;
2641 void KItemListView::disconnectRoleEditingSignals(int index
)
2643 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2648 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2649 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2650 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2653 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2657 const int minSpeed
= 4;
2658 const int maxSpeed
= 128;
2659 const int speedLimiter
= 96;
2660 const int autoScrollBorder
= 64;
2662 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2663 // This assures that the autoscrolling speed grows gradually.
2664 const int incLimiter
= 1;
2666 if (pos
< autoScrollBorder
) {
2667 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2668 inc
= qMax(inc
, -maxSpeed
);
2669 inc
= qMax(inc
, oldInc
- incLimiter
);
2670 } else if (pos
> range
- autoScrollBorder
) {
2671 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2672 inc
= qMin(inc
, maxSpeed
);
2673 inc
= qMin(inc
, oldInc
+ incLimiter
);
2679 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2681 const qreal availableSize
= size
- itemMargin
;
2682 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2688 KItemListCreatorBase::~KItemListCreatorBase()
2690 qDeleteAll(m_recycleableWidgets
);
2691 qDeleteAll(m_createdWidgets
);
2694 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2696 m_createdWidgets
.insert(widget
);
2699 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2701 Q_ASSERT(m_createdWidgets
.contains(widget
));
2702 m_createdWidgets
.remove(widget
);
2704 if (m_recycleableWidgets
.count() < 100) {
2705 m_recycleableWidgets
.append(widget
);
2706 widget
->setVisible(false);
2712 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2714 if (m_recycleableWidgets
.isEmpty()) {
2718 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2719 m_createdWidgets
.insert(widget
);
2723 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2727 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2729 widget
->setParentItem(nullptr);
2730 widget
->setOpacity(1.0);
2731 pushRecycleableWidget(widget
);
2734 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2738 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2740 header
->setOpacity(1.0);
2741 pushRecycleableWidget(header
);