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 "kitemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
36 #include "private/kitemlistviewanimation.h"
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
42 #include <QStyleOptionRubberBand>
44 #include <QElapsedTimer>
48 #include "kitemlistviewaccessible.h"
51 // Time in ms until reaching the autoscroll margin triggers
52 // an initial autoscrolling
53 const int InitialAutoScrollDelay
= 700;
55 // Delay in ms for triggering the next autoscroll
56 const int RepeatingAutoScrollDelay
= 1000 / 60;
59 #ifndef QT_NO_ACCESSIBILITY
60 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
64 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
65 return new KItemListContainerAccessible(container
);
66 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
67 return new KItemListViewAccessible(view
);
74 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
75 QGraphicsWidget(parent
),
76 m_enabledSelectionToggles(false),
78 m_supportsItemExpanding(false),
80 m_activeTransactions(0),
81 m_endTransactionAnimationHint(Animation
),
87 m_groupHeaderCreator(0),
92 m_sizeHintResolver(0),
97 m_oldMaximumScrollOffset(0),
99 m_oldMaximumItemOffset(0),
100 m_skipAutoScrollForRubberBand(false),
103 m_autoScrollIncrement(0),
104 m_autoScrollTimer(0),
109 setAcceptHoverEvents(true);
111 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
113 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
115 m_animation
= new KItemListViewAnimation(this);
116 connect(m_animation
, &KItemListViewAnimation::finished
,
117 this, &KItemListView::slotAnimationFinished
);
119 m_layoutTimer
= new QTimer(this);
120 m_layoutTimer
->setInterval(300);
121 m_layoutTimer
->setSingleShot(true);
122 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
124 m_rubberBand
= new KItemListRubberBand(this);
125 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
127 m_headerWidget
= new KItemListHeaderWidget(this);
128 m_headerWidget
->setVisible(false);
130 m_header
= new KItemListHeader(this);
132 #ifndef QT_NO_ACCESSIBILITY
133 QAccessible::installFactory(accessibleInterfaceFactory
);
138 KItemListView::~KItemListView()
140 // The group headers are children of the widgets created by
141 // widgetCreator(). So it is mandatory to delete the group headers
143 delete m_groupHeaderCreator
;
144 m_groupHeaderCreator
= 0;
146 delete m_widgetCreator
;
149 delete m_sizeHintResolver
;
150 m_sizeHintResolver
= 0;
153 void KItemListView::setScrollOffset(qreal offset
)
159 const qreal previousOffset
= m_layouter
->scrollOffset();
160 if (offset
== previousOffset
) {
164 m_layouter
->setScrollOffset(offset
);
165 m_animation
->setScrollOffset(offset
);
167 // Don't check whether the m_layoutTimer is active: Changing the
168 // scroll offset must always trigger a synchronous layout, otherwise
169 // the smooth-scrolling might get jerky.
170 doLayout(NoAnimation
);
171 onScrollOffsetChanged(offset
, previousOffset
);
174 qreal
KItemListView::scrollOffset() const
176 return m_layouter
->scrollOffset();
179 qreal
KItemListView::maximumScrollOffset() const
181 return m_layouter
->maximumScrollOffset();
184 void KItemListView::setItemOffset(qreal offset
)
186 if (m_layouter
->itemOffset() == offset
) {
190 m_layouter
->setItemOffset(offset
);
191 if (m_headerWidget
->isVisible()) {
192 m_headerWidget
->setOffset(offset
);
195 // Don't check whether the m_layoutTimer is active: Changing the
196 // item offset must always trigger a synchronous layout, otherwise
197 // the smooth-scrolling might get jerky.
198 doLayout(NoAnimation
);
201 qreal
KItemListView::itemOffset() const
203 return m_layouter
->itemOffset();
206 qreal
KItemListView::maximumItemOffset() const
208 return m_layouter
->maximumItemOffset();
211 int KItemListView::maximumVisibleItems() const
213 return m_layouter
->maximumVisibleItems();
216 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
218 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
219 m_visibleRoles
= roles
;
220 onVisibleRolesChanged(roles
, previousRoles
);
222 m_sizeHintResolver
->clearCache();
223 m_layouter
->markAsDirty();
225 if (m_itemSize
.isEmpty()) {
226 m_headerWidget
->setColumns(roles
);
227 updatePreferredColumnWidths();
228 if (!m_headerWidget
->automaticColumnResizing()) {
229 // The column-width of new roles are still 0. Apply the preferred
230 // column-width as default with.
231 foreach (const QByteArray
& role
, m_visibleRoles
) {
232 if (m_headerWidget
->columnWidth(role
) == 0) {
233 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
234 m_headerWidget
->setColumnWidth(role
, width
);
238 applyColumnWidthsFromHeader();
242 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
243 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
244 (roles
.count() <= 1 && previousRoles
.count() > 1));
246 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
247 while (it
.hasNext()) {
249 KItemListWidget
* widget
= it
.value();
250 widget
->setVisibleRoles(roles
);
251 if (alternateBackgroundsChanged
) {
252 updateAlternateBackgroundForWidget(widget
);
256 doLayout(NoAnimation
);
259 QList
<QByteArray
> KItemListView::visibleRoles() const
261 return m_visibleRoles
;
264 void KItemListView::setAutoScroll(bool enabled
)
266 if (enabled
&& !m_autoScrollTimer
) {
267 m_autoScrollTimer
= new QTimer(this);
268 m_autoScrollTimer
->setSingleShot(true);
269 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
270 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
271 } else if (!enabled
&& m_autoScrollTimer
) {
272 delete m_autoScrollTimer
;
273 m_autoScrollTimer
= 0;
277 bool KItemListView::autoScroll() const
279 return m_autoScrollTimer
!= 0;
282 void KItemListView::setEnabledSelectionToggles(bool enabled
)
284 if (m_enabledSelectionToggles
!= enabled
) {
285 m_enabledSelectionToggles
= enabled
;
287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
288 while (it
.hasNext()) {
290 it
.value()->setEnabledSelectionToggle(enabled
);
295 bool KItemListView::enabledSelectionToggles() const
297 return m_enabledSelectionToggles
;
300 KItemListController
* KItemListView::controller() const
305 KItemModelBase
* KItemListView::model() const
310 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
312 if (m_widgetCreator
) {
313 delete m_widgetCreator
;
315 m_widgetCreator
= widgetCreator
;
318 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
320 if (!m_widgetCreator
) {
321 m_widgetCreator
= defaultWidgetCreator();
323 return m_widgetCreator
;
326 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
328 if (m_groupHeaderCreator
) {
329 delete m_groupHeaderCreator
;
331 m_groupHeaderCreator
= groupHeaderCreator
;
334 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
336 if (!m_groupHeaderCreator
) {
337 m_groupHeaderCreator
= defaultGroupHeaderCreator();
339 return m_groupHeaderCreator
;
342 QSizeF
KItemListView::itemSize() const
347 QSizeF
KItemListView::itemSizeHint() const
349 return m_sizeHintResolver
->maxSizeHint();
352 const KItemListStyleOption
& KItemListView::styleOption() const
354 return m_styleOption
;
357 void KItemListView::setGeometry(const QRectF
& rect
)
359 QGraphicsWidget::setGeometry(rect
);
365 const QSizeF newSize
= rect
.size();
366 if (m_itemSize
.isEmpty()) {
367 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
368 if (m_headerWidget
->automaticColumnResizing()) {
369 applyAutomaticColumnWidths();
371 const qreal requiredWidth
= columnWidthsSum();
372 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
373 m_itemSize
.height());
374 m_layouter
->setItemSize(dynamicItemSize
);
377 // Triggering a synchronous layout is fine from a performance point of view,
378 // as with dynamic item sizes no moving animation must be done.
379 m_layouter
->setSize(newSize
);
380 doLayout(NoAnimation
);
382 const bool animate
= !changesItemGridLayout(newSize
,
383 m_layouter
->itemSize(),
384 m_layouter
->itemMargin());
385 m_layouter
->setSize(newSize
);
388 // Trigger an asynchronous relayout with m_layoutTimer to prevent
389 // performance bottlenecks. If the timer is exceeded, an animated layout
390 // will be triggered.
391 if (!m_layoutTimer
->isActive()) {
392 m_layoutTimer
->start();
395 m_layoutTimer
->stop();
396 doLayout(NoAnimation
);
401 qreal
KItemListView::verticalPageStep() const
403 qreal headerHeight
= 0;
404 if (m_headerWidget
->isVisible()) {
405 headerHeight
= m_headerWidget
->size().height();
407 return size().height() - headerHeight
;
410 int KItemListView::itemAt(const QPointF
& pos
) const
412 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
413 while (it
.hasNext()) {
416 const KItemListWidget
* widget
= it
.value();
417 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
418 if (widget
->contains(mappedPos
)) {
426 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
428 if (!m_enabledSelectionToggles
) {
432 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
434 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
435 if (!selectionToggleRect
.isEmpty()) {
436 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
437 return selectionToggleRect
.contains(mappedPos
);
443 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
445 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
447 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
448 if (!expansionToggleRect
.isEmpty()) {
449 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
450 return expansionToggleRect
.contains(mappedPos
);
456 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
458 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
460 const QRectF
&textRect
= widget
->textRect();
461 if (!textRect
.isEmpty()) {
462 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
463 return textRect
.contains(mappedPos
);
469 int KItemListView::firstVisibleIndex() const
471 return m_layouter
->firstVisibleIndex();
474 int KItemListView::lastVisibleIndex() const
476 return m_layouter
->lastVisibleIndex();
479 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
481 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
484 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
486 if (m_supportsItemExpanding
!= supportsExpanding
) {
487 m_supportsItemExpanding
= supportsExpanding
;
488 updateSiblingsInformation();
489 onSupportsItemExpandingChanged(supportsExpanding
);
493 bool KItemListView::supportsItemExpanding() const
495 return m_supportsItemExpanding
;
498 QRectF
KItemListView::itemRect(int index
) const
500 return m_layouter
->itemRect(index
);
503 QRectF
KItemListView::itemContextRect(int index
) const
507 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
509 contextRect
= widget
->iconRect() | widget
->textRect();
510 contextRect
.translate(itemRect(index
).topLeft());
516 void KItemListView::scrollToItem(int index
)
518 QRectF viewGeometry
= geometry();
519 if (m_headerWidget
->isVisible()) {
520 const qreal headerHeight
= m_headerWidget
->size().height();
521 viewGeometry
.adjust(0, headerHeight
, 0, 0);
523 QRectF currentRect
= itemRect(index
);
525 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
526 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
527 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
529 if (!viewGeometry
.contains(currentRect
)) {
530 qreal newOffset
= scrollOffset();
531 if (scrollOrientation() == Qt::Vertical
) {
532 if (currentRect
.top() < viewGeometry
.top()) {
533 newOffset
+= currentRect
.top() - viewGeometry
.top();
534 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
535 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
538 if (currentRect
.left() < viewGeometry
.left()) {
539 newOffset
+= currentRect
.left() - viewGeometry
.left();
540 } else if (currentRect
.right() > viewGeometry
.right()) {
541 newOffset
+= currentRect
.right() - viewGeometry
.right();
545 if (newOffset
!= scrollOffset()) {
546 emit
scrollTo(newOffset
);
551 void KItemListView::beginTransaction()
553 ++m_activeTransactions
;
554 if (m_activeTransactions
== 1) {
555 onTransactionBegin();
559 void KItemListView::endTransaction()
561 --m_activeTransactions
;
562 if (m_activeTransactions
< 0) {
563 m_activeTransactions
= 0;
564 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
567 if (m_activeTransactions
== 0) {
569 doLayout(m_endTransactionAnimationHint
);
570 m_endTransactionAnimationHint
= Animation
;
574 bool KItemListView::isTransactionActive() const
576 return m_activeTransactions
> 0;
579 void KItemListView::setHeaderVisible(bool visible
)
581 if (visible
&& !m_headerWidget
->isVisible()) {
582 QStyleOptionHeader option
;
583 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
586 m_headerWidget
->setPos(0, 0);
587 m_headerWidget
->resize(size().width(), headerSize
.height());
588 m_headerWidget
->setModel(m_model
);
589 m_headerWidget
->setColumns(m_visibleRoles
);
590 m_headerWidget
->setZValue(1);
592 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
593 this, &KItemListView::slotHeaderColumnWidthChanged
);
594 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
595 this, &KItemListView::slotHeaderColumnMoved
);
596 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
597 this, &KItemListView::sortOrderChanged
);
598 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
599 this, &KItemListView::sortRoleChanged
);
601 m_layouter
->setHeaderHeight(headerSize
.height());
602 m_headerWidget
->setVisible(true);
603 } else if (!visible
&& m_headerWidget
->isVisible()) {
604 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
605 this, &KItemListView::slotHeaderColumnWidthChanged
);
606 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
607 this, &KItemListView::slotHeaderColumnMoved
);
608 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
609 this, &KItemListView::sortOrderChanged
);
610 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
611 this, &KItemListView::sortRoleChanged
);
613 m_layouter
->setHeaderHeight(0);
614 m_headerWidget
->setVisible(false);
618 bool KItemListView::isHeaderVisible() const
620 return m_headerWidget
->isVisible();
623 KItemListHeader
* KItemListView::header() const
628 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
632 if (indexes
.count() == 1) {
633 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
634 QGraphicsView
* graphicsView
= scene()->views()[0];
635 if (item
&& graphicsView
) {
636 pixmap
= item
->createDragPixmap(0, graphicsView
);
639 // TODO: Not implemented yet. Probably extend the interface
640 // from KItemListWidget::createDragPixmap() to return a pixmap
641 // that can be used for multiple indexes.
647 void KItemListView::editRole(int index
, const QByteArray
& role
)
649 KItemListWidget
* widget
= m_visibleItems
.value(index
);
650 if (!widget
|| m_editingRole
) {
654 m_editingRole
= true;
655 widget
->setEditedRole(role
);
657 connect(widget
, &KItemListWidget::roleEditingCanceled
,
658 this, &KItemListView::slotRoleEditingCanceled
);
659 connect(widget
, &KItemListWidget::roleEditingFinished
,
660 this, &KItemListView::slotRoleEditingFinished
);
663 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
665 QGraphicsWidget::paint(painter
, option
, widget
);
667 if (m_rubberBand
->isActive()) {
668 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
669 m_rubberBand
->endPosition()).normalized();
671 const QPointF topLeft
= rubberBandRect
.topLeft();
672 if (scrollOrientation() == Qt::Vertical
) {
673 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
675 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
678 QStyleOptionRubberBand opt
;
679 opt
.initFrom(widget
);
680 opt
.shape
= QRubberBand::Rectangle
;
682 opt
.rect
= rubberBandRect
.toRect();
683 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
686 if (!m_dropIndicator
.isEmpty()) {
687 const QRectF r
= m_dropIndicator
.toRect();
689 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
690 painter
->setPen(color
);
692 // TODO: The following implementation works only for a vertical scroll-orientation
693 // and assumes a height of the m_draggingInsertIndicator of 1.
694 Q_ASSERT(r
.height() == 1);
695 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
698 painter
->setPen(color
);
699 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
703 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
705 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
706 if (!scene()->views().isEmpty()) {
707 m_styleOption
.palette
= scene()->views().at(0)->palette();
710 return QGraphicsItem::itemChange(change
, value
);
713 void KItemListView::setItemSize(const QSizeF
& size
)
715 const QSizeF previousSize
= m_itemSize
;
716 if (size
== previousSize
) {
720 // Skip animations when the number of rows or columns
721 // are changed in the grid layout. Although the animation
722 // engine can handle this usecase, it looks obtrusive.
723 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
725 m_layouter
->itemMargin());
727 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
728 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
729 (!m_itemSize
.isEmpty() && size
.isEmpty()));
733 if (alternateBackgroundsChanged
) {
734 // For an empty item size alternate backgrounds are drawn if more than
735 // one role is shown. Assure that the backgrounds for visible items are
736 // updated when changing the size in this context.
737 updateAlternateBackgrounds();
740 if (size
.isEmpty()) {
741 if (m_headerWidget
->automaticColumnResizing()) {
742 updatePreferredColumnWidths();
744 // Only apply the changed height and respect the header widths
746 const qreal currentWidth
= m_layouter
->itemSize().width();
747 const QSizeF
newSize(currentWidth
, size
.height());
748 m_layouter
->setItemSize(newSize
);
751 m_layouter
->setItemSize(size
);
754 m_sizeHintResolver
->clearCache();
755 doLayout(animate
? Animation
: NoAnimation
);
756 onItemSizeChanged(size
, previousSize
);
759 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
761 const KItemListStyleOption previousOption
= m_styleOption
;
762 m_styleOption
= option
;
765 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
766 if (margin
!= m_layouter
->itemMargin()) {
767 // Skip animations when the number of rows or columns
768 // are changed in the grid layout. Although the animation
769 // engine can handle this usecase, it looks obtrusive.
770 animate
= !changesItemGridLayout(m_layouter
->size(),
771 m_layouter
->itemSize(),
773 m_layouter
->setItemMargin(margin
);
777 updateGroupHeaderHeight();
781 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
782 // Animating a change of the maximum text size just results in expensive
783 // temporary eliding and clipping operations and does not look good visually.
787 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
788 while (it
.hasNext()) {
790 it
.value()->setStyleOption(option
);
793 m_sizeHintResolver
->clearCache();
794 m_layouter
->markAsDirty();
795 doLayout(animate
? Animation
: NoAnimation
);
797 if (m_itemSize
.isEmpty()) {
798 updatePreferredColumnWidths();
801 onStyleOptionChanged(option
, previousOption
);
804 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
806 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
807 if (orientation
== previousOrientation
) {
811 m_layouter
->setScrollOrientation(orientation
);
812 m_animation
->setScrollOrientation(orientation
);
813 m_sizeHintResolver
->clearCache();
816 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
817 while (it
.hasNext()) {
819 it
.value()->setScrollOrientation(orientation
);
821 updateGroupHeaderHeight();
825 doLayout(NoAnimation
);
827 onScrollOrientationChanged(orientation
, previousOrientation
);
828 emit
scrollOrientationChanged(orientation
, previousOrientation
);
831 Qt::Orientation
KItemListView::scrollOrientation() const
833 return m_layouter
->scrollOrientation();
836 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
841 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
846 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
851 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
853 Q_UNUSED(changedRoles
);
857 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
863 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
869 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
875 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
881 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
887 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
893 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
899 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
901 Q_UNUSED(supportsExpanding
);
904 void KItemListView::onTransactionBegin()
908 void KItemListView::onTransactionEnd()
912 bool KItemListView::event(QEvent
* event
)
914 switch (event
->type()) {
915 case QEvent::PaletteChange
:
919 case QEvent::FontChange
:
924 // Forward all other events to the controller and handle them there
925 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
931 return QGraphicsWidget::event(event
);
934 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
936 m_mousePos
= transform().map(event
->pos());
940 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
942 QGraphicsWidget::mouseMoveEvent(event
);
944 m_mousePos
= transform().map(event
->pos());
945 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
946 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
950 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
952 event
->setAccepted(true);
956 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
958 QGraphicsWidget::dragMoveEvent(event
);
960 m_mousePos
= transform().map(event
->pos());
961 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
962 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
966 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
968 QGraphicsWidget::dragLeaveEvent(event
);
969 setAutoScroll(false);
972 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
974 QGraphicsWidget::dropEvent(event
);
975 setAutoScroll(false);
978 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
980 return m_visibleItems
.values();
983 void KItemListView::updateFont()
985 if (scene() && !scene()->views().isEmpty()) {
986 KItemListStyleOption option
= styleOption();
987 option
.font
= scene()->views().first()->font();
988 option
.fontMetrics
= QFontMetrics(option
.font
);
990 setStyleOption(option
);
994 void KItemListView::updatePalette()
996 if (scene() && !scene()->views().isEmpty()) {
997 KItemListStyleOption option
= styleOption();
998 option
.palette
= scene()->views().first()->palette();
1000 setStyleOption(option
);
1004 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1006 if (m_itemSize
.isEmpty()) {
1007 updatePreferredColumnWidths(itemRanges
);
1010 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1011 if (hasMultipleRanges
) {
1015 m_layouter
->markAsDirty();
1017 m_sizeHintResolver
->itemsInserted(itemRanges
);
1019 int previouslyInsertedCount
= 0;
1020 foreach (const KItemRange
& range
, itemRanges
) {
1021 // range.index is related to the model before anything has been inserted.
1022 // As in each loop the current item-range gets inserted the index must
1023 // be increased by the already previously inserted items.
1024 const int index
= range
.index
+ previouslyInsertedCount
;
1025 const int count
= range
.count
;
1026 if (index
< 0 || count
<= 0) {
1027 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1030 previouslyInsertedCount
+= count
;
1032 // Determine which visible items must be moved
1033 QList
<int> itemsToMove
;
1034 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1035 while (it
.hasNext()) {
1037 const int visibleItemIndex
= it
.key();
1038 if (visibleItemIndex
>= index
) {
1039 itemsToMove
.append(visibleItemIndex
);
1043 // Update the indexes of all KItemListWidget instances that are located
1044 // after the inserted items. It is important to adjust the indexes in the order
1045 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1047 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1048 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1050 const int newIndex
= widget
->index() + count
;
1051 if (hasMultipleRanges
) {
1052 setWidgetIndex(widget
, newIndex
);
1054 // Try to animate the moving of the item
1055 moveWidgetToIndex(widget
, newIndex
);
1059 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1060 // Check whether a scrollbar is required to show the inserted items. In this case
1061 // the size of the layouter will be decreased before calling doLayout(): This prevents
1062 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1063 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1064 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1065 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1066 if (decreaseLayouterSize
) {
1067 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1069 int scrollbarSpacing
= 0;
1070 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1071 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1074 QSizeF layouterSize
= m_layouter
->size();
1075 if (verticalScrollOrientation
) {
1076 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1078 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1080 m_layouter
->setSize(layouterSize
);
1084 if (!hasMultipleRanges
) {
1085 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1086 updateSiblingsInformation();
1091 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1094 if (hasMultipleRanges
) {
1095 m_endTransactionAnimationHint
= NoAnimation
;
1098 updateSiblingsInformation();
1101 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1102 // In case if items of the same group have been inserted before an item that
1103 // currently represents the first item of the group, the group header of
1104 // this item must be removed.
1105 updateVisibleGroupHeaders();
1108 if (useAlternateBackgrounds()) {
1109 updateAlternateBackgrounds();
1113 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1115 if (m_itemSize
.isEmpty()) {
1116 // Don't pass the item-range: The preferred column-widths of
1117 // all items must be adjusted when removing items.
1118 updatePreferredColumnWidths();
1121 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1122 if (hasMultipleRanges
) {
1126 m_layouter
->markAsDirty();
1128 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1130 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1131 const KItemRange
& range
= itemRanges
[i
];
1132 const int index
= range
.index
;
1133 const int count
= range
.count
;
1134 if (index
< 0 || count
<= 0) {
1135 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1139 const int firstRemovedIndex
= index
;
1140 const int lastRemovedIndex
= index
+ count
- 1;
1142 // Remember which items have to be moved because they are behind the removed range.
1143 QVector
<int> itemsToMove
;
1145 // Remove all KItemListWidget instances that got deleted
1146 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1147 const int i
= widget
->index();
1148 if (i
< firstRemovedIndex
) {
1150 } else if (i
> lastRemovedIndex
) {
1151 itemsToMove
.append(i
);
1155 m_animation
->stop(widget
);
1156 // Stopping the animation might lead to recycling the widget if
1157 // it is invisible (see slotAnimationFinished()).
1158 // Check again whether it is still visible:
1159 if (!m_visibleItems
.contains(i
)) {
1163 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1164 // Remove the widget without animation
1165 recycleWidget(widget
);
1167 // Animate the removing of the items. Special case: When removing an item there
1168 // is no valid model index available anymore. For the
1169 // remove-animation the item gets removed from m_visibleItems but the widget
1170 // will stay alive until the animation has been finished and will
1171 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1172 m_visibleItems
.remove(i
);
1173 widget
->setIndex(-1);
1174 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1178 // Update the indexes of all KItemListWidget instances that are located
1179 // after the deleted items. It is important to update them in ascending
1180 // order to prevent overlaps when setting the new index.
1181 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1182 foreach (int i
, itemsToMove
) {
1183 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1185 const int newIndex
= i
- count
;
1186 if (hasMultipleRanges
) {
1187 setWidgetIndex(widget
, newIndex
);
1189 // Try to animate the moving of the item
1190 moveWidgetToIndex(widget
, newIndex
);
1194 if (!hasMultipleRanges
) {
1195 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1196 // assumes an updated geometry. If items are removed during an active transaction,
1197 // the transaction will be temporary deactivated so that doLayout() triggers a
1198 // geometry update if necessary.
1199 const int activeTransactions
= m_activeTransactions
;
1200 m_activeTransactions
= 0;
1201 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1202 m_activeTransactions
= activeTransactions
;
1203 updateSiblingsInformation();
1208 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1211 if (hasMultipleRanges
) {
1212 m_endTransactionAnimationHint
= NoAnimation
;
1214 updateSiblingsInformation();
1217 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1218 // In case if the first item of a group has been removed, the group header
1219 // must be applied to the next visible item.
1220 updateVisibleGroupHeaders();
1223 if (useAlternateBackgrounds()) {
1224 updateAlternateBackgrounds();
1228 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1230 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1231 m_layouter
->markAsDirty();
1234 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1237 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1238 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1240 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1241 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1243 updateWidgetProperties(widget
, index
);
1244 initializeItemListWidget(widget
);
1248 doLayout(NoAnimation
);
1249 updateSiblingsInformation();
1252 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1253 const QSet
<QByteArray
>& roles
)
1255 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1256 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1257 updatePreferredColumnWidths(itemRanges
);
1260 foreach (const KItemRange
& itemRange
, itemRanges
) {
1261 const int index
= itemRange
.index
;
1262 const int count
= itemRange
.count
;
1264 if (updateSizeHints
) {
1265 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1266 m_layouter
->markAsDirty();
1268 if (!m_layoutTimer
->isActive()) {
1269 m_layoutTimer
->start();
1273 // Apply the changed roles to the visible item-widgets
1274 const int lastIndex
= index
+ count
- 1;
1275 for (int i
= index
; i
<= lastIndex
; ++i
) {
1276 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1278 widget
->setData(m_model
->data(i
), roles
);
1282 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1283 // The sort-role has been changed which might result
1284 // in modified group headers
1285 updateVisibleGroupHeaders();
1286 doLayout(NoAnimation
);
1289 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1290 ev
.setFirstRow(itemRange
.index
);
1291 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1292 QAccessible::updateAccessibility(&ev
);
1296 void KItemListView::slotGroupsChanged()
1298 updateVisibleGroupHeaders();
1299 doLayout(NoAnimation
);
1300 updateSiblingsInformation();
1303 void KItemListView::slotGroupedSortingChanged(bool current
)
1305 m_grouped
= current
;
1306 m_layouter
->markAsDirty();
1309 updateGroupHeaderHeight();
1311 // Clear all visible headers. Note that the QHashIterator takes a copy of
1312 // m_visibleGroups. Therefore, it remains valid even if items are removed
1313 // from m_visibleGroups in recycleGroupHeaderForWidget().
1314 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1315 while (it
.hasNext()) {
1317 recycleGroupHeaderForWidget(it
.key());
1319 Q_ASSERT(m_visibleGroups
.isEmpty());
1322 if (useAlternateBackgrounds()) {
1323 // Changing the group mode requires to update the alternate backgrounds
1324 // as with the enabled group mode the altering is done on base of the first
1326 updateAlternateBackgrounds();
1328 updateSiblingsInformation();
1329 doLayout(NoAnimation
);
1332 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1337 updateVisibleGroupHeaders();
1338 doLayout(NoAnimation
);
1342 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1347 updateVisibleGroupHeaders();
1348 doLayout(NoAnimation
);
1352 void KItemListView::slotCurrentChanged(int current
, int previous
)
1356 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1357 // always the selected item. It is not necessary to highlight the current item then.
1358 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1359 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1360 if (previousWidget
) {
1361 previousWidget
->setCurrent(false);
1364 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1365 if (currentWidget
) {
1366 currentWidget
->setCurrent(true);
1370 QAccessibleEvent
ev(this, QAccessible::Focus
);
1371 ev
.setChild(current
);
1372 QAccessible::updateAccessibility(&ev
);
1375 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1379 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1380 while (it
.hasNext()) {
1382 const int index
= it
.key();
1383 KItemListWidget
* widget
= it
.value();
1384 widget
->setSelected(current
.contains(index
));
1388 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1389 KItemListViewAnimation::AnimationType type
)
1391 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1392 Q_ASSERT(itemListWidget
);
1395 case KItemListViewAnimation::DeleteAnimation
: {
1396 // As we recycle the widget in this case it is important to assure that no
1397 // other animation has been started. This is a convention in KItemListView and
1398 // not a requirement defined by KItemListViewAnimation.
1399 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1401 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1402 // by m_visibleWidgets and must be deleted manually after the animation has
1404 recycleGroupHeaderForWidget(itemListWidget
);
1405 widgetCreator()->recycle(itemListWidget
);
1409 case KItemListViewAnimation::CreateAnimation
:
1410 case KItemListViewAnimation::MovingAnimation
:
1411 case KItemListViewAnimation::ResizeAnimation
: {
1412 const int index
= itemListWidget
->index();
1413 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1414 (index
> m_layouter
->lastVisibleIndex());
1415 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1416 recycleWidget(itemListWidget
);
1425 void KItemListView::slotLayoutTimerFinished()
1427 m_layouter
->setSize(geometry().size());
1428 doLayout(Animation
);
1431 void KItemListView::slotRubberBandPosChanged()
1436 void KItemListView::slotRubberBandActivationChanged(bool active
)
1439 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1440 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1441 m_skipAutoScrollForRubberBand
= true;
1443 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1444 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1445 m_skipAutoScrollForRubberBand
= false;
1451 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1453 qreal previousWidth
)
1456 Q_UNUSED(currentWidth
);
1457 Q_UNUSED(previousWidth
);
1459 m_headerWidget
->setAutomaticColumnResizing(false);
1460 applyColumnWidthsFromHeader();
1461 doLayout(NoAnimation
);
1464 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1468 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1470 const QList
<QByteArray
> previous
= m_visibleRoles
;
1472 QList
<QByteArray
> current
= m_visibleRoles
;
1473 current
.removeAt(previousIndex
);
1474 current
.insert(currentIndex
, role
);
1476 setVisibleRoles(current
);
1478 emit
visibleRolesChanged(current
, previous
);
1481 void KItemListView::triggerAutoScrolling()
1483 if (!m_autoScrollTimer
) {
1488 int visibleSize
= 0;
1489 if (scrollOrientation() == Qt::Vertical
) {
1490 pos
= m_mousePos
.y();
1491 visibleSize
= size().height();
1493 pos
= m_mousePos
.x();
1494 visibleSize
= size().width();
1497 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1498 m_autoScrollIncrement
= 0;
1501 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1502 if (m_autoScrollIncrement
== 0) {
1503 // The mouse position is not above an autoscroll margin (the autoscroll timer
1504 // will be restarted in mouseMoveEvent())
1505 m_autoScrollTimer
->stop();
1509 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1510 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1511 // if the direction of the rubberband is similar to the autoscroll direction. This
1512 // prevents that starting to create a rubberband within the autoscroll margins starts
1513 // an autoscrolling.
1515 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1516 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1517 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1518 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1519 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1520 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1521 // been moved up although the autoscroll direction might be down)
1522 m_autoScrollTimer
->stop();
1527 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1528 // the autoscrolling may not get skipped anymore until a new rubberband is created
1529 m_skipAutoScrollForRubberBand
= false;
1531 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1532 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1533 setScrollOffset(newScrollOffset
);
1535 // Trigger the autoscroll timer which will periodically call
1536 // triggerAutoScrolling()
1537 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1540 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1542 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1544 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1545 Q_ASSERT(groupHeader
);
1546 updateGroupHeaderLayout(widget
);
1549 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1551 disconnectRoleEditingSignals(index
);
1553 emit
roleEditingCanceled(index
, role
, value
);
1554 m_editingRole
= false;
1557 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1559 disconnectRoleEditingSignals(index
);
1561 emit
roleEditingFinished(index
, role
, value
);
1562 m_editingRole
= false;
1565 void KItemListView::setController(KItemListController
* controller
)
1567 if (m_controller
!= controller
) {
1568 KItemListController
* previous
= m_controller
;
1570 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1571 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1572 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1575 m_controller
= controller
;
1578 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1579 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1580 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1583 onControllerChanged(controller
, previous
);
1587 void KItemListView::setModel(KItemModelBase
* model
)
1589 if (m_model
== model
) {
1593 KItemModelBase
* previous
= m_model
;
1596 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1597 this, &KItemListView::slotItemsChanged
);
1598 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1599 this, &KItemListView::slotItemsInserted
);
1600 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1601 this, &KItemListView::slotItemsRemoved
);
1602 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1603 this, &KItemListView::slotItemsMoved
);
1604 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1605 this, &KItemListView::slotGroupsChanged
);
1606 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1607 this, &KItemListView::slotGroupedSortingChanged
);
1608 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1609 this, &KItemListView::slotSortOrderChanged
);
1610 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1611 this, &KItemListView::slotSortRoleChanged
);
1613 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1617 m_layouter
->setModel(model
);
1618 m_grouped
= model
->groupedSorting();
1621 connect(m_model
, &KItemModelBase::itemsChanged
,
1622 this, &KItemListView::slotItemsChanged
);
1623 connect(m_model
, &KItemModelBase::itemsInserted
,
1624 this, &KItemListView::slotItemsInserted
);
1625 connect(m_model
, &KItemModelBase::itemsRemoved
,
1626 this, &KItemListView::slotItemsRemoved
);
1627 connect(m_model
, &KItemModelBase::itemsMoved
,
1628 this, &KItemListView::slotItemsMoved
);
1629 connect(m_model
, &KItemModelBase::groupsChanged
,
1630 this, &KItemListView::slotGroupsChanged
);
1631 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1632 this, &KItemListView::slotGroupedSortingChanged
);
1633 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1634 this, &KItemListView::slotSortOrderChanged
);
1635 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1636 this, &KItemListView::slotSortRoleChanged
);
1638 const int itemCount
= m_model
->count();
1639 if (itemCount
> 0) {
1640 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1644 onModelChanged(model
, previous
);
1647 KItemListRubberBand
* KItemListView::rubberBand() const
1649 return m_rubberBand
;
1652 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1654 if (m_layoutTimer
->isActive()) {
1655 m_layoutTimer
->stop();
1658 if (m_activeTransactions
> 0) {
1659 if (hint
== NoAnimation
) {
1660 // As soon as at least one property change should be done without animation,
1661 // the whole transaction will be marked as not animated.
1662 m_endTransactionAnimationHint
= NoAnimation
;
1667 if (!m_model
|| m_model
->count() < 0) {
1671 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1672 if (firstVisibleIndex
< 0) {
1673 emitOffsetChanges();
1677 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1678 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1679 // is still shown if the maximum offset got decreased.
1680 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1681 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1682 if (scrollOffset() > maxOffsetToShowFullRange
) {
1683 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1684 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1687 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1689 int firstSibblingIndex
= -1;
1690 int lastSibblingIndex
= -1;
1691 const bool supportsExpanding
= supportsItemExpanding();
1693 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1695 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1696 // instances from invisible items are reused. If no reusable items are
1697 // found then new KItemListWidget instances get created.
1698 const bool animate
= (hint
== Animation
);
1699 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1700 bool applyNewPos
= true;
1701 bool wasHidden
= false;
1703 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1704 const QPointF newPos
= itemBounds
.topLeft();
1705 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1708 if (!reusableItems
.isEmpty()) {
1709 // Reuse a KItemListWidget instance from an invisible item
1710 const int oldIndex
= reusableItems
.takeLast();
1711 widget
= m_visibleItems
.value(oldIndex
);
1712 setWidgetIndex(widget
, i
);
1713 updateWidgetProperties(widget
, i
);
1714 initializeItemListWidget(widget
);
1716 // No reusable KItemListWidget instance is available, create a new one
1717 widget
= createWidget(i
);
1719 widget
->resize(itemBounds
.size());
1721 if (animate
&& changedCount
< 0) {
1722 // Items have been deleted.
1723 if (i
>= changedIndex
) {
1724 // The item is located behind the removed range. Move the
1725 // created item to the imaginary old position outside the
1726 // view. It will get animated to the new position later.
1727 const int previousIndex
= i
- changedCount
;
1728 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1729 if (itemRect
.isEmpty()) {
1730 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1731 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1732 widget
->setPos(invisibleOldPos
);
1734 widget
->setPos(itemRect
.topLeft());
1736 applyNewPos
= false;
1740 if (supportsExpanding
&& changedCount
== 0) {
1741 if (firstSibblingIndex
< 0) {
1742 firstSibblingIndex
= i
;
1744 lastSibblingIndex
= i
;
1749 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1750 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1751 applyNewPos
= false;
1754 const bool itemsRemoved
= (changedCount
< 0);
1755 const bool itemsInserted
= (changedCount
> 0);
1756 if (itemsRemoved
&& (i
>= changedIndex
)) {
1757 // The item is located after the removed items. Animate the moving of the position.
1758 applyNewPos
= !moveWidget(widget
, newPos
);
1759 } else if (itemsInserted
&& i
>= changedIndex
) {
1760 // The item is located after the first inserted item
1761 if (i
<= changedIndex
+ changedCount
- 1) {
1762 // The item is an inserted item. Animate the appearing of the item.
1763 // For performance reasons no animation is done when changedCount is equal
1764 // to all available items.
1765 if (changedCount
< m_model
->count()) {
1766 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1768 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1769 // The item was already there before, so animate the moving of the position.
1770 // No moving animation is done if the item is animated by a create animation: This
1771 // prevents a "move animation mess" when inserting several ranges in parallel.
1772 applyNewPos
= !moveWidget(widget
, newPos
);
1774 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1775 // The size of the view might have been changed. Animate the moving of the position.
1776 applyNewPos
= !moveWidget(widget
, newPos
);
1779 m_animation
->stop(widget
);
1783 widget
->setPos(newPos
);
1786 Q_ASSERT(widget
->index() == i
);
1787 widget
->setVisible(true);
1789 if (widget
->size() != itemBounds
.size()) {
1790 // Resize the widget for the item to the changed size.
1792 // If a dynamic item size is used then no animation is done in the direction
1793 // of the dynamic size.
1794 if (m_itemSize
.width() <= 0) {
1795 // The width is dynamic, apply the new width without animation.
1796 widget
->resize(itemBounds
.width(), widget
->size().height());
1797 } else if (m_itemSize
.height() <= 0) {
1798 // The height is dynamic, apply the new height without animation.
1799 widget
->resize(widget
->size().width(), itemBounds
.height());
1801 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1803 widget
->resize(itemBounds
.size());
1807 // Updating the cell-information must be done as last step: The decision whether the
1808 // moving-animation should be started at all is based on the previous cell-information.
1809 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1810 m_visibleCells
.insert(i
, cell
);
1813 // Delete invisible KItemListWidget instances that have not been reused
1814 foreach (int index
, reusableItems
) {
1815 recycleWidget(m_visibleItems
.value(index
));
1818 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1819 Q_ASSERT(lastSibblingIndex
>= 0);
1820 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1824 // Update the layout of all visible group headers
1825 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1826 while (it
.hasNext()) {
1828 updateGroupHeaderLayout(it
.key());
1832 emitOffsetChanges();
1835 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1836 int lastVisibleIndex
,
1837 LayoutAnimationHint hint
)
1839 // Determine all items that are completely invisible and might be
1840 // reused for items that just got (at least partly) visible. If the
1841 // animation hint is set to 'Animation' items that do e.g. an animated
1842 // moving of their position are not marked as invisible: This assures
1843 // that a scrolling inside the view can be done without breaking an animation.
1847 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1848 while (it
.hasNext()) {
1851 KItemListWidget
* widget
= it
.value();
1852 const int index
= widget
->index();
1853 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1856 if (m_animation
->isStarted(widget
)) {
1857 if (hint
== NoAnimation
) {
1858 // Stopping the animation will call KItemListView::slotAnimationFinished()
1859 // and the widget will be recycled if necessary there.
1860 m_animation
->stop(widget
);
1863 widget
->setVisible(false);
1864 items
.append(index
);
1867 recycleGroupHeaderForWidget(widget
);
1876 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1878 if (widget
->pos() == newPos
) {
1882 bool startMovingAnim
= false;
1884 if (m_itemSize
.isEmpty()) {
1885 // The items are not aligned in a grid but either as columns or rows.
1886 startMovingAnim
= true;
1888 // When having a grid the moving-animation should only be started, if it is done within
1889 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1890 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1891 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1892 const int index
= widget
->index();
1893 const Cell cell
= m_visibleCells
.value(index
);
1894 if (cell
.column
>= 0 && cell
.row
>= 0) {
1895 if (scrollOrientation() == Qt::Vertical
) {
1896 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1898 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1903 if (startMovingAnim
) {
1904 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1908 m_animation
->stop(widget
);
1909 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1913 void KItemListView::emitOffsetChanges()
1915 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1916 if (m_oldScrollOffset
!= newScrollOffset
) {
1917 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1918 m_oldScrollOffset
= newScrollOffset
;
1921 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1922 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1923 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1924 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1927 const qreal newItemOffset
= m_layouter
->itemOffset();
1928 if (m_oldItemOffset
!= newItemOffset
) {
1929 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1930 m_oldItemOffset
= newItemOffset
;
1933 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1934 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1935 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1936 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1940 KItemListWidget
* KItemListView::createWidget(int index
)
1942 KItemListWidget
* widget
= widgetCreator()->create(this);
1943 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1945 m_visibleItems
.insert(index
, widget
);
1946 m_visibleCells
.insert(index
, Cell());
1947 updateWidgetProperties(widget
, index
);
1948 initializeItemListWidget(widget
);
1952 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1955 recycleGroupHeaderForWidget(widget
);
1958 const int index
= widget
->index();
1959 m_visibleItems
.remove(index
);
1960 m_visibleCells
.remove(index
);
1962 widgetCreator()->recycle(widget
);
1965 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1967 const int oldIndex
= widget
->index();
1968 m_visibleItems
.remove(oldIndex
);
1969 m_visibleCells
.remove(oldIndex
);
1971 m_visibleItems
.insert(index
, widget
);
1972 m_visibleCells
.insert(index
, Cell());
1974 widget
->setIndex(index
);
1977 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1979 const int oldIndex
= widget
->index();
1980 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1982 setWidgetIndex(widget
, index
);
1984 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1985 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1986 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1987 (!vertical
&& oldCell
.column
== newCell
.column
);
1989 m_visibleCells
.insert(index
, newCell
);
1993 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1996 case LayouterSize
: m_layouter
->setSize(size
); break;
1997 case ItemSize
: m_layouter
->setItemSize(size
); break;
2002 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2004 widget
->setVisibleRoles(m_visibleRoles
);
2005 updateWidgetColumnWidths(widget
);
2006 widget
->setStyleOption(m_styleOption
);
2008 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2010 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2011 // always the selected item. It is not necessary to highlight the current item then.
2012 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2013 widget
->setCurrent(index
== selectionManager
->currentItem());
2015 widget
->setSelected(selectionManager
->isSelected(index
));
2016 widget
->setHovered(false);
2017 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2018 widget
->setIndex(index
);
2019 widget
->setData(m_model
->data(index
));
2020 widget
->setSiblingsInformation(QBitArray());
2021 updateAlternateBackgroundForWidget(widget
);
2024 updateGroupHeaderForWidget(widget
);
2028 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2030 Q_ASSERT(m_grouped
);
2032 const int index
= widget
->index();
2033 if (!m_layouter
->isFirstGroupItem(index
)) {
2034 // The widget does not represent the first item of a group
2035 // and hence requires no header
2036 recycleGroupHeaderForWidget(widget
);
2040 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2041 if (groups
.isEmpty() || !groupHeaderCreator()) {
2045 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2047 groupHeader
= groupHeaderCreator()->create(this);
2048 groupHeader
->setParentItem(widget
);
2049 m_visibleGroups
.insert(widget
, groupHeader
);
2050 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2052 Q_ASSERT(groupHeader
->parentItem() == widget
);
2054 const int groupIndex
= groupIndexForItem(index
);
2055 Q_ASSERT(groupIndex
>= 0);
2056 groupHeader
->setData(groups
.at(groupIndex
).second
);
2057 groupHeader
->setRole(model()->sortRole());
2058 groupHeader
->setStyleOption(m_styleOption
);
2059 groupHeader
->setScrollOrientation(scrollOrientation());
2060 groupHeader
->setItemIndex(index
);
2062 groupHeader
->show();
2065 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2067 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2068 Q_ASSERT(groupHeader
);
2070 const int index
= widget
->index();
2071 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2072 const QRectF itemRect
= m_layouter
->itemRect(index
);
2074 // The group-header is a child of the itemlist widget. Translate the
2075 // group header position to the relative position.
2076 if (scrollOrientation() == Qt::Vertical
) {
2077 // In the vertical scroll orientation the group header should always span
2078 // the whole width no matter which temporary position the parent widget
2079 // has. In this case the x-position and width will be adjusted manually.
2080 const qreal x
= -widget
->x() - itemOffset();
2081 const qreal width
= maximumItemOffset();
2082 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2083 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2085 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2086 groupHeader
->resize(groupHeaderRect
.size());
2090 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2092 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2094 header
->setParentItem(0);
2095 groupHeaderCreator()->recycle(header
);
2096 m_visibleGroups
.remove(widget
);
2097 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2101 void KItemListView::updateVisibleGroupHeaders()
2103 Q_ASSERT(m_grouped
);
2104 m_layouter
->markAsDirty();
2106 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2107 while (it
.hasNext()) {
2109 updateGroupHeaderForWidget(it
.value());
2113 int KItemListView::groupIndexForItem(int index
) const
2115 Q_ASSERT(m_grouped
);
2117 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2118 if (groups
.isEmpty()) {
2123 int max
= groups
.count() - 1;
2126 mid
= (min
+ max
) / 2;
2127 if (index
> groups
[mid
].first
) {
2132 } while (groups
[mid
].first
!= index
&& min
<= max
);
2135 while (groups
[mid
].first
> index
&& mid
> 0) {
2143 void KItemListView::updateAlternateBackgrounds()
2145 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2146 while (it
.hasNext()) {
2148 updateAlternateBackgroundForWidget(it
.value());
2152 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2154 bool enabled
= useAlternateBackgrounds();
2156 const int index
= widget
->index();
2157 enabled
= (index
& 0x1) > 0;
2159 const int groupIndex
= groupIndexForItem(index
);
2160 if (groupIndex
>= 0) {
2161 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2162 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2163 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2164 enabled
= (relativeIndex
& 0x1) > 0;
2168 widget
->setAlternateBackground(enabled
);
2171 bool KItemListView::useAlternateBackgrounds() const
2173 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2176 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2178 QElapsedTimer timer
;
2181 QHash
<QByteArray
, qreal
> widths
;
2183 // Calculate the minimum width for each column that is required
2184 // to show the headline unclipped.
2185 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2186 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2187 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2188 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2189 const QString headerText
= m_model
->roleDescription(visibleRole
);
2190 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2191 widths
.insert(visibleRole
, headerWidth
);
2194 // Calculate the preferred column withs for each item and ignore values
2195 // smaller than the width for showing the headline unclipped.
2196 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2197 int calculatedItemCount
= 0;
2198 bool maxTimeExceeded
= false;
2199 foreach (const KItemRange
& itemRange
, itemRanges
) {
2200 const int startIndex
= itemRange
.index
;
2201 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2203 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2204 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2205 qreal maxWidth
= widths
.value(visibleRole
, 0);
2206 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2207 maxWidth
= qMax(width
, maxWidth
);
2208 widths
.insert(visibleRole
, maxWidth
);
2211 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2212 // When having several thousands of items calculating the sizes can get
2213 // very expensive. We accept a possibly too small role-size in favour
2214 // of having no blocking user interface.
2215 maxTimeExceeded
= true;
2218 ++calculatedItemCount
;
2220 if (maxTimeExceeded
) {
2228 void KItemListView::applyColumnWidthsFromHeader()
2230 // Apply the new size to the layouter
2231 const qreal requiredWidth
= columnWidthsSum();
2232 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2233 m_itemSize
.height());
2234 m_layouter
->setItemSize(dynamicItemSize
);
2236 // Update the role sizes for all visible widgets
2237 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2238 while (it
.hasNext()) {
2240 updateWidgetColumnWidths(it
.value());
2244 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2246 foreach (const QByteArray
& role
, m_visibleRoles
) {
2247 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2251 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2253 Q_ASSERT(m_itemSize
.isEmpty());
2254 const int itemCount
= m_model
->count();
2255 int rangesItemCount
= 0;
2256 foreach (const KItemRange
& range
, itemRanges
) {
2257 rangesItemCount
+= range
.count
;
2260 if (itemCount
== rangesItemCount
) {
2261 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2262 foreach (const QByteArray
& role
, m_visibleRoles
) {
2263 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2266 // Only a sub range of the roles need to be determined.
2267 // The chances are good that the widths of the sub ranges
2268 // already fit into the available widths and hence no
2269 // expensive update might be required.
2270 bool changed
= false;
2272 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2273 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2274 while (it
.hasNext()) {
2276 const QByteArray
& role
= it
.key();
2277 const qreal updatedWidth
= it
.value();
2278 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2279 if (updatedWidth
> currentWidth
) {
2280 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2286 // All the updated sizes are smaller than the current sizes and no change
2287 // of the stretched roles-widths is required
2292 if (m_headerWidget
->automaticColumnResizing()) {
2293 applyAutomaticColumnWidths();
2297 void KItemListView::updatePreferredColumnWidths()
2300 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2304 void KItemListView::applyAutomaticColumnWidths()
2306 Q_ASSERT(m_itemSize
.isEmpty());
2307 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2308 if (m_visibleRoles
.isEmpty()) {
2312 // Calculate the maximum size of an item by considering the
2313 // visible role sizes and apply them to the layouter. If the
2314 // size does not use the available view-size the size of the
2315 // first role will get stretched.
2317 foreach (const QByteArray
& role
, m_visibleRoles
) {
2318 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2319 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2322 const QByteArray firstRole
= m_visibleRoles
.first();
2323 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2324 QSizeF dynamicItemSize
= m_itemSize
;
2326 qreal requiredWidth
= columnWidthsSum();
2327 const qreal availableWidth
= size().width();
2328 if (requiredWidth
< availableWidth
) {
2329 // Stretch the first column to use the whole remaining width
2330 firstColumnWidth
+= availableWidth
- requiredWidth
;
2331 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2332 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2333 // Shrink the first column to be able to show as much other
2334 // columns as possible
2335 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2337 // TODO: A proper calculation of the minimum width depends on the implementation
2338 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2340 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2341 if (shrinkedFirstColumnWidth
< minWidth
) {
2342 shrinkedFirstColumnWidth
= minWidth
;
2345 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2346 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2349 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2351 m_layouter
->setItemSize(dynamicItemSize
);
2353 // Update the role sizes for all visible widgets
2354 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2355 while (it
.hasNext()) {
2357 updateWidgetColumnWidths(it
.value());
2361 qreal
KItemListView::columnWidthsSum() const
2363 qreal widthsSum
= 0;
2364 foreach (const QByteArray
& role
, m_visibleRoles
) {
2365 widthsSum
+= m_headerWidget
->columnWidth(role
);
2370 QRectF
KItemListView::headerBoundaries() const
2372 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2375 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2376 const QSizeF
& newItemSize
,
2377 const QSizeF
& newItemMargin
) const
2379 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2383 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2384 const qreal itemWidth
= m_layouter
->itemSize().width();
2385 if (itemWidth
> 0) {
2386 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2387 newItemSize
.width(),
2388 newItemMargin
.width());
2389 if (m_model
->count() > newColumnCount
) {
2390 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2392 m_layouter
->itemMargin().width());
2393 return oldColumnCount
!= newColumnCount
;
2397 const qreal itemHeight
= m_layouter
->itemSize().height();
2398 if (itemHeight
> 0) {
2399 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2400 newItemSize
.height(),
2401 newItemMargin
.height());
2402 if (m_model
->count() > newRowCount
) {
2403 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2405 m_layouter
->itemMargin().height());
2406 return oldRowCount
!= newRowCount
;
2414 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2416 if (m_itemSize
.isEmpty()) {
2417 // We have only columns or only rows, but no grid: An animation is usually
2418 // welcome when inserting or removing items.
2419 return !supportsItemExpanding();
2422 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2426 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2427 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2428 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2429 // Only animate if up to 2/3 of a row or column are inserted or removed
2430 return changedItemCount
<= maximum
* 2 / 3;
2434 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2436 const QSizeF oldSize
= m_layouter
->size();
2438 m_layouter
->setSize(size
);
2439 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2440 m_layouter
->setSize(oldSize
);
2442 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2443 : maxOffset
> size
.width();
2446 int KItemListView::showDropIndicator(const QPointF
& pos
)
2448 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2449 while (it
.hasNext()) {
2451 const KItemListWidget
* widget
= it
.value();
2453 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2454 const QRectF rect
= itemRect(widget
->index());
2455 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2456 if (m_model
->supportsDropping(widget
->index())) {
2457 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2458 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2459 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2464 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2465 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2467 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2468 if (m_dropIndicator
!= draggingInsertIndicator
) {
2469 m_dropIndicator
= draggingInsertIndicator
;
2473 int index
= widget
->index();
2481 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2482 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2485 void KItemListView::hideDropIndicator()
2487 if (!m_dropIndicator
.isNull()) {
2488 m_dropIndicator
= QRectF();
2493 void KItemListView::updateGroupHeaderHeight()
2495 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2496 qreal groupHeaderMargin
= 0;
2498 if (scrollOrientation() == Qt::Horizontal
) {
2499 // The vertical margin above and below the header should be
2500 // equal to the horizontal margin, not the vertical margin
2501 // from m_styleOption.
2502 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2503 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2504 } else if (m_itemSize
.isEmpty()){
2505 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2506 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2508 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2509 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2511 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2512 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2514 updateVisibleGroupHeaders();
2517 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2519 if (!supportsItemExpanding() || !m_model
) {
2523 if (firstIndex
< 0 || lastIndex
< 0) {
2524 firstIndex
= m_layouter
->firstVisibleIndex();
2525 lastIndex
= m_layouter
->lastVisibleIndex();
2527 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2528 lastIndex
>= m_layouter
->firstVisibleIndex());
2529 if (!isRangeVisible
) {
2534 int previousParents
= 0;
2535 QBitArray previousSiblings
;
2537 // The rootIndex describes the first index where the siblings get
2538 // calculated from. For the calculation the upper most parent item
2539 // is required. For performance reasons it is checked first whether
2540 // the visible items before or after the current range already
2541 // contain a siblings information which can be used as base.
2542 int rootIndex
= firstIndex
;
2544 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2546 // There is no visible widget before the range, check whether there
2547 // is one after the range:
2548 widget
= m_visibleItems
.value(lastIndex
+ 1);
2550 // The sibling information of the widget may only be used if
2551 // all items of the range have the same number of parents.
2552 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2553 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2554 if (m_model
->expandedParentsCount(i
) != parents
) {
2563 // Performance optimization: Use the sibling information of the visible
2564 // widget beside the given range.
2565 previousSiblings
= widget
->siblingsInformation();
2566 if (previousSiblings
.isEmpty()) {
2569 previousParents
= previousSiblings
.count() - 1;
2570 previousSiblings
.truncate(previousParents
);
2572 // Potentially slow path: Go back to the upper most parent of firstIndex
2573 // to be able to calculate the initial value for the siblings.
2574 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2579 Q_ASSERT(previousParents
>= 0);
2580 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2581 // Update the parent-siblings in case if the current item represents
2582 // a child or an upper parent.
2583 const int currentParents
= m_model
->expandedParentsCount(i
);
2584 Q_ASSERT(currentParents
>= 0);
2585 if (previousParents
< currentParents
) {
2586 previousParents
= currentParents
;
2587 previousSiblings
.resize(currentParents
);
2588 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2589 } else if (previousParents
> currentParents
) {
2590 previousParents
= currentParents
;
2591 previousSiblings
.truncate(currentParents
);
2594 if (i
>= firstIndex
) {
2595 // The index represents a visible item. Apply the parent-siblings
2596 // and update the sibling of the current item.
2597 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2602 QBitArray siblings
= previousSiblings
;
2603 siblings
.resize(siblings
.count() + 1);
2604 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2606 widget
->setSiblingsInformation(siblings
);
2611 bool KItemListView::hasSiblingSuccessor(int index
) const
2613 bool hasSuccessor
= false;
2614 const int parentsCount
= m_model
->expandedParentsCount(index
);
2615 int successorIndex
= index
+ 1;
2617 // Search the next sibling
2618 const int itemCount
= m_model
->count();
2619 while (successorIndex
< itemCount
) {
2620 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2621 if (currentParentsCount
== parentsCount
) {
2622 hasSuccessor
= true;
2624 } else if (currentParentsCount
< parentsCount
) {
2630 if (m_grouped
&& hasSuccessor
) {
2631 // If the sibling is part of another group, don't mark it as
2632 // successor as the group header is between the sibling connections.
2633 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2634 if (m_layouter
->isFirstGroupItem(i
)) {
2635 hasSuccessor
= false;
2641 return hasSuccessor
;
2644 void KItemListView::disconnectRoleEditingSignals(int index
)
2646 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2651 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2652 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2655 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2659 const int minSpeed
= 4;
2660 const int maxSpeed
= 128;
2661 const int speedLimiter
= 96;
2662 const int autoScrollBorder
= 64;
2664 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2665 // This assures that the autoscrolling speed grows gradually.
2666 const int incLimiter
= 1;
2668 if (pos
< autoScrollBorder
) {
2669 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2670 inc
= qMax(inc
, -maxSpeed
);
2671 inc
= qMax(inc
, oldInc
- incLimiter
);
2672 } else if (pos
> range
- autoScrollBorder
) {
2673 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2674 inc
= qMin(inc
, maxSpeed
);
2675 inc
= qMin(inc
, oldInc
+ incLimiter
);
2681 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2683 const qreal availableSize
= size
- itemMargin
;
2684 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2690 KItemListCreatorBase::~KItemListCreatorBase()
2692 qDeleteAll(m_recycleableWidgets
);
2693 qDeleteAll(m_createdWidgets
);
2696 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2698 m_createdWidgets
.insert(widget
);
2701 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2703 Q_ASSERT(m_createdWidgets
.contains(widget
));
2704 m_createdWidgets
.remove(widget
);
2706 if (m_recycleableWidgets
.count() < 100) {
2707 m_recycleableWidgets
.append(widget
);
2708 widget
->setVisible(false);
2714 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2716 if (m_recycleableWidgets
.isEmpty()) {
2720 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2721 m_createdWidgets
.insert(widget
);
2725 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2729 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2731 widget
->setParentItem(0);
2732 widget
->setOpacity(1.0);
2733 pushRecycleableWidget(widget
);
2736 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2740 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2742 header
->setOpacity(1.0);
2743 pushRecycleableWidget(header
);