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 delete m_widgetCreator
;
313 m_widgetCreator
= widgetCreator
;
316 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
318 if (!m_widgetCreator
) {
319 m_widgetCreator
= defaultWidgetCreator();
321 return m_widgetCreator
;
324 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
326 delete m_groupHeaderCreator
;
327 m_groupHeaderCreator
= groupHeaderCreator
;
330 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
332 if (!m_groupHeaderCreator
) {
333 m_groupHeaderCreator
= defaultGroupHeaderCreator();
335 return m_groupHeaderCreator
;
338 QSizeF
KItemListView::itemSize() const
343 QSizeF
KItemListView::itemSizeHint() const
345 return m_sizeHintResolver
->maxSizeHint();
348 const KItemListStyleOption
& KItemListView::styleOption() const
350 return m_styleOption
;
353 void KItemListView::setGeometry(const QRectF
& rect
)
355 QGraphicsWidget::setGeometry(rect
);
361 const QSizeF newSize
= rect
.size();
362 if (m_itemSize
.isEmpty()) {
363 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
364 if (m_headerWidget
->automaticColumnResizing()) {
365 applyAutomaticColumnWidths();
367 const qreal requiredWidth
= columnWidthsSum();
368 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
369 m_itemSize
.height());
370 m_layouter
->setItemSize(dynamicItemSize
);
373 // Triggering a synchronous layout is fine from a performance point of view,
374 // as with dynamic item sizes no moving animation must be done.
375 m_layouter
->setSize(newSize
);
376 doLayout(NoAnimation
);
378 const bool animate
= !changesItemGridLayout(newSize
,
379 m_layouter
->itemSize(),
380 m_layouter
->itemMargin());
381 m_layouter
->setSize(newSize
);
384 // Trigger an asynchronous relayout with m_layoutTimer to prevent
385 // performance bottlenecks. If the timer is exceeded, an animated layout
386 // will be triggered.
387 if (!m_layoutTimer
->isActive()) {
388 m_layoutTimer
->start();
391 m_layoutTimer
->stop();
392 doLayout(NoAnimation
);
397 qreal
KItemListView::verticalPageStep() const
399 qreal headerHeight
= 0;
400 if (m_headerWidget
->isVisible()) {
401 headerHeight
= m_headerWidget
->size().height();
403 return size().height() - headerHeight
;
406 int KItemListView::itemAt(const QPointF
& pos
) const
408 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
409 while (it
.hasNext()) {
412 const KItemListWidget
* widget
= it
.value();
413 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
414 if (widget
->contains(mappedPos
)) {
422 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
424 if (!m_enabledSelectionToggles
) {
428 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
430 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
431 if (!selectionToggleRect
.isEmpty()) {
432 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
433 return selectionToggleRect
.contains(mappedPos
);
439 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
441 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
443 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
444 if (!expansionToggleRect
.isEmpty()) {
445 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
446 return expansionToggleRect
.contains(mappedPos
);
452 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
454 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
456 const QRectF
&textRect
= widget
->textRect();
457 if (!textRect
.isEmpty()) {
458 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
459 return textRect
.contains(mappedPos
);
465 int KItemListView::firstVisibleIndex() const
467 return m_layouter
->firstVisibleIndex();
470 int KItemListView::lastVisibleIndex() const
472 return m_layouter
->lastVisibleIndex();
475 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
477 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
480 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
482 if (m_supportsItemExpanding
!= supportsExpanding
) {
483 m_supportsItemExpanding
= supportsExpanding
;
484 updateSiblingsInformation();
485 onSupportsItemExpandingChanged(supportsExpanding
);
489 bool KItemListView::supportsItemExpanding() const
491 return m_supportsItemExpanding
;
494 QRectF
KItemListView::itemRect(int index
) const
496 return m_layouter
->itemRect(index
);
499 QRectF
KItemListView::itemContextRect(int index
) const
503 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
505 contextRect
= widget
->iconRect() | widget
->textRect();
506 contextRect
.translate(itemRect(index
).topLeft());
512 void KItemListView::scrollToItem(int index
)
514 QRectF viewGeometry
= geometry();
515 if (m_headerWidget
->isVisible()) {
516 const qreal headerHeight
= m_headerWidget
->size().height();
517 viewGeometry
.adjust(0, headerHeight
, 0, 0);
519 QRectF currentRect
= itemRect(index
);
521 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
522 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
523 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
525 if (!viewGeometry
.contains(currentRect
)) {
526 qreal newOffset
= scrollOffset();
527 if (scrollOrientation() == Qt::Vertical
) {
528 if (currentRect
.top() < viewGeometry
.top()) {
529 newOffset
+= currentRect
.top() - viewGeometry
.top();
530 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
531 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
534 if (currentRect
.left() < viewGeometry
.left()) {
535 newOffset
+= currentRect
.left() - viewGeometry
.left();
536 } else if (currentRect
.right() > viewGeometry
.right()) {
537 newOffset
+= currentRect
.right() - viewGeometry
.right();
541 if (newOffset
!= scrollOffset()) {
542 emit
scrollTo(newOffset
);
547 void KItemListView::beginTransaction()
549 ++m_activeTransactions
;
550 if (m_activeTransactions
== 1) {
551 onTransactionBegin();
555 void KItemListView::endTransaction()
557 --m_activeTransactions
;
558 if (m_activeTransactions
< 0) {
559 m_activeTransactions
= 0;
560 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
563 if (m_activeTransactions
== 0) {
565 doLayout(m_endTransactionAnimationHint
);
566 m_endTransactionAnimationHint
= Animation
;
570 bool KItemListView::isTransactionActive() const
572 return m_activeTransactions
> 0;
575 void KItemListView::setHeaderVisible(bool visible
)
577 if (visible
&& !m_headerWidget
->isVisible()) {
578 QStyleOptionHeader option
;
579 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
582 m_headerWidget
->setPos(0, 0);
583 m_headerWidget
->resize(size().width(), headerSize
.height());
584 m_headerWidget
->setModel(m_model
);
585 m_headerWidget
->setColumns(m_visibleRoles
);
586 m_headerWidget
->setZValue(1);
588 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
589 this, &KItemListView::slotHeaderColumnWidthChanged
);
590 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
591 this, &KItemListView::slotHeaderColumnMoved
);
592 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
593 this, &KItemListView::sortOrderChanged
);
594 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
595 this, &KItemListView::sortRoleChanged
);
597 m_layouter
->setHeaderHeight(headerSize
.height());
598 m_headerWidget
->setVisible(true);
599 } else if (!visible
&& m_headerWidget
->isVisible()) {
600 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
601 this, &KItemListView::slotHeaderColumnWidthChanged
);
602 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
603 this, &KItemListView::slotHeaderColumnMoved
);
604 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
605 this, &KItemListView::sortOrderChanged
);
606 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
607 this, &KItemListView::sortRoleChanged
);
609 m_layouter
->setHeaderHeight(0);
610 m_headerWidget
->setVisible(false);
614 bool KItemListView::isHeaderVisible() const
616 return m_headerWidget
->isVisible();
619 KItemListHeader
* KItemListView::header() const
624 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
628 if (indexes
.count() == 1) {
629 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
630 QGraphicsView
* graphicsView
= scene()->views()[0];
631 if (item
&& graphicsView
) {
632 pixmap
= item
->createDragPixmap(0, graphicsView
);
635 // TODO: Not implemented yet. Probably extend the interface
636 // from KItemListWidget::createDragPixmap() to return a pixmap
637 // that can be used for multiple indexes.
643 void KItemListView::editRole(int index
, const QByteArray
& role
)
645 KItemListWidget
* widget
= m_visibleItems
.value(index
);
646 if (!widget
|| m_editingRole
) {
650 m_editingRole
= true;
651 widget
->setEditedRole(role
);
653 connect(widget
, &KItemListWidget::roleEditingCanceled
,
654 this, &KItemListView::slotRoleEditingCanceled
);
655 connect(widget
, &KItemListWidget::roleEditingFinished
,
656 this, &KItemListView::slotRoleEditingFinished
);
659 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
661 QGraphicsWidget::paint(painter
, option
, widget
);
663 if (m_rubberBand
->isActive()) {
664 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
665 m_rubberBand
->endPosition()).normalized();
667 const QPointF topLeft
= rubberBandRect
.topLeft();
668 if (scrollOrientation() == Qt::Vertical
) {
669 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
671 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
674 QStyleOptionRubberBand opt
;
675 opt
.initFrom(widget
);
676 opt
.shape
= QRubberBand::Rectangle
;
678 opt
.rect
= rubberBandRect
.toRect();
679 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
682 if (!m_dropIndicator
.isEmpty()) {
683 const QRectF r
= m_dropIndicator
.toRect();
685 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
686 painter
->setPen(color
);
688 // TODO: The following implementation works only for a vertical scroll-orientation
689 // and assumes a height of the m_draggingInsertIndicator of 1.
690 Q_ASSERT(r
.height() == 1);
691 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
694 painter
->setPen(color
);
695 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
699 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
701 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
702 if (!scene()->views().isEmpty()) {
703 m_styleOption
.palette
= scene()->views().at(0)->palette();
706 return QGraphicsItem::itemChange(change
, value
);
709 void KItemListView::setItemSize(const QSizeF
& size
)
711 const QSizeF previousSize
= m_itemSize
;
712 if (size
== previousSize
) {
716 // Skip animations when the number of rows or columns
717 // are changed in the grid layout. Although the animation
718 // engine can handle this usecase, it looks obtrusive.
719 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
721 m_layouter
->itemMargin());
723 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
724 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
725 (!m_itemSize
.isEmpty() && size
.isEmpty()));
729 if (alternateBackgroundsChanged
) {
730 // For an empty item size alternate backgrounds are drawn if more than
731 // one role is shown. Assure that the backgrounds for visible items are
732 // updated when changing the size in this context.
733 updateAlternateBackgrounds();
736 if (size
.isEmpty()) {
737 if (m_headerWidget
->automaticColumnResizing()) {
738 updatePreferredColumnWidths();
740 // Only apply the changed height and respect the header widths
742 const qreal currentWidth
= m_layouter
->itemSize().width();
743 const QSizeF
newSize(currentWidth
, size
.height());
744 m_layouter
->setItemSize(newSize
);
747 m_layouter
->setItemSize(size
);
750 m_sizeHintResolver
->clearCache();
751 doLayout(animate
? Animation
: NoAnimation
);
752 onItemSizeChanged(size
, previousSize
);
755 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
757 const KItemListStyleOption previousOption
= m_styleOption
;
758 m_styleOption
= option
;
761 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
762 if (margin
!= m_layouter
->itemMargin()) {
763 // Skip animations when the number of rows or columns
764 // are changed in the grid layout. Although the animation
765 // engine can handle this usecase, it looks obtrusive.
766 animate
= !changesItemGridLayout(m_layouter
->size(),
767 m_layouter
->itemSize(),
769 m_layouter
->setItemMargin(margin
);
773 updateGroupHeaderHeight();
777 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
778 // Animating a change of the maximum text size just results in expensive
779 // temporary eliding and clipping operations and does not look good visually.
783 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
784 while (it
.hasNext()) {
786 it
.value()->setStyleOption(option
);
789 m_sizeHintResolver
->clearCache();
790 m_layouter
->markAsDirty();
791 doLayout(animate
? Animation
: NoAnimation
);
793 if (m_itemSize
.isEmpty()) {
794 updatePreferredColumnWidths();
797 onStyleOptionChanged(option
, previousOption
);
800 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
802 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
803 if (orientation
== previousOrientation
) {
807 m_layouter
->setScrollOrientation(orientation
);
808 m_animation
->setScrollOrientation(orientation
);
809 m_sizeHintResolver
->clearCache();
812 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
813 while (it
.hasNext()) {
815 it
.value()->setScrollOrientation(orientation
);
817 updateGroupHeaderHeight();
821 doLayout(NoAnimation
);
823 onScrollOrientationChanged(orientation
, previousOrientation
);
824 emit
scrollOrientationChanged(orientation
, previousOrientation
);
827 Qt::Orientation
KItemListView::scrollOrientation() const
829 return m_layouter
->scrollOrientation();
832 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
837 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
842 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
847 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
849 Q_UNUSED(changedRoles
);
853 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
859 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
865 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
871 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
877 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
883 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
889 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
895 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
897 Q_UNUSED(supportsExpanding
);
900 void KItemListView::onTransactionBegin()
904 void KItemListView::onTransactionEnd()
908 bool KItemListView::event(QEvent
* event
)
910 switch (event
->type()) {
911 case QEvent::PaletteChange
:
915 case QEvent::FontChange
:
920 // Forward all other events to the controller and handle them there
921 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
927 return QGraphicsWidget::event(event
);
930 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
932 m_mousePos
= transform().map(event
->pos());
936 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
938 QGraphicsWidget::mouseMoveEvent(event
);
940 m_mousePos
= transform().map(event
->pos());
941 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
942 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
946 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
948 event
->setAccepted(true);
952 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
954 QGraphicsWidget::dragMoveEvent(event
);
956 m_mousePos
= transform().map(event
->pos());
957 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
958 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
962 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
964 QGraphicsWidget::dragLeaveEvent(event
);
965 setAutoScroll(false);
968 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
970 QGraphicsWidget::dropEvent(event
);
971 setAutoScroll(false);
974 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
976 return m_visibleItems
.values();
979 void KItemListView::updateFont()
981 if (scene() && !scene()->views().isEmpty()) {
982 KItemListStyleOption option
= styleOption();
983 option
.font
= scene()->views().first()->font();
984 option
.fontMetrics
= QFontMetrics(option
.font
);
986 setStyleOption(option
);
990 void KItemListView::updatePalette()
992 if (scene() && !scene()->views().isEmpty()) {
993 KItemListStyleOption option
= styleOption();
994 option
.palette
= scene()->views().first()->palette();
996 setStyleOption(option
);
1000 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1002 if (m_itemSize
.isEmpty()) {
1003 updatePreferredColumnWidths(itemRanges
);
1006 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1007 if (hasMultipleRanges
) {
1011 m_layouter
->markAsDirty();
1013 m_sizeHintResolver
->itemsInserted(itemRanges
);
1015 int previouslyInsertedCount
= 0;
1016 foreach (const KItemRange
& range
, itemRanges
) {
1017 // range.index is related to the model before anything has been inserted.
1018 // As in each loop the current item-range gets inserted the index must
1019 // be increased by the already previously inserted items.
1020 const int index
= range
.index
+ previouslyInsertedCount
;
1021 const int count
= range
.count
;
1022 if (index
< 0 || count
<= 0) {
1023 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1026 previouslyInsertedCount
+= count
;
1028 // Determine which visible items must be moved
1029 QList
<int> itemsToMove
;
1030 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1031 while (it
.hasNext()) {
1033 const int visibleItemIndex
= it
.key();
1034 if (visibleItemIndex
>= index
) {
1035 itemsToMove
.append(visibleItemIndex
);
1039 // Update the indexes of all KItemListWidget instances that are located
1040 // after the inserted items. It is important to adjust the indexes in the order
1041 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1043 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1044 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1046 const int newIndex
= widget
->index() + count
;
1047 if (hasMultipleRanges
) {
1048 setWidgetIndex(widget
, newIndex
);
1050 // Try to animate the moving of the item
1051 moveWidgetToIndex(widget
, newIndex
);
1055 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1056 // Check whether a scrollbar is required to show the inserted items. In this case
1057 // the size of the layouter will be decreased before calling doLayout(): This prevents
1058 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1059 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1060 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1061 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1062 if (decreaseLayouterSize
) {
1063 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1065 int scrollbarSpacing
= 0;
1066 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1067 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1070 QSizeF layouterSize
= m_layouter
->size();
1071 if (verticalScrollOrientation
) {
1072 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1074 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1076 m_layouter
->setSize(layouterSize
);
1080 if (!hasMultipleRanges
) {
1081 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1082 updateSiblingsInformation();
1087 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1090 if (hasMultipleRanges
) {
1091 m_endTransactionAnimationHint
= NoAnimation
;
1094 updateSiblingsInformation();
1097 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1098 // In case if items of the same group have been inserted before an item that
1099 // currently represents the first item of the group, the group header of
1100 // this item must be removed.
1101 updateVisibleGroupHeaders();
1104 if (useAlternateBackgrounds()) {
1105 updateAlternateBackgrounds();
1109 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1111 if (m_itemSize
.isEmpty()) {
1112 // Don't pass the item-range: The preferred column-widths of
1113 // all items must be adjusted when removing items.
1114 updatePreferredColumnWidths();
1117 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1118 if (hasMultipleRanges
) {
1122 m_layouter
->markAsDirty();
1124 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1126 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1127 const KItemRange
& range
= itemRanges
[i
];
1128 const int index
= range
.index
;
1129 const int count
= range
.count
;
1130 if (index
< 0 || count
<= 0) {
1131 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1135 const int firstRemovedIndex
= index
;
1136 const int lastRemovedIndex
= index
+ count
- 1;
1138 // Remember which items have to be moved because they are behind the removed range.
1139 QVector
<int> itemsToMove
;
1141 // Remove all KItemListWidget instances that got deleted
1142 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1143 const int i
= widget
->index();
1144 if (i
< firstRemovedIndex
) {
1146 } else if (i
> lastRemovedIndex
) {
1147 itemsToMove
.append(i
);
1151 m_animation
->stop(widget
);
1152 // Stopping the animation might lead to recycling the widget if
1153 // it is invisible (see slotAnimationFinished()).
1154 // Check again whether it is still visible:
1155 if (!m_visibleItems
.contains(i
)) {
1159 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1160 // Remove the widget without animation
1161 recycleWidget(widget
);
1163 // Animate the removing of the items. Special case: When removing an item there
1164 // is no valid model index available anymore. For the
1165 // remove-animation the item gets removed from m_visibleItems but the widget
1166 // will stay alive until the animation has been finished and will
1167 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1168 m_visibleItems
.remove(i
);
1169 widget
->setIndex(-1);
1170 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1174 // Update the indexes of all KItemListWidget instances that are located
1175 // after the deleted items. It is important to update them in ascending
1176 // order to prevent overlaps when setting the new index.
1177 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1178 foreach (int i
, itemsToMove
) {
1179 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1181 const int newIndex
= i
- count
;
1182 if (hasMultipleRanges
) {
1183 setWidgetIndex(widget
, newIndex
);
1185 // Try to animate the moving of the item
1186 moveWidgetToIndex(widget
, newIndex
);
1190 if (!hasMultipleRanges
) {
1191 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1192 // assumes an updated geometry. If items are removed during an active transaction,
1193 // the transaction will be temporary deactivated so that doLayout() triggers a
1194 // geometry update if necessary.
1195 const int activeTransactions
= m_activeTransactions
;
1196 m_activeTransactions
= 0;
1197 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1198 m_activeTransactions
= activeTransactions
;
1199 updateSiblingsInformation();
1204 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1207 if (hasMultipleRanges
) {
1208 m_endTransactionAnimationHint
= NoAnimation
;
1210 updateSiblingsInformation();
1213 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1214 // In case if the first item of a group has been removed, the group header
1215 // must be applied to the next visible item.
1216 updateVisibleGroupHeaders();
1219 if (useAlternateBackgrounds()) {
1220 updateAlternateBackgrounds();
1224 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1226 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1227 m_layouter
->markAsDirty();
1230 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1233 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1234 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1236 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1237 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1239 updateWidgetProperties(widget
, index
);
1240 initializeItemListWidget(widget
);
1244 doLayout(NoAnimation
);
1245 updateSiblingsInformation();
1248 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1249 const QSet
<QByteArray
>& roles
)
1251 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1252 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1253 updatePreferredColumnWidths(itemRanges
);
1256 foreach (const KItemRange
& itemRange
, itemRanges
) {
1257 const int index
= itemRange
.index
;
1258 const int count
= itemRange
.count
;
1260 if (updateSizeHints
) {
1261 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1262 m_layouter
->markAsDirty();
1264 if (!m_layoutTimer
->isActive()) {
1265 m_layoutTimer
->start();
1269 // Apply the changed roles to the visible item-widgets
1270 const int lastIndex
= index
+ count
- 1;
1271 for (int i
= index
; i
<= lastIndex
; ++i
) {
1272 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1274 widget
->setData(m_model
->data(i
), roles
);
1278 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1279 // The sort-role has been changed which might result
1280 // in modified group headers
1281 updateVisibleGroupHeaders();
1282 doLayout(NoAnimation
);
1285 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1286 ev
.setFirstRow(itemRange
.index
);
1287 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1288 QAccessible::updateAccessibility(&ev
);
1292 void KItemListView::slotGroupsChanged()
1294 updateVisibleGroupHeaders();
1295 doLayout(NoAnimation
);
1296 updateSiblingsInformation();
1299 void KItemListView::slotGroupedSortingChanged(bool current
)
1301 m_grouped
= current
;
1302 m_layouter
->markAsDirty();
1305 updateGroupHeaderHeight();
1307 // Clear all visible headers. Note that the QHashIterator takes a copy of
1308 // m_visibleGroups. Therefore, it remains valid even if items are removed
1309 // from m_visibleGroups in recycleGroupHeaderForWidget().
1310 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1311 while (it
.hasNext()) {
1313 recycleGroupHeaderForWidget(it
.key());
1315 Q_ASSERT(m_visibleGroups
.isEmpty());
1318 if (useAlternateBackgrounds()) {
1319 // Changing the group mode requires to update the alternate backgrounds
1320 // as with the enabled group mode the altering is done on base of the first
1322 updateAlternateBackgrounds();
1324 updateSiblingsInformation();
1325 doLayout(NoAnimation
);
1328 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1333 updateVisibleGroupHeaders();
1334 doLayout(NoAnimation
);
1338 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1343 updateVisibleGroupHeaders();
1344 doLayout(NoAnimation
);
1348 void KItemListView::slotCurrentChanged(int current
, int previous
)
1352 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1353 // always the selected item. It is not necessary to highlight the current item then.
1354 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1355 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1356 if (previousWidget
) {
1357 previousWidget
->setCurrent(false);
1360 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1361 if (currentWidget
) {
1362 currentWidget
->setCurrent(true);
1366 QAccessibleEvent
ev(this, QAccessible::Focus
);
1367 ev
.setChild(current
);
1368 QAccessible::updateAccessibility(&ev
);
1371 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1375 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1376 while (it
.hasNext()) {
1378 const int index
= it
.key();
1379 KItemListWidget
* widget
= it
.value();
1380 widget
->setSelected(current
.contains(index
));
1384 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1385 KItemListViewAnimation::AnimationType type
)
1387 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1388 Q_ASSERT(itemListWidget
);
1391 case KItemListViewAnimation::DeleteAnimation
: {
1392 // As we recycle the widget in this case it is important to assure that no
1393 // other animation has been started. This is a convention in KItemListView and
1394 // not a requirement defined by KItemListViewAnimation.
1395 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1397 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1398 // by m_visibleWidgets and must be deleted manually after the animation has
1400 recycleGroupHeaderForWidget(itemListWidget
);
1401 widgetCreator()->recycle(itemListWidget
);
1405 case KItemListViewAnimation::CreateAnimation
:
1406 case KItemListViewAnimation::MovingAnimation
:
1407 case KItemListViewAnimation::ResizeAnimation
: {
1408 const int index
= itemListWidget
->index();
1409 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1410 (index
> m_layouter
->lastVisibleIndex());
1411 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1412 recycleWidget(itemListWidget
);
1421 void KItemListView::slotLayoutTimerFinished()
1423 m_layouter
->setSize(geometry().size());
1424 doLayout(Animation
);
1427 void KItemListView::slotRubberBandPosChanged()
1432 void KItemListView::slotRubberBandActivationChanged(bool active
)
1435 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1436 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1437 m_skipAutoScrollForRubberBand
= true;
1439 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1440 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1441 m_skipAutoScrollForRubberBand
= false;
1447 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1449 qreal previousWidth
)
1452 Q_UNUSED(currentWidth
);
1453 Q_UNUSED(previousWidth
);
1455 m_headerWidget
->setAutomaticColumnResizing(false);
1456 applyColumnWidthsFromHeader();
1457 doLayout(NoAnimation
);
1460 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1464 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1466 const QList
<QByteArray
> previous
= m_visibleRoles
;
1468 QList
<QByteArray
> current
= m_visibleRoles
;
1469 current
.removeAt(previousIndex
);
1470 current
.insert(currentIndex
, role
);
1472 setVisibleRoles(current
);
1474 emit
visibleRolesChanged(current
, previous
);
1477 void KItemListView::triggerAutoScrolling()
1479 if (!m_autoScrollTimer
) {
1484 int visibleSize
= 0;
1485 if (scrollOrientation() == Qt::Vertical
) {
1486 pos
= m_mousePos
.y();
1487 visibleSize
= size().height();
1489 pos
= m_mousePos
.x();
1490 visibleSize
= size().width();
1493 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1494 m_autoScrollIncrement
= 0;
1497 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1498 if (m_autoScrollIncrement
== 0) {
1499 // The mouse position is not above an autoscroll margin (the autoscroll timer
1500 // will be restarted in mouseMoveEvent())
1501 m_autoScrollTimer
->stop();
1505 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1506 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1507 // if the direction of the rubberband is similar to the autoscroll direction. This
1508 // prevents that starting to create a rubberband within the autoscroll margins starts
1509 // an autoscrolling.
1511 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1512 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1513 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1514 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1515 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1516 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1517 // been moved up although the autoscroll direction might be down)
1518 m_autoScrollTimer
->stop();
1523 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1524 // the autoscrolling may not get skipped anymore until a new rubberband is created
1525 m_skipAutoScrollForRubberBand
= false;
1527 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1528 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1529 setScrollOffset(newScrollOffset
);
1531 // Trigger the autoscroll timer which will periodically call
1532 // triggerAutoScrolling()
1533 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1536 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1538 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1540 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1541 Q_ASSERT(groupHeader
);
1542 updateGroupHeaderLayout(widget
);
1545 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1547 disconnectRoleEditingSignals(index
);
1549 emit
roleEditingCanceled(index
, role
, value
);
1550 m_editingRole
= false;
1553 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1555 disconnectRoleEditingSignals(index
);
1557 emit
roleEditingFinished(index
, role
, value
);
1558 m_editingRole
= false;
1561 void KItemListView::setController(KItemListController
* controller
)
1563 if (m_controller
!= controller
) {
1564 KItemListController
* previous
= m_controller
;
1566 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1567 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1568 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1571 m_controller
= controller
;
1574 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1575 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1576 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1579 onControllerChanged(controller
, previous
);
1583 void KItemListView::setModel(KItemModelBase
* model
)
1585 if (m_model
== model
) {
1589 KItemModelBase
* previous
= m_model
;
1592 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1593 this, &KItemListView::slotItemsChanged
);
1594 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1595 this, &KItemListView::slotItemsInserted
);
1596 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1597 this, &KItemListView::slotItemsRemoved
);
1598 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1599 this, &KItemListView::slotItemsMoved
);
1600 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1601 this, &KItemListView::slotGroupsChanged
);
1602 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1603 this, &KItemListView::slotGroupedSortingChanged
);
1604 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1605 this, &KItemListView::slotSortOrderChanged
);
1606 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1607 this, &KItemListView::slotSortRoleChanged
);
1609 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1613 m_layouter
->setModel(model
);
1614 m_grouped
= model
->groupedSorting();
1617 connect(m_model
, &KItemModelBase::itemsChanged
,
1618 this, &KItemListView::slotItemsChanged
);
1619 connect(m_model
, &KItemModelBase::itemsInserted
,
1620 this, &KItemListView::slotItemsInserted
);
1621 connect(m_model
, &KItemModelBase::itemsRemoved
,
1622 this, &KItemListView::slotItemsRemoved
);
1623 connect(m_model
, &KItemModelBase::itemsMoved
,
1624 this, &KItemListView::slotItemsMoved
);
1625 connect(m_model
, &KItemModelBase::groupsChanged
,
1626 this, &KItemListView::slotGroupsChanged
);
1627 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1628 this, &KItemListView::slotGroupedSortingChanged
);
1629 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1630 this, &KItemListView::slotSortOrderChanged
);
1631 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1632 this, &KItemListView::slotSortRoleChanged
);
1634 const int itemCount
= m_model
->count();
1635 if (itemCount
> 0) {
1636 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1640 onModelChanged(model
, previous
);
1643 KItemListRubberBand
* KItemListView::rubberBand() const
1645 return m_rubberBand
;
1648 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1650 if (m_layoutTimer
->isActive()) {
1651 m_layoutTimer
->stop();
1654 if (m_activeTransactions
> 0) {
1655 if (hint
== NoAnimation
) {
1656 // As soon as at least one property change should be done without animation,
1657 // the whole transaction will be marked as not animated.
1658 m_endTransactionAnimationHint
= NoAnimation
;
1663 if (!m_model
|| m_model
->count() < 0) {
1667 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1668 if (firstVisibleIndex
< 0) {
1669 emitOffsetChanges();
1673 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1674 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1675 // is still shown if the maximum offset got decreased.
1676 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1677 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1678 if (scrollOffset() > maxOffsetToShowFullRange
) {
1679 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1680 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1683 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1685 int firstSibblingIndex
= -1;
1686 int lastSibblingIndex
= -1;
1687 const bool supportsExpanding
= supportsItemExpanding();
1689 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1691 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1692 // instances from invisible items are reused. If no reusable items are
1693 // found then new KItemListWidget instances get created.
1694 const bool animate
= (hint
== Animation
);
1695 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1696 bool applyNewPos
= true;
1697 bool wasHidden
= false;
1699 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1700 const QPointF newPos
= itemBounds
.topLeft();
1701 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1704 if (!reusableItems
.isEmpty()) {
1705 // Reuse a KItemListWidget instance from an invisible item
1706 const int oldIndex
= reusableItems
.takeLast();
1707 widget
= m_visibleItems
.value(oldIndex
);
1708 setWidgetIndex(widget
, i
);
1709 updateWidgetProperties(widget
, i
);
1710 initializeItemListWidget(widget
);
1712 // No reusable KItemListWidget instance is available, create a new one
1713 widget
= createWidget(i
);
1715 widget
->resize(itemBounds
.size());
1717 if (animate
&& changedCount
< 0) {
1718 // Items have been deleted.
1719 if (i
>= changedIndex
) {
1720 // The item is located behind the removed range. Move the
1721 // created item to the imaginary old position outside the
1722 // view. It will get animated to the new position later.
1723 const int previousIndex
= i
- changedCount
;
1724 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1725 if (itemRect
.isEmpty()) {
1726 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1727 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1728 widget
->setPos(invisibleOldPos
);
1730 widget
->setPos(itemRect
.topLeft());
1732 applyNewPos
= false;
1736 if (supportsExpanding
&& changedCount
== 0) {
1737 if (firstSibblingIndex
< 0) {
1738 firstSibblingIndex
= i
;
1740 lastSibblingIndex
= i
;
1745 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1746 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1747 applyNewPos
= false;
1750 const bool itemsRemoved
= (changedCount
< 0);
1751 const bool itemsInserted
= (changedCount
> 0);
1752 if (itemsRemoved
&& (i
>= changedIndex
)) {
1753 // The item is located after the removed items. Animate the moving of the position.
1754 applyNewPos
= !moveWidget(widget
, newPos
);
1755 } else if (itemsInserted
&& i
>= changedIndex
) {
1756 // The item is located after the first inserted item
1757 if (i
<= changedIndex
+ changedCount
- 1) {
1758 // The item is an inserted item. Animate the appearing of the item.
1759 // For performance reasons no animation is done when changedCount is equal
1760 // to all available items.
1761 if (changedCount
< m_model
->count()) {
1762 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1764 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1765 // The item was already there before, so animate the moving of the position.
1766 // No moving animation is done if the item is animated by a create animation: This
1767 // prevents a "move animation mess" when inserting several ranges in parallel.
1768 applyNewPos
= !moveWidget(widget
, newPos
);
1770 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1771 // The size of the view might have been changed. Animate the moving of the position.
1772 applyNewPos
= !moveWidget(widget
, newPos
);
1775 m_animation
->stop(widget
);
1779 widget
->setPos(newPos
);
1782 Q_ASSERT(widget
->index() == i
);
1783 widget
->setVisible(true);
1785 if (widget
->size() != itemBounds
.size()) {
1786 // Resize the widget for the item to the changed size.
1788 // If a dynamic item size is used then no animation is done in the direction
1789 // of the dynamic size.
1790 if (m_itemSize
.width() <= 0) {
1791 // The width is dynamic, apply the new width without animation.
1792 widget
->resize(itemBounds
.width(), widget
->size().height());
1793 } else if (m_itemSize
.height() <= 0) {
1794 // The height is dynamic, apply the new height without animation.
1795 widget
->resize(widget
->size().width(), itemBounds
.height());
1797 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1799 widget
->resize(itemBounds
.size());
1803 // Updating the cell-information must be done as last step: The decision whether the
1804 // moving-animation should be started at all is based on the previous cell-information.
1805 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1806 m_visibleCells
.insert(i
, cell
);
1809 // Delete invisible KItemListWidget instances that have not been reused
1810 foreach (int index
, reusableItems
) {
1811 recycleWidget(m_visibleItems
.value(index
));
1814 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1815 Q_ASSERT(lastSibblingIndex
>= 0);
1816 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1820 // Update the layout of all visible group headers
1821 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1822 while (it
.hasNext()) {
1824 updateGroupHeaderLayout(it
.key());
1828 emitOffsetChanges();
1831 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1832 int lastVisibleIndex
,
1833 LayoutAnimationHint hint
)
1835 // Determine all items that are completely invisible and might be
1836 // reused for items that just got (at least partly) visible. If the
1837 // animation hint is set to 'Animation' items that do e.g. an animated
1838 // moving of their position are not marked as invisible: This assures
1839 // that a scrolling inside the view can be done without breaking an animation.
1843 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1844 while (it
.hasNext()) {
1847 KItemListWidget
* widget
= it
.value();
1848 const int index
= widget
->index();
1849 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1852 if (m_animation
->isStarted(widget
)) {
1853 if (hint
== NoAnimation
) {
1854 // Stopping the animation will call KItemListView::slotAnimationFinished()
1855 // and the widget will be recycled if necessary there.
1856 m_animation
->stop(widget
);
1859 widget
->setVisible(false);
1860 items
.append(index
);
1863 recycleGroupHeaderForWidget(widget
);
1872 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1874 if (widget
->pos() == newPos
) {
1878 bool startMovingAnim
= false;
1880 if (m_itemSize
.isEmpty()) {
1881 // The items are not aligned in a grid but either as columns or rows.
1882 startMovingAnim
= true;
1884 // When having a grid the moving-animation should only be started, if it is done within
1885 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1886 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1887 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1888 const int index
= widget
->index();
1889 const Cell cell
= m_visibleCells
.value(index
);
1890 if (cell
.column
>= 0 && cell
.row
>= 0) {
1891 if (scrollOrientation() == Qt::Vertical
) {
1892 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1894 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1899 if (startMovingAnim
) {
1900 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1904 m_animation
->stop(widget
);
1905 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1909 void KItemListView::emitOffsetChanges()
1911 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1912 if (m_oldScrollOffset
!= newScrollOffset
) {
1913 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1914 m_oldScrollOffset
= newScrollOffset
;
1917 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1918 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1919 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1920 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1923 const qreal newItemOffset
= m_layouter
->itemOffset();
1924 if (m_oldItemOffset
!= newItemOffset
) {
1925 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1926 m_oldItemOffset
= newItemOffset
;
1929 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1930 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1931 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1932 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1936 KItemListWidget
* KItemListView::createWidget(int index
)
1938 KItemListWidget
* widget
= widgetCreator()->create(this);
1939 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1941 m_visibleItems
.insert(index
, widget
);
1942 m_visibleCells
.insert(index
, Cell());
1943 updateWidgetProperties(widget
, index
);
1944 initializeItemListWidget(widget
);
1948 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1951 recycleGroupHeaderForWidget(widget
);
1954 const int index
= widget
->index();
1955 m_visibleItems
.remove(index
);
1956 m_visibleCells
.remove(index
);
1958 widgetCreator()->recycle(widget
);
1961 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1963 const int oldIndex
= widget
->index();
1964 m_visibleItems
.remove(oldIndex
);
1965 m_visibleCells
.remove(oldIndex
);
1967 m_visibleItems
.insert(index
, widget
);
1968 m_visibleCells
.insert(index
, Cell());
1970 widget
->setIndex(index
);
1973 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1975 const int oldIndex
= widget
->index();
1976 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1978 setWidgetIndex(widget
, index
);
1980 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1981 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1982 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1983 (!vertical
&& oldCell
.column
== newCell
.column
);
1985 m_visibleCells
.insert(index
, newCell
);
1989 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1992 case LayouterSize
: m_layouter
->setSize(size
); break;
1993 case ItemSize
: m_layouter
->setItemSize(size
); break;
1998 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2000 widget
->setVisibleRoles(m_visibleRoles
);
2001 updateWidgetColumnWidths(widget
);
2002 widget
->setStyleOption(m_styleOption
);
2004 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2006 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2007 // always the selected item. It is not necessary to highlight the current item then.
2008 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2009 widget
->setCurrent(index
== selectionManager
->currentItem());
2011 widget
->setSelected(selectionManager
->isSelected(index
));
2012 widget
->setHovered(false);
2013 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2014 widget
->setIndex(index
);
2015 widget
->setData(m_model
->data(index
));
2016 widget
->setSiblingsInformation(QBitArray());
2017 updateAlternateBackgroundForWidget(widget
);
2020 updateGroupHeaderForWidget(widget
);
2024 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2026 Q_ASSERT(m_grouped
);
2028 const int index
= widget
->index();
2029 if (!m_layouter
->isFirstGroupItem(index
)) {
2030 // The widget does not represent the first item of a group
2031 // and hence requires no header
2032 recycleGroupHeaderForWidget(widget
);
2036 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2037 if (groups
.isEmpty() || !groupHeaderCreator()) {
2041 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2043 groupHeader
= groupHeaderCreator()->create(this);
2044 groupHeader
->setParentItem(widget
);
2045 m_visibleGroups
.insert(widget
, groupHeader
);
2046 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2048 Q_ASSERT(groupHeader
->parentItem() == widget
);
2050 const int groupIndex
= groupIndexForItem(index
);
2051 Q_ASSERT(groupIndex
>= 0);
2052 groupHeader
->setData(groups
.at(groupIndex
).second
);
2053 groupHeader
->setRole(model()->sortRole());
2054 groupHeader
->setStyleOption(m_styleOption
);
2055 groupHeader
->setScrollOrientation(scrollOrientation());
2056 groupHeader
->setItemIndex(index
);
2058 groupHeader
->show();
2061 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2063 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2064 Q_ASSERT(groupHeader
);
2066 const int index
= widget
->index();
2067 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2068 const QRectF itemRect
= m_layouter
->itemRect(index
);
2070 // The group-header is a child of the itemlist widget. Translate the
2071 // group header position to the relative position.
2072 if (scrollOrientation() == Qt::Vertical
) {
2073 // In the vertical scroll orientation the group header should always span
2074 // the whole width no matter which temporary position the parent widget
2075 // has. In this case the x-position and width will be adjusted manually.
2076 const qreal x
= -widget
->x() - itemOffset();
2077 const qreal width
= maximumItemOffset();
2078 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2079 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2081 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2082 groupHeader
->resize(groupHeaderRect
.size());
2086 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2088 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2090 header
->setParentItem(0);
2091 groupHeaderCreator()->recycle(header
);
2092 m_visibleGroups
.remove(widget
);
2093 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2097 void KItemListView::updateVisibleGroupHeaders()
2099 Q_ASSERT(m_grouped
);
2100 m_layouter
->markAsDirty();
2102 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2103 while (it
.hasNext()) {
2105 updateGroupHeaderForWidget(it
.value());
2109 int KItemListView::groupIndexForItem(int index
) const
2111 Q_ASSERT(m_grouped
);
2113 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2114 if (groups
.isEmpty()) {
2119 int max
= groups
.count() - 1;
2122 mid
= (min
+ max
) / 2;
2123 if (index
> groups
[mid
].first
) {
2128 } while (groups
[mid
].first
!= index
&& min
<= max
);
2131 while (groups
[mid
].first
> index
&& mid
> 0) {
2139 void KItemListView::updateAlternateBackgrounds()
2141 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2142 while (it
.hasNext()) {
2144 updateAlternateBackgroundForWidget(it
.value());
2148 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2150 bool enabled
= useAlternateBackgrounds();
2152 const int index
= widget
->index();
2153 enabled
= (index
& 0x1) > 0;
2155 const int groupIndex
= groupIndexForItem(index
);
2156 if (groupIndex
>= 0) {
2157 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2158 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2159 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2160 enabled
= (relativeIndex
& 0x1) > 0;
2164 widget
->setAlternateBackground(enabled
);
2167 bool KItemListView::useAlternateBackgrounds() const
2169 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2172 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2174 QElapsedTimer timer
;
2177 QHash
<QByteArray
, qreal
> widths
;
2179 // Calculate the minimum width for each column that is required
2180 // to show the headline unclipped.
2181 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2182 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2183 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2184 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2185 const QString headerText
= m_model
->roleDescription(visibleRole
);
2186 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2187 widths
.insert(visibleRole
, headerWidth
);
2190 // Calculate the preferred column withs for each item and ignore values
2191 // smaller than the width for showing the headline unclipped.
2192 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2193 int calculatedItemCount
= 0;
2194 bool maxTimeExceeded
= false;
2195 foreach (const KItemRange
& itemRange
, itemRanges
) {
2196 const int startIndex
= itemRange
.index
;
2197 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2199 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2200 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2201 qreal maxWidth
= widths
.value(visibleRole
, 0);
2202 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2203 maxWidth
= qMax(width
, maxWidth
);
2204 widths
.insert(visibleRole
, maxWidth
);
2207 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2208 // When having several thousands of items calculating the sizes can get
2209 // very expensive. We accept a possibly too small role-size in favour
2210 // of having no blocking user interface.
2211 maxTimeExceeded
= true;
2214 ++calculatedItemCount
;
2216 if (maxTimeExceeded
) {
2224 void KItemListView::applyColumnWidthsFromHeader()
2226 // Apply the new size to the layouter
2227 const qreal requiredWidth
= columnWidthsSum();
2228 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2229 m_itemSize
.height());
2230 m_layouter
->setItemSize(dynamicItemSize
);
2232 // Update the role sizes for all visible widgets
2233 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2234 while (it
.hasNext()) {
2236 updateWidgetColumnWidths(it
.value());
2240 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2242 foreach (const QByteArray
& role
, m_visibleRoles
) {
2243 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2247 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2249 Q_ASSERT(m_itemSize
.isEmpty());
2250 const int itemCount
= m_model
->count();
2251 int rangesItemCount
= 0;
2252 foreach (const KItemRange
& range
, itemRanges
) {
2253 rangesItemCount
+= range
.count
;
2256 if (itemCount
== rangesItemCount
) {
2257 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2258 foreach (const QByteArray
& role
, m_visibleRoles
) {
2259 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2262 // Only a sub range of the roles need to be determined.
2263 // The chances are good that the widths of the sub ranges
2264 // already fit into the available widths and hence no
2265 // expensive update might be required.
2266 bool changed
= false;
2268 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2269 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2270 while (it
.hasNext()) {
2272 const QByteArray
& role
= it
.key();
2273 const qreal updatedWidth
= it
.value();
2274 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2275 if (updatedWidth
> currentWidth
) {
2276 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2282 // All the updated sizes are smaller than the current sizes and no change
2283 // of the stretched roles-widths is required
2288 if (m_headerWidget
->automaticColumnResizing()) {
2289 applyAutomaticColumnWidths();
2293 void KItemListView::updatePreferredColumnWidths()
2296 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2300 void KItemListView::applyAutomaticColumnWidths()
2302 Q_ASSERT(m_itemSize
.isEmpty());
2303 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2304 if (m_visibleRoles
.isEmpty()) {
2308 // Calculate the maximum size of an item by considering the
2309 // visible role sizes and apply them to the layouter. If the
2310 // size does not use the available view-size the size of the
2311 // first role will get stretched.
2313 foreach (const QByteArray
& role
, m_visibleRoles
) {
2314 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2315 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2318 const QByteArray firstRole
= m_visibleRoles
.first();
2319 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2320 QSizeF dynamicItemSize
= m_itemSize
;
2322 qreal requiredWidth
= columnWidthsSum();
2323 const qreal availableWidth
= size().width();
2324 if (requiredWidth
< availableWidth
) {
2325 // Stretch the first column to use the whole remaining width
2326 firstColumnWidth
+= availableWidth
- requiredWidth
;
2327 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2328 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2329 // Shrink the first column to be able to show as much other
2330 // columns as possible
2331 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2333 // TODO: A proper calculation of the minimum width depends on the implementation
2334 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2336 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2337 if (shrinkedFirstColumnWidth
< minWidth
) {
2338 shrinkedFirstColumnWidth
= minWidth
;
2341 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2342 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2345 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2347 m_layouter
->setItemSize(dynamicItemSize
);
2349 // Update the role sizes for all visible widgets
2350 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2351 while (it
.hasNext()) {
2353 updateWidgetColumnWidths(it
.value());
2357 qreal
KItemListView::columnWidthsSum() const
2359 qreal widthsSum
= 0;
2360 foreach (const QByteArray
& role
, m_visibleRoles
) {
2361 widthsSum
+= m_headerWidget
->columnWidth(role
);
2366 QRectF
KItemListView::headerBoundaries() const
2368 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2371 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2372 const QSizeF
& newItemSize
,
2373 const QSizeF
& newItemMargin
) const
2375 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2379 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2380 const qreal itemWidth
= m_layouter
->itemSize().width();
2381 if (itemWidth
> 0) {
2382 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2383 newItemSize
.width(),
2384 newItemMargin
.width());
2385 if (m_model
->count() > newColumnCount
) {
2386 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2388 m_layouter
->itemMargin().width());
2389 return oldColumnCount
!= newColumnCount
;
2393 const qreal itemHeight
= m_layouter
->itemSize().height();
2394 if (itemHeight
> 0) {
2395 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2396 newItemSize
.height(),
2397 newItemMargin
.height());
2398 if (m_model
->count() > newRowCount
) {
2399 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2401 m_layouter
->itemMargin().height());
2402 return oldRowCount
!= newRowCount
;
2410 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2412 if (m_itemSize
.isEmpty()) {
2413 // We have only columns or only rows, but no grid: An animation is usually
2414 // welcome when inserting or removing items.
2415 return !supportsItemExpanding();
2418 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2422 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2423 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2424 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2425 // Only animate if up to 2/3 of a row or column are inserted or removed
2426 return changedItemCount
<= maximum
* 2 / 3;
2430 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2432 const QSizeF oldSize
= m_layouter
->size();
2434 m_layouter
->setSize(size
);
2435 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2436 m_layouter
->setSize(oldSize
);
2438 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2439 : maxOffset
> size
.width();
2442 int KItemListView::showDropIndicator(const QPointF
& pos
)
2444 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2445 while (it
.hasNext()) {
2447 const KItemListWidget
* widget
= it
.value();
2449 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2450 const QRectF rect
= itemRect(widget
->index());
2451 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2452 if (m_model
->supportsDropping(widget
->index())) {
2453 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2454 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2455 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2460 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2461 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2463 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2464 if (m_dropIndicator
!= draggingInsertIndicator
) {
2465 m_dropIndicator
= draggingInsertIndicator
;
2469 int index
= widget
->index();
2477 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2478 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2481 void KItemListView::hideDropIndicator()
2483 if (!m_dropIndicator
.isNull()) {
2484 m_dropIndicator
= QRectF();
2489 void KItemListView::updateGroupHeaderHeight()
2491 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2492 qreal groupHeaderMargin
= 0;
2494 if (scrollOrientation() == Qt::Horizontal
) {
2495 // The vertical margin above and below the header should be
2496 // equal to the horizontal margin, not the vertical margin
2497 // from m_styleOption.
2498 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2499 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2500 } else if (m_itemSize
.isEmpty()){
2501 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2502 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2504 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2505 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2507 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2508 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2510 updateVisibleGroupHeaders();
2513 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2515 if (!supportsItemExpanding() || !m_model
) {
2519 if (firstIndex
< 0 || lastIndex
< 0) {
2520 firstIndex
= m_layouter
->firstVisibleIndex();
2521 lastIndex
= m_layouter
->lastVisibleIndex();
2523 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2524 lastIndex
>= m_layouter
->firstVisibleIndex());
2525 if (!isRangeVisible
) {
2530 int previousParents
= 0;
2531 QBitArray previousSiblings
;
2533 // The rootIndex describes the first index where the siblings get
2534 // calculated from. For the calculation the upper most parent item
2535 // is required. For performance reasons it is checked first whether
2536 // the visible items before or after the current range already
2537 // contain a siblings information which can be used as base.
2538 int rootIndex
= firstIndex
;
2540 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2542 // There is no visible widget before the range, check whether there
2543 // is one after the range:
2544 widget
= m_visibleItems
.value(lastIndex
+ 1);
2546 // The sibling information of the widget may only be used if
2547 // all items of the range have the same number of parents.
2548 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2549 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2550 if (m_model
->expandedParentsCount(i
) != parents
) {
2559 // Performance optimization: Use the sibling information of the visible
2560 // widget beside the given range.
2561 previousSiblings
= widget
->siblingsInformation();
2562 if (previousSiblings
.isEmpty()) {
2565 previousParents
= previousSiblings
.count() - 1;
2566 previousSiblings
.truncate(previousParents
);
2568 // Potentially slow path: Go back to the upper most parent of firstIndex
2569 // to be able to calculate the initial value for the siblings.
2570 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2575 Q_ASSERT(previousParents
>= 0);
2576 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2577 // Update the parent-siblings in case if the current item represents
2578 // a child or an upper parent.
2579 const int currentParents
= m_model
->expandedParentsCount(i
);
2580 Q_ASSERT(currentParents
>= 0);
2581 if (previousParents
< currentParents
) {
2582 previousParents
= currentParents
;
2583 previousSiblings
.resize(currentParents
);
2584 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2585 } else if (previousParents
> currentParents
) {
2586 previousParents
= currentParents
;
2587 previousSiblings
.truncate(currentParents
);
2590 if (i
>= firstIndex
) {
2591 // The index represents a visible item. Apply the parent-siblings
2592 // and update the sibling of the current item.
2593 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2598 QBitArray siblings
= previousSiblings
;
2599 siblings
.resize(siblings
.count() + 1);
2600 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2602 widget
->setSiblingsInformation(siblings
);
2607 bool KItemListView::hasSiblingSuccessor(int index
) const
2609 bool hasSuccessor
= false;
2610 const int parentsCount
= m_model
->expandedParentsCount(index
);
2611 int successorIndex
= index
+ 1;
2613 // Search the next sibling
2614 const int itemCount
= m_model
->count();
2615 while (successorIndex
< itemCount
) {
2616 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2617 if (currentParentsCount
== parentsCount
) {
2618 hasSuccessor
= true;
2620 } else if (currentParentsCount
< parentsCount
) {
2626 if (m_grouped
&& hasSuccessor
) {
2627 // If the sibling is part of another group, don't mark it as
2628 // successor as the group header is between the sibling connections.
2629 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2630 if (m_layouter
->isFirstGroupItem(i
)) {
2631 hasSuccessor
= false;
2637 return hasSuccessor
;
2640 void KItemListView::disconnectRoleEditingSignals(int index
)
2642 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2647 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2648 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2651 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2655 const int minSpeed
= 4;
2656 const int maxSpeed
= 128;
2657 const int speedLimiter
= 96;
2658 const int autoScrollBorder
= 64;
2660 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2661 // This assures that the autoscrolling speed grows gradually.
2662 const int incLimiter
= 1;
2664 if (pos
< autoScrollBorder
) {
2665 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2666 inc
= qMax(inc
, -maxSpeed
);
2667 inc
= qMax(inc
, oldInc
- incLimiter
);
2668 } else if (pos
> range
- autoScrollBorder
) {
2669 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2670 inc
= qMin(inc
, maxSpeed
);
2671 inc
= qMin(inc
, oldInc
+ incLimiter
);
2677 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2679 const qreal availableSize
= size
- itemMargin
;
2680 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2686 KItemListCreatorBase::~KItemListCreatorBase()
2688 qDeleteAll(m_recycleableWidgets
);
2689 qDeleteAll(m_createdWidgets
);
2692 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2694 m_createdWidgets
.insert(widget
);
2697 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2699 Q_ASSERT(m_createdWidgets
.contains(widget
));
2700 m_createdWidgets
.remove(widget
);
2702 if (m_recycleableWidgets
.count() < 100) {
2703 m_recycleableWidgets
.append(widget
);
2704 widget
->setVisible(false);
2710 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2712 if (m_recycleableWidgets
.isEmpty()) {
2716 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2717 m_createdWidgets
.insert(widget
);
2721 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2725 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2727 widget
->setParentItem(0);
2728 widget
->setOpacity(1.0);
2729 pushRecycleableWidget(widget
);
2732 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2736 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2738 header
->setOpacity(1.0);
2739 pushRecycleableWidget(header
);