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 const KItemListStyleOption
& KItemListView::styleOption() const
349 return m_styleOption
;
352 void KItemListView::setGeometry(const QRectF
& rect
)
354 QGraphicsWidget::setGeometry(rect
);
360 const QSizeF newSize
= rect
.size();
361 if (m_itemSize
.isEmpty()) {
362 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
363 if (m_headerWidget
->automaticColumnResizing()) {
364 applyAutomaticColumnWidths();
366 const qreal requiredWidth
= columnWidthsSum();
367 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
368 m_itemSize
.height());
369 m_layouter
->setItemSize(dynamicItemSize
);
372 // Triggering a synchronous layout is fine from a performance point of view,
373 // as with dynamic item sizes no moving animation must be done.
374 m_layouter
->setSize(newSize
);
375 doLayout(NoAnimation
);
377 const bool animate
= !changesItemGridLayout(newSize
,
378 m_layouter
->itemSize(),
379 m_layouter
->itemMargin());
380 m_layouter
->setSize(newSize
);
383 // Trigger an asynchronous relayout with m_layoutTimer to prevent
384 // performance bottlenecks. If the timer is exceeded, an animated layout
385 // will be triggered.
386 if (!m_layoutTimer
->isActive()) {
387 m_layoutTimer
->start();
390 m_layoutTimer
->stop();
391 doLayout(NoAnimation
);
396 qreal
KItemListView::verticalPageStep() const
398 qreal headerHeight
= 0;
399 if (m_headerWidget
->isVisible()) {
400 headerHeight
= m_headerWidget
->size().height();
402 return size().height() - headerHeight
;
405 int KItemListView::itemAt(const QPointF
& pos
) const
407 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
408 while (it
.hasNext()) {
411 const KItemListWidget
* widget
= it
.value();
412 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
413 if (widget
->contains(mappedPos
)) {
421 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
423 if (!m_enabledSelectionToggles
) {
427 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
429 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
430 if (!selectionToggleRect
.isEmpty()) {
431 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
432 return selectionToggleRect
.contains(mappedPos
);
438 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
440 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
442 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
443 if (!expansionToggleRect
.isEmpty()) {
444 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
445 return expansionToggleRect
.contains(mappedPos
);
451 int KItemListView::firstVisibleIndex() const
453 return m_layouter
->firstVisibleIndex();
456 int KItemListView::lastVisibleIndex() const
458 return m_layouter
->lastVisibleIndex();
461 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
463 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
466 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
468 if (m_supportsItemExpanding
!= supportsExpanding
) {
469 m_supportsItemExpanding
= supportsExpanding
;
470 updateSiblingsInformation();
471 onSupportsItemExpandingChanged(supportsExpanding
);
475 bool KItemListView::supportsItemExpanding() const
477 return m_supportsItemExpanding
;
480 QRectF
KItemListView::itemRect(int index
) const
482 return m_layouter
->itemRect(index
);
485 QRectF
KItemListView::itemContextRect(int index
) const
489 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
491 contextRect
= widget
->iconRect() | widget
->textRect();
492 contextRect
.translate(itemRect(index
).topLeft());
498 void KItemListView::scrollToItem(int index
)
500 QRectF viewGeometry
= geometry();
501 if (m_headerWidget
->isVisible()) {
502 const qreal headerHeight
= m_headerWidget
->size().height();
503 viewGeometry
.adjust(0, headerHeight
, 0, 0);
505 QRectF currentRect
= itemRect(index
);
507 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
508 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
509 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
511 if (!viewGeometry
.contains(currentRect
)) {
512 qreal newOffset
= scrollOffset();
513 if (scrollOrientation() == Qt::Vertical
) {
514 if (currentRect
.top() < viewGeometry
.top()) {
515 newOffset
+= currentRect
.top() - viewGeometry
.top();
516 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
517 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
520 if (currentRect
.left() < viewGeometry
.left()) {
521 newOffset
+= currentRect
.left() - viewGeometry
.left();
522 } else if (currentRect
.right() > viewGeometry
.right()) {
523 newOffset
+= currentRect
.right() - viewGeometry
.right();
527 if (newOffset
!= scrollOffset()) {
528 emit
scrollTo(newOffset
);
533 void KItemListView::beginTransaction()
535 ++m_activeTransactions
;
536 if (m_activeTransactions
== 1) {
537 onTransactionBegin();
541 void KItemListView::endTransaction()
543 --m_activeTransactions
;
544 if (m_activeTransactions
< 0) {
545 m_activeTransactions
= 0;
546 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
549 if (m_activeTransactions
== 0) {
551 doLayout(m_endTransactionAnimationHint
);
552 m_endTransactionAnimationHint
= Animation
;
556 bool KItemListView::isTransactionActive() const
558 return m_activeTransactions
> 0;
561 void KItemListView::setHeaderVisible(bool visible
)
563 if (visible
&& !m_headerWidget
->isVisible()) {
564 QStyleOptionHeader option
;
565 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
568 m_headerWidget
->setPos(0, 0);
569 m_headerWidget
->resize(size().width(), headerSize
.height());
570 m_headerWidget
->setModel(m_model
);
571 m_headerWidget
->setColumns(m_visibleRoles
);
572 m_headerWidget
->setZValue(1);
574 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
575 this, &KItemListView::slotHeaderColumnWidthChanged
);
576 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
577 this, &KItemListView::slotHeaderColumnMoved
);
578 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
579 this, &KItemListView::sortOrderChanged
);
580 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
581 this, &KItemListView::sortRoleChanged
);
583 m_layouter
->setHeaderHeight(headerSize
.height());
584 m_headerWidget
->setVisible(true);
585 } else if (!visible
&& m_headerWidget
->isVisible()) {
586 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
587 this, &KItemListView::slotHeaderColumnWidthChanged
);
588 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
589 this, &KItemListView::slotHeaderColumnMoved
);
590 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
591 this, &KItemListView::sortOrderChanged
);
592 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
593 this, &KItemListView::sortRoleChanged
);
595 m_layouter
->setHeaderHeight(0);
596 m_headerWidget
->setVisible(false);
600 bool KItemListView::isHeaderVisible() const
602 return m_headerWidget
->isVisible();
605 KItemListHeader
* KItemListView::header() const
610 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
614 if (indexes
.count() == 1) {
615 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
616 QGraphicsView
* graphicsView
= scene()->views()[0];
617 if (item
&& graphicsView
) {
618 pixmap
= item
->createDragPixmap(0, graphicsView
);
621 // TODO: Not implemented yet. Probably extend the interface
622 // from KItemListWidget::createDragPixmap() to return a pixmap
623 // that can be used for multiple indexes.
629 void KItemListView::editRole(int index
, const QByteArray
& role
)
631 KItemListWidget
* widget
= m_visibleItems
.value(index
);
632 if (!widget
|| m_editingRole
) {
636 m_editingRole
= true;
637 widget
->setEditedRole(role
);
639 connect(widget
, &KItemListWidget::roleEditingCanceled
,
640 this, &KItemListView::slotRoleEditingCanceled
);
641 connect(widget
, &KItemListWidget::roleEditingFinished
,
642 this, &KItemListView::slotRoleEditingFinished
);
645 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
647 QGraphicsWidget::paint(painter
, option
, widget
);
649 if (m_rubberBand
->isActive()) {
650 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
651 m_rubberBand
->endPosition()).normalized();
653 const QPointF topLeft
= rubberBandRect
.topLeft();
654 if (scrollOrientation() == Qt::Vertical
) {
655 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
657 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
660 QStyleOptionRubberBand opt
;
661 opt
.initFrom(widget
);
662 opt
.shape
= QRubberBand::Rectangle
;
664 opt
.rect
= rubberBandRect
.toRect();
665 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
668 if (!m_dropIndicator
.isEmpty()) {
669 const QRectF r
= m_dropIndicator
.toRect();
671 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
672 painter
->setPen(color
);
674 // TODO: The following implementation works only for a vertical scroll-orientation
675 // and assumes a height of the m_draggingInsertIndicator of 1.
676 Q_ASSERT(r
.height() == 1);
677 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
680 painter
->setPen(color
);
681 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
685 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
687 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
688 if (!scene()->views().isEmpty()) {
689 m_styleOption
.palette
= scene()->views().at(0)->palette();
692 return QGraphicsItem::itemChange(change
, value
);
695 void KItemListView::setItemSize(const QSizeF
& size
)
697 const QSizeF previousSize
= m_itemSize
;
698 if (size
== previousSize
) {
702 // Skip animations when the number of rows or columns
703 // are changed in the grid layout. Although the animation
704 // engine can handle this usecase, it looks obtrusive.
705 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
707 m_layouter
->itemMargin());
709 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
710 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
711 (!m_itemSize
.isEmpty() && size
.isEmpty()));
715 if (alternateBackgroundsChanged
) {
716 // For an empty item size alternate backgrounds are drawn if more than
717 // one role is shown. Assure that the backgrounds for visible items are
718 // updated when changing the size in this context.
719 updateAlternateBackgrounds();
722 if (size
.isEmpty()) {
723 if (m_headerWidget
->automaticColumnResizing()) {
724 updatePreferredColumnWidths();
726 // Only apply the changed height and respect the header widths
728 const qreal currentWidth
= m_layouter
->itemSize().width();
729 const QSizeF
newSize(currentWidth
, size
.height());
730 m_layouter
->setItemSize(newSize
);
733 m_layouter
->setItemSize(size
);
736 m_sizeHintResolver
->clearCache();
737 doLayout(animate
? Animation
: NoAnimation
);
738 onItemSizeChanged(size
, previousSize
);
741 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
743 const KItemListStyleOption previousOption
= m_styleOption
;
744 m_styleOption
= option
;
747 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
748 if (margin
!= m_layouter
->itemMargin()) {
749 // Skip animations when the number of rows or columns
750 // are changed in the grid layout. Although the animation
751 // engine can handle this usecase, it looks obtrusive.
752 animate
= !changesItemGridLayout(m_layouter
->size(),
753 m_layouter
->itemSize(),
755 m_layouter
->setItemMargin(margin
);
759 updateGroupHeaderHeight();
763 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
764 // Animating a change of the maximum text size just results in expensive
765 // temporary eliding and clipping operations and does not look good visually.
769 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
770 while (it
.hasNext()) {
772 it
.value()->setStyleOption(option
);
775 m_sizeHintResolver
->clearCache();
776 m_layouter
->markAsDirty();
777 doLayout(animate
? Animation
: NoAnimation
);
779 if (m_itemSize
.isEmpty()) {
780 updatePreferredColumnWidths();
783 onStyleOptionChanged(option
, previousOption
);
786 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
788 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
789 if (orientation
== previousOrientation
) {
793 m_layouter
->setScrollOrientation(orientation
);
794 m_animation
->setScrollOrientation(orientation
);
795 m_sizeHintResolver
->clearCache();
798 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
799 while (it
.hasNext()) {
801 it
.value()->setScrollOrientation(orientation
);
803 updateGroupHeaderHeight();
807 doLayout(NoAnimation
);
809 onScrollOrientationChanged(orientation
, previousOrientation
);
810 emit
scrollOrientationChanged(orientation
, previousOrientation
);
813 Qt::Orientation
KItemListView::scrollOrientation() const
815 return m_layouter
->scrollOrientation();
818 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
823 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
828 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
833 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
835 Q_UNUSED(changedRoles
);
839 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
845 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
851 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
857 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
863 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
869 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
875 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
881 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
883 Q_UNUSED(supportsExpanding
);
886 void KItemListView::onTransactionBegin()
890 void KItemListView::onTransactionEnd()
894 bool KItemListView::event(QEvent
* event
)
896 switch (event
->type()) {
897 case QEvent::PaletteChange
:
901 case QEvent::FontChange
:
906 // Forward all other events to the controller and handle them there
907 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
913 return QGraphicsWidget::event(event
);
916 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
918 m_mousePos
= transform().map(event
->pos());
922 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
924 QGraphicsWidget::mouseMoveEvent(event
);
926 m_mousePos
= transform().map(event
->pos());
927 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
928 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
932 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
934 event
->setAccepted(true);
938 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
940 QGraphicsWidget::dragMoveEvent(event
);
942 m_mousePos
= transform().map(event
->pos());
943 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
944 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
948 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
950 QGraphicsWidget::dragLeaveEvent(event
);
951 setAutoScroll(false);
954 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
956 QGraphicsWidget::dropEvent(event
);
957 setAutoScroll(false);
960 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
962 return m_visibleItems
.values();
965 void KItemListView::updateFont()
967 if (scene() && !scene()->views().isEmpty()) {
968 KItemListStyleOption option
= styleOption();
969 option
.font
= scene()->views().first()->font();
970 option
.fontMetrics
= QFontMetrics(option
.font
);
972 setStyleOption(option
);
976 void KItemListView::updatePalette()
978 if (scene() && !scene()->views().isEmpty()) {
979 KItemListStyleOption option
= styleOption();
980 option
.palette
= scene()->views().first()->palette();
982 setStyleOption(option
);
986 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
988 if (m_itemSize
.isEmpty()) {
989 updatePreferredColumnWidths(itemRanges
);
992 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
993 if (hasMultipleRanges
) {
997 m_layouter
->markAsDirty();
999 m_sizeHintResolver
->itemsInserted(itemRanges
);
1001 int previouslyInsertedCount
= 0;
1002 foreach (const KItemRange
& range
, itemRanges
) {
1003 // range.index is related to the model before anything has been inserted.
1004 // As in each loop the current item-range gets inserted the index must
1005 // be increased by the already previously inserted items.
1006 const int index
= range
.index
+ previouslyInsertedCount
;
1007 const int count
= range
.count
;
1008 if (index
< 0 || count
<= 0) {
1009 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1012 previouslyInsertedCount
+= count
;
1014 // Determine which visible items must be moved
1015 QList
<int> itemsToMove
;
1016 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1017 while (it
.hasNext()) {
1019 const int visibleItemIndex
= it
.key();
1020 if (visibleItemIndex
>= index
) {
1021 itemsToMove
.append(visibleItemIndex
);
1025 // Update the indexes of all KItemListWidget instances that are located
1026 // after the inserted items. It is important to adjust the indexes in the order
1027 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1029 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1030 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1032 const int newIndex
= widget
->index() + count
;
1033 if (hasMultipleRanges
) {
1034 setWidgetIndex(widget
, newIndex
);
1036 // Try to animate the moving of the item
1037 moveWidgetToIndex(widget
, newIndex
);
1041 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1042 // Check whether a scrollbar is required to show the inserted items. In this case
1043 // the size of the layouter will be decreased before calling doLayout(): This prevents
1044 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1045 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1046 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1047 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1048 if (decreaseLayouterSize
) {
1049 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1051 int scrollbarSpacing
= 0;
1052 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1053 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1056 QSizeF layouterSize
= m_layouter
->size();
1057 if (verticalScrollOrientation
) {
1058 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1060 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1062 m_layouter
->setSize(layouterSize
);
1066 if (!hasMultipleRanges
) {
1067 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1068 updateSiblingsInformation();
1073 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1076 if (hasMultipleRanges
) {
1077 m_endTransactionAnimationHint
= NoAnimation
;
1080 updateSiblingsInformation();
1083 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1084 // In case if items of the same group have been inserted before an item that
1085 // currently represents the first item of the group, the group header of
1086 // this item must be removed.
1087 updateVisibleGroupHeaders();
1090 if (useAlternateBackgrounds()) {
1091 updateAlternateBackgrounds();
1095 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1097 if (m_itemSize
.isEmpty()) {
1098 // Don't pass the item-range: The preferred column-widths of
1099 // all items must be adjusted when removing items.
1100 updatePreferredColumnWidths();
1103 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1104 if (hasMultipleRanges
) {
1108 m_layouter
->markAsDirty();
1110 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1112 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1113 const KItemRange
& range
= itemRanges
[i
];
1114 const int index
= range
.index
;
1115 const int count
= range
.count
;
1116 if (index
< 0 || count
<= 0) {
1117 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1121 const int firstRemovedIndex
= index
;
1122 const int lastRemovedIndex
= index
+ count
- 1;
1124 // Remember which items have to be moved because they are behind the removed range.
1125 QVector
<int> itemsToMove
;
1127 // Remove all KItemListWidget instances that got deleted
1128 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1129 const int i
= widget
->index();
1130 if (i
< firstRemovedIndex
) {
1132 } else if (i
> lastRemovedIndex
) {
1133 itemsToMove
.append(i
);
1137 m_animation
->stop(widget
);
1138 // Stopping the animation might lead to recycling the widget if
1139 // it is invisible (see slotAnimationFinished()).
1140 // Check again whether it is still visible:
1141 if (!m_visibleItems
.contains(i
)) {
1145 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1146 // Remove the widget without animation
1147 recycleWidget(widget
);
1149 // Animate the removing of the items. Special case: When removing an item there
1150 // is no valid model index available anymore. For the
1151 // remove-animation the item gets removed from m_visibleItems but the widget
1152 // will stay alive until the animation has been finished and will
1153 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1154 m_visibleItems
.remove(i
);
1155 widget
->setIndex(-1);
1156 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1160 // Update the indexes of all KItemListWidget instances that are located
1161 // after the deleted items. It is important to update them in ascending
1162 // order to prevent overlaps when setting the new index.
1163 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1164 foreach (int i
, itemsToMove
) {
1165 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1167 const int newIndex
= i
- count
;
1168 if (hasMultipleRanges
) {
1169 setWidgetIndex(widget
, newIndex
);
1171 // Try to animate the moving of the item
1172 moveWidgetToIndex(widget
, newIndex
);
1176 if (!hasMultipleRanges
) {
1177 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1178 // assumes an updated geometry. If items are removed during an active transaction,
1179 // the transaction will be temporary deactivated so that doLayout() triggers a
1180 // geometry update if necessary.
1181 const int activeTransactions
= m_activeTransactions
;
1182 m_activeTransactions
= 0;
1183 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1184 m_activeTransactions
= activeTransactions
;
1185 updateSiblingsInformation();
1190 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1193 if (hasMultipleRanges
) {
1194 m_endTransactionAnimationHint
= NoAnimation
;
1196 updateSiblingsInformation();
1199 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1200 // In case if the first item of a group has been removed, the group header
1201 // must be applied to the next visible item.
1202 updateVisibleGroupHeaders();
1205 if (useAlternateBackgrounds()) {
1206 updateAlternateBackgrounds();
1210 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1212 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1213 m_layouter
->markAsDirty();
1216 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1219 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1220 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1222 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1223 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1225 updateWidgetProperties(widget
, index
);
1226 initializeItemListWidget(widget
);
1230 doLayout(NoAnimation
);
1231 updateSiblingsInformation();
1234 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1235 const QSet
<QByteArray
>& roles
)
1237 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1238 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1239 updatePreferredColumnWidths(itemRanges
);
1242 foreach (const KItemRange
& itemRange
, itemRanges
) {
1243 const int index
= itemRange
.index
;
1244 const int count
= itemRange
.count
;
1246 if (updateSizeHints
) {
1247 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1248 m_layouter
->markAsDirty();
1250 if (!m_layoutTimer
->isActive()) {
1251 m_layoutTimer
->start();
1255 // Apply the changed roles to the visible item-widgets
1256 const int lastIndex
= index
+ count
- 1;
1257 for (int i
= index
; i
<= lastIndex
; ++i
) {
1258 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1260 widget
->setData(m_model
->data(i
), roles
);
1264 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1265 // The sort-role has been changed which might result
1266 // in modified group headers
1267 updateVisibleGroupHeaders();
1268 doLayout(NoAnimation
);
1271 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1272 ev
.setFirstRow(itemRange
.index
);
1273 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1274 QAccessible::updateAccessibility(&ev
);
1278 void KItemListView::slotGroupsChanged()
1280 updateVisibleGroupHeaders();
1281 doLayout(NoAnimation
);
1282 updateSiblingsInformation();
1285 void KItemListView::slotGroupedSortingChanged(bool current
)
1287 m_grouped
= current
;
1288 m_layouter
->markAsDirty();
1291 updateGroupHeaderHeight();
1293 // Clear all visible headers. Note that the QHashIterator takes a copy of
1294 // m_visibleGroups. Therefore, it remains valid even if items are removed
1295 // from m_visibleGroups in recycleGroupHeaderForWidget().
1296 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1297 while (it
.hasNext()) {
1299 recycleGroupHeaderForWidget(it
.key());
1301 Q_ASSERT(m_visibleGroups
.isEmpty());
1304 if (useAlternateBackgrounds()) {
1305 // Changing the group mode requires to update the alternate backgrounds
1306 // as with the enabled group mode the altering is done on base of the first
1308 updateAlternateBackgrounds();
1310 updateSiblingsInformation();
1311 doLayout(NoAnimation
);
1314 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1319 updateVisibleGroupHeaders();
1320 doLayout(NoAnimation
);
1324 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1329 updateVisibleGroupHeaders();
1330 doLayout(NoAnimation
);
1334 void KItemListView::slotCurrentChanged(int current
, int previous
)
1338 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1339 // always the selected item. It is not necessary to highlight the current item then.
1340 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1341 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1342 if (previousWidget
) {
1343 previousWidget
->setCurrent(false);
1346 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1347 if (currentWidget
) {
1348 currentWidget
->setCurrent(true);
1352 QAccessibleEvent
ev(this, QAccessible::Focus
);
1353 ev
.setChild(current
);
1354 QAccessible::updateAccessibility(&ev
);
1357 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1361 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1362 while (it
.hasNext()) {
1364 const int index
= it
.key();
1365 KItemListWidget
* widget
= it
.value();
1366 widget
->setSelected(current
.contains(index
));
1370 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1371 KItemListViewAnimation::AnimationType type
)
1373 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1374 Q_ASSERT(itemListWidget
);
1377 case KItemListViewAnimation::DeleteAnimation
: {
1378 // As we recycle the widget in this case it is important to assure that no
1379 // other animation has been started. This is a convention in KItemListView and
1380 // not a requirement defined by KItemListViewAnimation.
1381 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1383 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1384 // by m_visibleWidgets and must be deleted manually after the animation has
1386 recycleGroupHeaderForWidget(itemListWidget
);
1387 widgetCreator()->recycle(itemListWidget
);
1391 case KItemListViewAnimation::CreateAnimation
:
1392 case KItemListViewAnimation::MovingAnimation
:
1393 case KItemListViewAnimation::ResizeAnimation
: {
1394 const int index
= itemListWidget
->index();
1395 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1396 (index
> m_layouter
->lastVisibleIndex());
1397 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1398 recycleWidget(itemListWidget
);
1407 void KItemListView::slotLayoutTimerFinished()
1409 m_layouter
->setSize(geometry().size());
1410 doLayout(Animation
);
1413 void KItemListView::slotRubberBandPosChanged()
1418 void KItemListView::slotRubberBandActivationChanged(bool active
)
1421 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1422 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1423 m_skipAutoScrollForRubberBand
= true;
1425 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1426 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1427 m_skipAutoScrollForRubberBand
= false;
1433 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1435 qreal previousWidth
)
1438 Q_UNUSED(currentWidth
);
1439 Q_UNUSED(previousWidth
);
1441 m_headerWidget
->setAutomaticColumnResizing(false);
1442 applyColumnWidthsFromHeader();
1443 doLayout(NoAnimation
);
1446 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1450 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1452 const QList
<QByteArray
> previous
= m_visibleRoles
;
1454 QList
<QByteArray
> current
= m_visibleRoles
;
1455 current
.removeAt(previousIndex
);
1456 current
.insert(currentIndex
, role
);
1458 setVisibleRoles(current
);
1460 emit
visibleRolesChanged(current
, previous
);
1463 void KItemListView::triggerAutoScrolling()
1465 if (!m_autoScrollTimer
) {
1470 int visibleSize
= 0;
1471 if (scrollOrientation() == Qt::Vertical
) {
1472 pos
= m_mousePos
.y();
1473 visibleSize
= size().height();
1475 pos
= m_mousePos
.x();
1476 visibleSize
= size().width();
1479 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1480 m_autoScrollIncrement
= 0;
1483 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1484 if (m_autoScrollIncrement
== 0) {
1485 // The mouse position is not above an autoscroll margin (the autoscroll timer
1486 // will be restarted in mouseMoveEvent())
1487 m_autoScrollTimer
->stop();
1491 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1492 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1493 // if the direction of the rubberband is similar to the autoscroll direction. This
1494 // prevents that starting to create a rubberband within the autoscroll margins starts
1495 // an autoscrolling.
1497 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1498 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1499 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1500 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1501 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1502 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1503 // been moved up although the autoscroll direction might be down)
1504 m_autoScrollTimer
->stop();
1509 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1510 // the autoscrolling may not get skipped anymore until a new rubberband is created
1511 m_skipAutoScrollForRubberBand
= false;
1513 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1514 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1515 setScrollOffset(newScrollOffset
);
1517 // Trigger the autoscroll timer which will periodically call
1518 // triggerAutoScrolling()
1519 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1522 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1524 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1526 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1527 Q_ASSERT(groupHeader
);
1528 updateGroupHeaderLayout(widget
);
1531 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1533 disconnectRoleEditingSignals(index
);
1535 emit
roleEditingCanceled(index
, role
, value
);
1536 m_editingRole
= false;
1539 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1541 disconnectRoleEditingSignals(index
);
1543 emit
roleEditingFinished(index
, role
, value
);
1544 m_editingRole
= false;
1547 void KItemListView::setController(KItemListController
* controller
)
1549 if (m_controller
!= controller
) {
1550 KItemListController
* previous
= m_controller
;
1552 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1553 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1554 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1557 m_controller
= controller
;
1560 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1561 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1562 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1565 onControllerChanged(controller
, previous
);
1569 void KItemListView::setModel(KItemModelBase
* model
)
1571 if (m_model
== model
) {
1575 KItemModelBase
* previous
= m_model
;
1578 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1579 this, &KItemListView::slotItemsChanged
);
1580 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1581 this, &KItemListView::slotItemsInserted
);
1582 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1583 this, &KItemListView::slotItemsRemoved
);
1584 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1585 this, &KItemListView::slotItemsMoved
);
1586 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1587 this, &KItemListView::slotGroupsChanged
);
1588 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1589 this, &KItemListView::slotGroupedSortingChanged
);
1590 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1591 this, &KItemListView::slotSortOrderChanged
);
1592 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1593 this, &KItemListView::slotSortRoleChanged
);
1595 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1599 m_layouter
->setModel(model
);
1600 m_grouped
= model
->groupedSorting();
1603 connect(m_model
, &KItemModelBase::itemsChanged
,
1604 this, &KItemListView::slotItemsChanged
);
1605 connect(m_model
, &KItemModelBase::itemsInserted
,
1606 this, &KItemListView::slotItemsInserted
);
1607 connect(m_model
, &KItemModelBase::itemsRemoved
,
1608 this, &KItemListView::slotItemsRemoved
);
1609 connect(m_model
, &KItemModelBase::itemsMoved
,
1610 this, &KItemListView::slotItemsMoved
);
1611 connect(m_model
, &KItemModelBase::groupsChanged
,
1612 this, &KItemListView::slotGroupsChanged
);
1613 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1614 this, &KItemListView::slotGroupedSortingChanged
);
1615 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1616 this, &KItemListView::slotSortOrderChanged
);
1617 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1618 this, &KItemListView::slotSortRoleChanged
);
1620 const int itemCount
= m_model
->count();
1621 if (itemCount
> 0) {
1622 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1626 onModelChanged(model
, previous
);
1629 KItemListRubberBand
* KItemListView::rubberBand() const
1631 return m_rubberBand
;
1634 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1636 if (m_layoutTimer
->isActive()) {
1637 m_layoutTimer
->stop();
1640 if (m_activeTransactions
> 0) {
1641 if (hint
== NoAnimation
) {
1642 // As soon as at least one property change should be done without animation,
1643 // the whole transaction will be marked as not animated.
1644 m_endTransactionAnimationHint
= NoAnimation
;
1649 if (!m_model
|| m_model
->count() < 0) {
1653 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1654 if (firstVisibleIndex
< 0) {
1655 emitOffsetChanges();
1659 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1660 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1661 // is still shown if the maximum offset got decreased.
1662 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1663 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1664 if (scrollOffset() > maxOffsetToShowFullRange
) {
1665 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1666 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1669 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1671 int firstSibblingIndex
= -1;
1672 int lastSibblingIndex
= -1;
1673 const bool supportsExpanding
= supportsItemExpanding();
1675 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1677 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1678 // instances from invisible items are reused. If no reusable items are
1679 // found then new KItemListWidget instances get created.
1680 const bool animate
= (hint
== Animation
);
1681 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1682 bool applyNewPos
= true;
1683 bool wasHidden
= false;
1685 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1686 const QPointF newPos
= itemBounds
.topLeft();
1687 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1690 if (!reusableItems
.isEmpty()) {
1691 // Reuse a KItemListWidget instance from an invisible item
1692 const int oldIndex
= reusableItems
.takeLast();
1693 widget
= m_visibleItems
.value(oldIndex
);
1694 setWidgetIndex(widget
, i
);
1695 updateWidgetProperties(widget
, i
);
1696 initializeItemListWidget(widget
);
1698 // No reusable KItemListWidget instance is available, create a new one
1699 widget
= createWidget(i
);
1701 widget
->resize(itemBounds
.size());
1703 if (animate
&& changedCount
< 0) {
1704 // Items have been deleted.
1705 if (i
>= changedIndex
) {
1706 // The item is located behind the removed range. Move the
1707 // created item to the imaginary old position outside the
1708 // view. It will get animated to the new position later.
1709 const int previousIndex
= i
- changedCount
;
1710 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1711 if (itemRect
.isEmpty()) {
1712 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1713 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1714 widget
->setPos(invisibleOldPos
);
1716 widget
->setPos(itemRect
.topLeft());
1718 applyNewPos
= false;
1722 if (supportsExpanding
&& changedCount
== 0) {
1723 if (firstSibblingIndex
< 0) {
1724 firstSibblingIndex
= i
;
1726 lastSibblingIndex
= i
;
1731 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1732 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1733 applyNewPos
= false;
1736 const bool itemsRemoved
= (changedCount
< 0);
1737 const bool itemsInserted
= (changedCount
> 0);
1738 if (itemsRemoved
&& (i
>= changedIndex
)) {
1739 // The item is located after the removed items. Animate the moving of the position.
1740 applyNewPos
= !moveWidget(widget
, newPos
);
1741 } else if (itemsInserted
&& i
>= changedIndex
) {
1742 // The item is located after the first inserted item
1743 if (i
<= changedIndex
+ changedCount
- 1) {
1744 // The item is an inserted item. Animate the appearing of the item.
1745 // For performance reasons no animation is done when changedCount is equal
1746 // to all available items.
1747 if (changedCount
< m_model
->count()) {
1748 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1750 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1751 // The item was already there before, so animate the moving of the position.
1752 // No moving animation is done if the item is animated by a create animation: This
1753 // prevents a "move animation mess" when inserting several ranges in parallel.
1754 applyNewPos
= !moveWidget(widget
, newPos
);
1756 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1757 // The size of the view might have been changed. Animate the moving of the position.
1758 applyNewPos
= !moveWidget(widget
, newPos
);
1761 m_animation
->stop(widget
);
1765 widget
->setPos(newPos
);
1768 Q_ASSERT(widget
->index() == i
);
1769 widget
->setVisible(true);
1771 if (widget
->size() != itemBounds
.size()) {
1772 // Resize the widget for the item to the changed size.
1774 // If a dynamic item size is used then no animation is done in the direction
1775 // of the dynamic size.
1776 if (m_itemSize
.width() <= 0) {
1777 // The width is dynamic, apply the new width without animation.
1778 widget
->resize(itemBounds
.width(), widget
->size().height());
1779 } else if (m_itemSize
.height() <= 0) {
1780 // The height is dynamic, apply the new height without animation.
1781 widget
->resize(widget
->size().width(), itemBounds
.height());
1783 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1785 widget
->resize(itemBounds
.size());
1789 // Updating the cell-information must be done as last step: The decision whether the
1790 // moving-animation should be started at all is based on the previous cell-information.
1791 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1792 m_visibleCells
.insert(i
, cell
);
1795 // Delete invisible KItemListWidget instances that have not been reused
1796 foreach (int index
, reusableItems
) {
1797 recycleWidget(m_visibleItems
.value(index
));
1800 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1801 Q_ASSERT(lastSibblingIndex
>= 0);
1802 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1806 // Update the layout of all visible group headers
1807 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1808 while (it
.hasNext()) {
1810 updateGroupHeaderLayout(it
.key());
1814 emitOffsetChanges();
1817 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1818 int lastVisibleIndex
,
1819 LayoutAnimationHint hint
)
1821 // Determine all items that are completely invisible and might be
1822 // reused for items that just got (at least partly) visible. If the
1823 // animation hint is set to 'Animation' items that do e.g. an animated
1824 // moving of their position are not marked as invisible: This assures
1825 // that a scrolling inside the view can be done without breaking an animation.
1829 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1830 while (it
.hasNext()) {
1833 KItemListWidget
* widget
= it
.value();
1834 const int index
= widget
->index();
1835 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1838 if (m_animation
->isStarted(widget
)) {
1839 if (hint
== NoAnimation
) {
1840 // Stopping the animation will call KItemListView::slotAnimationFinished()
1841 // and the widget will be recycled if necessary there.
1842 m_animation
->stop(widget
);
1845 widget
->setVisible(false);
1846 items
.append(index
);
1849 recycleGroupHeaderForWidget(widget
);
1858 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1860 if (widget
->pos() == newPos
) {
1864 bool startMovingAnim
= false;
1866 if (m_itemSize
.isEmpty()) {
1867 // The items are not aligned in a grid but either as columns or rows.
1868 startMovingAnim
= true;
1870 // When having a grid the moving-animation should only be started, if it is done within
1871 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1872 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1873 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1874 const int index
= widget
->index();
1875 const Cell cell
= m_visibleCells
.value(index
);
1876 if (cell
.column
>= 0 && cell
.row
>= 0) {
1877 if (scrollOrientation() == Qt::Vertical
) {
1878 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1880 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1885 if (startMovingAnim
) {
1886 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1890 m_animation
->stop(widget
);
1891 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1895 void KItemListView::emitOffsetChanges()
1897 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1898 if (m_oldScrollOffset
!= newScrollOffset
) {
1899 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1900 m_oldScrollOffset
= newScrollOffset
;
1903 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1904 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1905 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1906 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1909 const qreal newItemOffset
= m_layouter
->itemOffset();
1910 if (m_oldItemOffset
!= newItemOffset
) {
1911 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1912 m_oldItemOffset
= newItemOffset
;
1915 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1916 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1917 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1918 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1922 KItemListWidget
* KItemListView::createWidget(int index
)
1924 KItemListWidget
* widget
= widgetCreator()->create(this);
1925 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1927 m_visibleItems
.insert(index
, widget
);
1928 m_visibleCells
.insert(index
, Cell());
1929 updateWidgetProperties(widget
, index
);
1930 initializeItemListWidget(widget
);
1934 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1937 recycleGroupHeaderForWidget(widget
);
1940 const int index
= widget
->index();
1941 m_visibleItems
.remove(index
);
1942 m_visibleCells
.remove(index
);
1944 widgetCreator()->recycle(widget
);
1947 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1949 const int oldIndex
= widget
->index();
1950 m_visibleItems
.remove(oldIndex
);
1951 m_visibleCells
.remove(oldIndex
);
1953 m_visibleItems
.insert(index
, widget
);
1954 m_visibleCells
.insert(index
, Cell());
1956 widget
->setIndex(index
);
1959 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1961 const int oldIndex
= widget
->index();
1962 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1964 setWidgetIndex(widget
, index
);
1966 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1967 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1968 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1969 (!vertical
&& oldCell
.column
== newCell
.column
);
1971 m_visibleCells
.insert(index
, newCell
);
1975 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1978 case LayouterSize
: m_layouter
->setSize(size
); break;
1979 case ItemSize
: m_layouter
->setItemSize(size
); break;
1984 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1986 widget
->setVisibleRoles(m_visibleRoles
);
1987 updateWidgetColumnWidths(widget
);
1988 widget
->setStyleOption(m_styleOption
);
1990 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1992 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1993 // always the selected item. It is not necessary to highlight the current item then.
1994 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1995 widget
->setCurrent(index
== selectionManager
->currentItem());
1997 widget
->setSelected(selectionManager
->isSelected(index
));
1998 widget
->setHovered(false);
1999 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2000 widget
->setIndex(index
);
2001 widget
->setData(m_model
->data(index
));
2002 widget
->setSiblingsInformation(QBitArray());
2003 updateAlternateBackgroundForWidget(widget
);
2006 updateGroupHeaderForWidget(widget
);
2010 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2012 Q_ASSERT(m_grouped
);
2014 const int index
= widget
->index();
2015 if (!m_layouter
->isFirstGroupItem(index
)) {
2016 // The widget does not represent the first item of a group
2017 // and hence requires no header
2018 recycleGroupHeaderForWidget(widget
);
2022 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2023 if (groups
.isEmpty() || !groupHeaderCreator()) {
2027 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2029 groupHeader
= groupHeaderCreator()->create(this);
2030 groupHeader
->setParentItem(widget
);
2031 m_visibleGroups
.insert(widget
, groupHeader
);
2032 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2034 Q_ASSERT(groupHeader
->parentItem() == widget
);
2036 const int groupIndex
= groupIndexForItem(index
);
2037 Q_ASSERT(groupIndex
>= 0);
2038 groupHeader
->setData(groups
.at(groupIndex
).second
);
2039 groupHeader
->setRole(model()->sortRole());
2040 groupHeader
->setStyleOption(m_styleOption
);
2041 groupHeader
->setScrollOrientation(scrollOrientation());
2042 groupHeader
->setItemIndex(index
);
2044 groupHeader
->show();
2047 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2049 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2050 Q_ASSERT(groupHeader
);
2052 const int index
= widget
->index();
2053 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2054 const QRectF itemRect
= m_layouter
->itemRect(index
);
2056 // The group-header is a child of the itemlist widget. Translate the
2057 // group header position to the relative position.
2058 if (scrollOrientation() == Qt::Vertical
) {
2059 // In the vertical scroll orientation the group header should always span
2060 // the whole width no matter which temporary position the parent widget
2061 // has. In this case the x-position and width will be adjusted manually.
2062 const qreal x
= -widget
->x() - itemOffset();
2063 const qreal width
= maximumItemOffset();
2064 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2065 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2067 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2068 groupHeader
->resize(groupHeaderRect
.size());
2072 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2074 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2076 header
->setParentItem(0);
2077 groupHeaderCreator()->recycle(header
);
2078 m_visibleGroups
.remove(widget
);
2079 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2083 void KItemListView::updateVisibleGroupHeaders()
2085 Q_ASSERT(m_grouped
);
2086 m_layouter
->markAsDirty();
2088 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2089 while (it
.hasNext()) {
2091 updateGroupHeaderForWidget(it
.value());
2095 int KItemListView::groupIndexForItem(int index
) const
2097 Q_ASSERT(m_grouped
);
2099 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2100 if (groups
.isEmpty()) {
2105 int max
= groups
.count() - 1;
2108 mid
= (min
+ max
) / 2;
2109 if (index
> groups
[mid
].first
) {
2114 } while (groups
[mid
].first
!= index
&& min
<= max
);
2117 while (groups
[mid
].first
> index
&& mid
> 0) {
2125 void KItemListView::updateAlternateBackgrounds()
2127 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2128 while (it
.hasNext()) {
2130 updateAlternateBackgroundForWidget(it
.value());
2134 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2136 bool enabled
= useAlternateBackgrounds();
2138 const int index
= widget
->index();
2139 enabled
= (index
& 0x1) > 0;
2141 const int groupIndex
= groupIndexForItem(index
);
2142 if (groupIndex
>= 0) {
2143 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2144 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2145 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2146 enabled
= (relativeIndex
& 0x1) > 0;
2150 widget
->setAlternateBackground(enabled
);
2153 bool KItemListView::useAlternateBackgrounds() const
2155 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2158 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2160 QElapsedTimer timer
;
2163 QHash
<QByteArray
, qreal
> widths
;
2165 // Calculate the minimum width for each column that is required
2166 // to show the headline unclipped.
2167 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2168 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2169 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2170 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2171 const QString headerText
= m_model
->roleDescription(visibleRole
);
2172 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2173 widths
.insert(visibleRole
, headerWidth
);
2176 // Calculate the preferred column withs for each item and ignore values
2177 // smaller than the width for showing the headline unclipped.
2178 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2179 int calculatedItemCount
= 0;
2180 bool maxTimeExceeded
= false;
2181 foreach (const KItemRange
& itemRange
, itemRanges
) {
2182 const int startIndex
= itemRange
.index
;
2183 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2185 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2186 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2187 qreal maxWidth
= widths
.value(visibleRole
, 0);
2188 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2189 maxWidth
= qMax(width
, maxWidth
);
2190 widths
.insert(visibleRole
, maxWidth
);
2193 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2194 // When having several thousands of items calculating the sizes can get
2195 // very expensive. We accept a possibly too small role-size in favour
2196 // of having no blocking user interface.
2197 maxTimeExceeded
= true;
2200 ++calculatedItemCount
;
2202 if (maxTimeExceeded
) {
2210 void KItemListView::applyColumnWidthsFromHeader()
2212 // Apply the new size to the layouter
2213 const qreal requiredWidth
= columnWidthsSum();
2214 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2215 m_itemSize
.height());
2216 m_layouter
->setItemSize(dynamicItemSize
);
2218 // Update the role sizes for all visible widgets
2219 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2220 while (it
.hasNext()) {
2222 updateWidgetColumnWidths(it
.value());
2226 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2228 foreach (const QByteArray
& role
, m_visibleRoles
) {
2229 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2233 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2235 Q_ASSERT(m_itemSize
.isEmpty());
2236 const int itemCount
= m_model
->count();
2237 int rangesItemCount
= 0;
2238 foreach (const KItemRange
& range
, itemRanges
) {
2239 rangesItemCount
+= range
.count
;
2242 if (itemCount
== rangesItemCount
) {
2243 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2244 foreach (const QByteArray
& role
, m_visibleRoles
) {
2245 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2248 // Only a sub range of the roles need to be determined.
2249 // The chances are good that the widths of the sub ranges
2250 // already fit into the available widths and hence no
2251 // expensive update might be required.
2252 bool changed
= false;
2254 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2255 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2256 while (it
.hasNext()) {
2258 const QByteArray
& role
= it
.key();
2259 const qreal updatedWidth
= it
.value();
2260 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2261 if (updatedWidth
> currentWidth
) {
2262 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2268 // All the updated sizes are smaller than the current sizes and no change
2269 // of the stretched roles-widths is required
2274 if (m_headerWidget
->automaticColumnResizing()) {
2275 applyAutomaticColumnWidths();
2279 void KItemListView::updatePreferredColumnWidths()
2282 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2286 void KItemListView::applyAutomaticColumnWidths()
2288 Q_ASSERT(m_itemSize
.isEmpty());
2289 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2290 if (m_visibleRoles
.isEmpty()) {
2294 // Calculate the maximum size of an item by considering the
2295 // visible role sizes and apply them to the layouter. If the
2296 // size does not use the available view-size the size of the
2297 // first role will get stretched.
2299 foreach (const QByteArray
& role
, m_visibleRoles
) {
2300 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2301 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2304 const QByteArray firstRole
= m_visibleRoles
.first();
2305 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2306 QSizeF dynamicItemSize
= m_itemSize
;
2308 qreal requiredWidth
= columnWidthsSum();
2309 const qreal availableWidth
= size().width();
2310 if (requiredWidth
< availableWidth
) {
2311 // Stretch the first column to use the whole remaining width
2312 firstColumnWidth
+= availableWidth
- requiredWidth
;
2313 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2314 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2315 // Shrink the first column to be able to show as much other
2316 // columns as possible
2317 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2319 // TODO: A proper calculation of the minimum width depends on the implementation
2320 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2322 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2323 if (shrinkedFirstColumnWidth
< minWidth
) {
2324 shrinkedFirstColumnWidth
= minWidth
;
2327 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2328 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2331 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2333 m_layouter
->setItemSize(dynamicItemSize
);
2335 // Update the role sizes for all visible widgets
2336 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2337 while (it
.hasNext()) {
2339 updateWidgetColumnWidths(it
.value());
2343 qreal
KItemListView::columnWidthsSum() const
2345 qreal widthsSum
= 0;
2346 foreach (const QByteArray
& role
, m_visibleRoles
) {
2347 widthsSum
+= m_headerWidget
->columnWidth(role
);
2352 QRectF
KItemListView::headerBoundaries() const
2354 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2357 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2358 const QSizeF
& newItemSize
,
2359 const QSizeF
& newItemMargin
) const
2361 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2365 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2366 const qreal itemWidth
= m_layouter
->itemSize().width();
2367 if (itemWidth
> 0) {
2368 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2369 newItemSize
.width(),
2370 newItemMargin
.width());
2371 if (m_model
->count() > newColumnCount
) {
2372 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2374 m_layouter
->itemMargin().width());
2375 return oldColumnCount
!= newColumnCount
;
2379 const qreal itemHeight
= m_layouter
->itemSize().height();
2380 if (itemHeight
> 0) {
2381 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2382 newItemSize
.height(),
2383 newItemMargin
.height());
2384 if (m_model
->count() > newRowCount
) {
2385 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2387 m_layouter
->itemMargin().height());
2388 return oldRowCount
!= newRowCount
;
2396 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2398 if (m_itemSize
.isEmpty()) {
2399 // We have only columns or only rows, but no grid: An animation is usually
2400 // welcome when inserting or removing items.
2401 return !supportsItemExpanding();
2404 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2408 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2409 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2410 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2411 // Only animate if up to 2/3 of a row or column are inserted or removed
2412 return changedItemCount
<= maximum
* 2 / 3;
2416 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2418 const QSizeF oldSize
= m_layouter
->size();
2420 m_layouter
->setSize(size
);
2421 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2422 m_layouter
->setSize(oldSize
);
2424 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2425 : maxOffset
> size
.width();
2428 int KItemListView::showDropIndicator(const QPointF
& pos
)
2430 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2431 while (it
.hasNext()) {
2433 const KItemListWidget
* widget
= it
.value();
2435 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2436 const QRectF rect
= itemRect(widget
->index());
2437 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2438 if (m_model
->supportsDropping(widget
->index())) {
2439 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2440 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2441 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2446 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2447 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2449 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2450 if (m_dropIndicator
!= draggingInsertIndicator
) {
2451 m_dropIndicator
= draggingInsertIndicator
;
2455 int index
= widget
->index();
2463 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2464 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2467 void KItemListView::hideDropIndicator()
2469 if (!m_dropIndicator
.isNull()) {
2470 m_dropIndicator
= QRectF();
2475 void KItemListView::updateGroupHeaderHeight()
2477 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2478 qreal groupHeaderMargin
= 0;
2480 if (scrollOrientation() == Qt::Horizontal
) {
2481 // The vertical margin above and below the header should be
2482 // equal to the horizontal margin, not the vertical margin
2483 // from m_styleOption.
2484 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2485 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2486 } else if (m_itemSize
.isEmpty()){
2487 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2488 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2490 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2491 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2493 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2494 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2496 updateVisibleGroupHeaders();
2499 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2501 if (!supportsItemExpanding() || !m_model
) {
2505 if (firstIndex
< 0 || lastIndex
< 0) {
2506 firstIndex
= m_layouter
->firstVisibleIndex();
2507 lastIndex
= m_layouter
->lastVisibleIndex();
2509 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2510 lastIndex
>= m_layouter
->firstVisibleIndex());
2511 if (!isRangeVisible
) {
2516 int previousParents
= 0;
2517 QBitArray previousSiblings
;
2519 // The rootIndex describes the first index where the siblings get
2520 // calculated from. For the calculation the upper most parent item
2521 // is required. For performance reasons it is checked first whether
2522 // the visible items before or after the current range already
2523 // contain a siblings information which can be used as base.
2524 int rootIndex
= firstIndex
;
2526 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2528 // There is no visible widget before the range, check whether there
2529 // is one after the range:
2530 widget
= m_visibleItems
.value(lastIndex
+ 1);
2532 // The sibling information of the widget may only be used if
2533 // all items of the range have the same number of parents.
2534 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2535 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2536 if (m_model
->expandedParentsCount(i
) != parents
) {
2545 // Performance optimization: Use the sibling information of the visible
2546 // widget beside the given range.
2547 previousSiblings
= widget
->siblingsInformation();
2548 if (previousSiblings
.isEmpty()) {
2551 previousParents
= previousSiblings
.count() - 1;
2552 previousSiblings
.truncate(previousParents
);
2554 // Potentially slow path: Go back to the upper most parent of firstIndex
2555 // to be able to calculate the initial value for the siblings.
2556 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2561 Q_ASSERT(previousParents
>= 0);
2562 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2563 // Update the parent-siblings in case if the current item represents
2564 // a child or an upper parent.
2565 const int currentParents
= m_model
->expandedParentsCount(i
);
2566 Q_ASSERT(currentParents
>= 0);
2567 if (previousParents
< currentParents
) {
2568 previousParents
= currentParents
;
2569 previousSiblings
.resize(currentParents
);
2570 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2571 } else if (previousParents
> currentParents
) {
2572 previousParents
= currentParents
;
2573 previousSiblings
.truncate(currentParents
);
2576 if (i
>= firstIndex
) {
2577 // The index represents a visible item. Apply the parent-siblings
2578 // and update the sibling of the current item.
2579 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2584 QBitArray siblings
= previousSiblings
;
2585 siblings
.resize(siblings
.count() + 1);
2586 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2588 widget
->setSiblingsInformation(siblings
);
2593 bool KItemListView::hasSiblingSuccessor(int index
) const
2595 bool hasSuccessor
= false;
2596 const int parentsCount
= m_model
->expandedParentsCount(index
);
2597 int successorIndex
= index
+ 1;
2599 // Search the next sibling
2600 const int itemCount
= m_model
->count();
2601 while (successorIndex
< itemCount
) {
2602 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2603 if (currentParentsCount
== parentsCount
) {
2604 hasSuccessor
= true;
2606 } else if (currentParentsCount
< parentsCount
) {
2612 if (m_grouped
&& hasSuccessor
) {
2613 // If the sibling is part of another group, don't mark it as
2614 // successor as the group header is between the sibling connections.
2615 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2616 if (m_layouter
->isFirstGroupItem(i
)) {
2617 hasSuccessor
= false;
2623 return hasSuccessor
;
2626 void KItemListView::disconnectRoleEditingSignals(int index
)
2628 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2633 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2634 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2637 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2641 const int minSpeed
= 4;
2642 const int maxSpeed
= 128;
2643 const int speedLimiter
= 96;
2644 const int autoScrollBorder
= 64;
2646 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2647 // This assures that the autoscrolling speed grows gradually.
2648 const int incLimiter
= 1;
2650 if (pos
< autoScrollBorder
) {
2651 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2652 inc
= qMax(inc
, -maxSpeed
);
2653 inc
= qMax(inc
, oldInc
- incLimiter
);
2654 } else if (pos
> range
- autoScrollBorder
) {
2655 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2656 inc
= qMin(inc
, maxSpeed
);
2657 inc
= qMin(inc
, oldInc
+ incLimiter
);
2663 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2665 const qreal availableSize
= size
- itemMargin
;
2666 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2672 KItemListCreatorBase::~KItemListCreatorBase()
2674 qDeleteAll(m_recycleableWidgets
);
2675 qDeleteAll(m_createdWidgets
);
2678 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2680 m_createdWidgets
.insert(widget
);
2683 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2685 Q_ASSERT(m_createdWidgets
.contains(widget
));
2686 m_createdWidgets
.remove(widget
);
2688 if (m_recycleableWidgets
.count() < 100) {
2689 m_recycleableWidgets
.append(widget
);
2690 widget
->setVisible(false);
2696 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2698 if (m_recycleableWidgets
.isEmpty()) {
2702 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2703 m_createdWidgets
.insert(widget
);
2707 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2711 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2713 widget
->setParentItem(0);
2714 widget
->setOpacity(1.0);
2715 pushRecycleableWidget(widget
);
2718 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2722 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2724 header
->setOpacity(1.0);
2725 pushRecycleableWidget(header
);