1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "dolphindebug.h"
26 #include "kitemlistcontainer.h"
27 #include "kitemlistcontroller.h"
28 #include "kitemlistheader.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
36 #include "private/kitemlistviewanimation.h"
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
42 #include <QStyleOptionRubberBand>
44 #include <QElapsedTimer>
48 #include "kitemlistviewaccessible.h"
51 // Time in ms until reaching the autoscroll margin triggers
52 // an initial autoscrolling
53 const int InitialAutoScrollDelay
= 700;
55 // Delay in ms for triggering the next autoscroll
56 const int RepeatingAutoScrollDelay
= 1000 / 60;
59 #ifndef QT_NO_ACCESSIBILITY
60 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
64 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
65 return new KItemListContainerAccessible(container
);
66 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
67 return new KItemListViewAccessible(view
);
74 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
75 QGraphicsWidget(parent
),
76 m_enabledSelectionToggles(false),
78 m_supportsItemExpanding(false),
80 m_activeTransactions(0),
81 m_endTransactionAnimationHint(Animation
),
87 m_groupHeaderCreator(0),
92 m_sizeHintResolver(0),
97 m_oldMaximumScrollOffset(0),
99 m_oldMaximumItemOffset(0),
100 m_skipAutoScrollForRubberBand(false),
103 m_autoScrollIncrement(0),
104 m_autoScrollTimer(0),
109 setAcceptHoverEvents(true);
111 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
113 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
115 m_animation
= new KItemListViewAnimation(this);
116 connect(m_animation
, &KItemListViewAnimation::finished
,
117 this, &KItemListView::slotAnimationFinished
);
119 m_layoutTimer
= new QTimer(this);
120 m_layoutTimer
->setInterval(300);
121 m_layoutTimer
->setSingleShot(true);
122 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
124 m_rubberBand
= new KItemListRubberBand(this);
125 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
127 m_headerWidget
= new KItemListHeaderWidget(this);
128 m_headerWidget
->setVisible(false);
130 m_header
= new KItemListHeader(this);
132 #ifndef QT_NO_ACCESSIBILITY
133 QAccessible::installFactory(accessibleInterfaceFactory
);
138 KItemListView::~KItemListView()
140 // The group headers are children of the widgets created by
141 // widgetCreator(). So it is mandatory to delete the group headers
143 delete m_groupHeaderCreator
;
144 m_groupHeaderCreator
= 0;
146 delete m_widgetCreator
;
149 delete m_sizeHintResolver
;
150 m_sizeHintResolver
= 0;
153 void KItemListView::setScrollOffset(qreal offset
)
159 const qreal previousOffset
= m_layouter
->scrollOffset();
160 if (offset
== previousOffset
) {
164 m_layouter
->setScrollOffset(offset
);
165 m_animation
->setScrollOffset(offset
);
167 // Don't check whether the m_layoutTimer is active: Changing the
168 // scroll offset must always trigger a synchronous layout, otherwise
169 // the smooth-scrolling might get jerky.
170 doLayout(NoAnimation
);
171 onScrollOffsetChanged(offset
, previousOffset
);
174 qreal
KItemListView::scrollOffset() const
176 return m_layouter
->scrollOffset();
179 qreal
KItemListView::maximumScrollOffset() const
181 return m_layouter
->maximumScrollOffset();
184 void KItemListView::setItemOffset(qreal offset
)
186 if (m_layouter
->itemOffset() == offset
) {
190 m_layouter
->setItemOffset(offset
);
191 if (m_headerWidget
->isVisible()) {
192 m_headerWidget
->setOffset(offset
);
195 // Don't check whether the m_layoutTimer is active: Changing the
196 // item offset must always trigger a synchronous layout, otherwise
197 // the smooth-scrolling might get jerky.
198 doLayout(NoAnimation
);
201 qreal
KItemListView::itemOffset() const
203 return m_layouter
->itemOffset();
206 qreal
KItemListView::maximumItemOffset() const
208 return m_layouter
->maximumItemOffset();
211 int KItemListView::maximumVisibleItems() const
213 return m_layouter
->maximumVisibleItems();
216 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
218 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
219 m_visibleRoles
= roles
;
220 onVisibleRolesChanged(roles
, previousRoles
);
222 m_sizeHintResolver
->clearCache();
223 m_layouter
->markAsDirty();
225 if (m_itemSize
.isEmpty()) {
226 m_headerWidget
->setColumns(roles
);
227 updatePreferredColumnWidths();
228 if (!m_headerWidget
->automaticColumnResizing()) {
229 // The column-width of new roles are still 0. Apply the preferred
230 // column-width as default with.
231 foreach (const QByteArray
& role
, m_visibleRoles
) {
232 if (m_headerWidget
->columnWidth(role
) == 0) {
233 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
234 m_headerWidget
->setColumnWidth(role
, width
);
238 applyColumnWidthsFromHeader();
242 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
243 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
244 (roles
.count() <= 1 && previousRoles
.count() > 1));
246 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
247 while (it
.hasNext()) {
249 KItemListWidget
* widget
= it
.value();
250 widget
->setVisibleRoles(roles
);
251 if (alternateBackgroundsChanged
) {
252 updateAlternateBackgroundForWidget(widget
);
256 doLayout(NoAnimation
);
259 QList
<QByteArray
> KItemListView::visibleRoles() const
261 return m_visibleRoles
;
264 void KItemListView::setAutoScroll(bool enabled
)
266 if (enabled
&& !m_autoScrollTimer
) {
267 m_autoScrollTimer
= new QTimer(this);
268 m_autoScrollTimer
->setSingleShot(true);
269 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
270 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
271 } else if (!enabled
&& m_autoScrollTimer
) {
272 delete m_autoScrollTimer
;
273 m_autoScrollTimer
= 0;
277 bool KItemListView::autoScroll() const
279 return m_autoScrollTimer
!= 0;
282 void KItemListView::setEnabledSelectionToggles(bool enabled
)
284 if (m_enabledSelectionToggles
!= enabled
) {
285 m_enabledSelectionToggles
= enabled
;
287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
288 while (it
.hasNext()) {
290 it
.value()->setEnabledSelectionToggle(enabled
);
295 bool KItemListView::enabledSelectionToggles() const
297 return m_enabledSelectionToggles
;
300 KItemListController
* KItemListView::controller() const
305 KItemModelBase
* KItemListView::model() const
310 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
312 if (m_widgetCreator
) {
313 delete m_widgetCreator
;
315 m_widgetCreator
= widgetCreator
;
318 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
320 if (!m_widgetCreator
) {
321 m_widgetCreator
= defaultWidgetCreator();
323 return m_widgetCreator
;
326 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
328 if (m_groupHeaderCreator
) {
329 delete m_groupHeaderCreator
;
331 m_groupHeaderCreator
= groupHeaderCreator
;
334 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
336 if (!m_groupHeaderCreator
) {
337 m_groupHeaderCreator
= defaultGroupHeaderCreator();
339 return m_groupHeaderCreator
;
342 QSizeF
KItemListView::itemSize() const
347 QSizeF
KItemListView::itemSizeHint() const
349 return m_sizeHintResolver
->maxSizeHint();
352 const KItemListStyleOption
& KItemListView::styleOption() const
354 return m_styleOption
;
357 void KItemListView::setGeometry(const QRectF
& rect
)
359 QGraphicsWidget::setGeometry(rect
);
365 const QSizeF newSize
= rect
.size();
366 if (m_itemSize
.isEmpty()) {
367 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
368 if (m_headerWidget
->automaticColumnResizing()) {
369 applyAutomaticColumnWidths();
371 const qreal requiredWidth
= columnWidthsSum();
372 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
373 m_itemSize
.height());
374 m_layouter
->setItemSize(dynamicItemSize
);
377 // Triggering a synchronous layout is fine from a performance point of view,
378 // as with dynamic item sizes no moving animation must be done.
379 m_layouter
->setSize(newSize
);
380 doLayout(NoAnimation
);
382 const bool animate
= !changesItemGridLayout(newSize
,
383 m_layouter
->itemSize(),
384 m_layouter
->itemMargin());
385 m_layouter
->setSize(newSize
);
388 // Trigger an asynchronous relayout with m_layoutTimer to prevent
389 // performance bottlenecks. If the timer is exceeded, an animated layout
390 // will be triggered.
391 if (!m_layoutTimer
->isActive()) {
392 m_layoutTimer
->start();
395 m_layoutTimer
->stop();
396 doLayout(NoAnimation
);
401 qreal
KItemListView::verticalPageStep() const
403 qreal headerHeight
= 0;
404 if (m_headerWidget
->isVisible()) {
405 headerHeight
= m_headerWidget
->size().height();
407 return size().height() - headerHeight
;
410 int KItemListView::itemAt(const QPointF
& pos
) const
412 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
413 while (it
.hasNext()) {
416 const KItemListWidget
* widget
= it
.value();
417 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
418 if (widget
->contains(mappedPos
)) {
426 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
428 if (!m_enabledSelectionToggles
) {
432 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
434 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
435 if (!selectionToggleRect
.isEmpty()) {
436 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
437 return selectionToggleRect
.contains(mappedPos
);
443 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
445 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
447 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
448 if (!expansionToggleRect
.isEmpty()) {
449 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
450 return expansionToggleRect
.contains(mappedPos
);
456 int KItemListView::firstVisibleIndex() const
458 return m_layouter
->firstVisibleIndex();
461 int KItemListView::lastVisibleIndex() const
463 return m_layouter
->lastVisibleIndex();
466 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
468 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
471 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
473 if (m_supportsItemExpanding
!= supportsExpanding
) {
474 m_supportsItemExpanding
= supportsExpanding
;
475 updateSiblingsInformation();
476 onSupportsItemExpandingChanged(supportsExpanding
);
480 bool KItemListView::supportsItemExpanding() const
482 return m_supportsItemExpanding
;
485 QRectF
KItemListView::itemRect(int index
) const
487 return m_layouter
->itemRect(index
);
490 QRectF
KItemListView::itemContextRect(int index
) const
494 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
496 contextRect
= widget
->iconRect() | widget
->textRect();
497 contextRect
.translate(itemRect(index
).topLeft());
503 void KItemListView::scrollToItem(int index
)
505 QRectF viewGeometry
= geometry();
506 if (m_headerWidget
->isVisible()) {
507 const qreal headerHeight
= m_headerWidget
->size().height();
508 viewGeometry
.adjust(0, headerHeight
, 0, 0);
510 QRectF currentRect
= itemRect(index
);
512 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
513 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
514 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
516 if (!viewGeometry
.contains(currentRect
)) {
517 qreal newOffset
= scrollOffset();
518 if (scrollOrientation() == Qt::Vertical
) {
519 if (currentRect
.top() < viewGeometry
.top()) {
520 newOffset
+= currentRect
.top() - viewGeometry
.top();
521 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
522 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
525 if (currentRect
.left() < viewGeometry
.left()) {
526 newOffset
+= currentRect
.left() - viewGeometry
.left();
527 } else if (currentRect
.right() > viewGeometry
.right()) {
528 newOffset
+= currentRect
.right() - viewGeometry
.right();
532 if (newOffset
!= scrollOffset()) {
533 emit
scrollTo(newOffset
);
538 void KItemListView::beginTransaction()
540 ++m_activeTransactions
;
541 if (m_activeTransactions
== 1) {
542 onTransactionBegin();
546 void KItemListView::endTransaction()
548 --m_activeTransactions
;
549 if (m_activeTransactions
< 0) {
550 m_activeTransactions
= 0;
551 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
554 if (m_activeTransactions
== 0) {
556 doLayout(m_endTransactionAnimationHint
);
557 m_endTransactionAnimationHint
= Animation
;
561 bool KItemListView::isTransactionActive() const
563 return m_activeTransactions
> 0;
566 void KItemListView::setHeaderVisible(bool visible
)
568 if (visible
&& !m_headerWidget
->isVisible()) {
569 QStyleOptionHeader option
;
570 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
573 m_headerWidget
->setPos(0, 0);
574 m_headerWidget
->resize(size().width(), headerSize
.height());
575 m_headerWidget
->setModel(m_model
);
576 m_headerWidget
->setColumns(m_visibleRoles
);
577 m_headerWidget
->setZValue(1);
579 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
580 this, &KItemListView::slotHeaderColumnWidthChanged
);
581 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
582 this, &KItemListView::slotHeaderColumnMoved
);
583 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
584 this, &KItemListView::sortOrderChanged
);
585 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
586 this, &KItemListView::sortRoleChanged
);
588 m_layouter
->setHeaderHeight(headerSize
.height());
589 m_headerWidget
->setVisible(true);
590 } else if (!visible
&& m_headerWidget
->isVisible()) {
591 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
592 this, &KItemListView::slotHeaderColumnWidthChanged
);
593 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
594 this, &KItemListView::slotHeaderColumnMoved
);
595 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
596 this, &KItemListView::sortOrderChanged
);
597 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
598 this, &KItemListView::sortRoleChanged
);
600 m_layouter
->setHeaderHeight(0);
601 m_headerWidget
->setVisible(false);
605 bool KItemListView::isHeaderVisible() const
607 return m_headerWidget
->isVisible();
610 KItemListHeader
* KItemListView::header() const
615 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
619 if (indexes
.count() == 1) {
620 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
621 QGraphicsView
* graphicsView
= scene()->views()[0];
622 if (item
&& graphicsView
) {
623 pixmap
= item
->createDragPixmap(0, graphicsView
);
626 // TODO: Not implemented yet. Probably extend the interface
627 // from KItemListWidget::createDragPixmap() to return a pixmap
628 // that can be used for multiple indexes.
634 void KItemListView::editRole(int index
, const QByteArray
& role
)
636 KItemListWidget
* widget
= m_visibleItems
.value(index
);
637 if (!widget
|| m_editingRole
) {
641 m_editingRole
= true;
642 widget
->setEditedRole(role
);
644 connect(widget
, &KItemListWidget::roleEditingCanceled
,
645 this, &KItemListView::slotRoleEditingCanceled
);
646 connect(widget
, &KItemListWidget::roleEditingFinished
,
647 this, &KItemListView::slotRoleEditingFinished
);
650 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
652 QGraphicsWidget::paint(painter
, option
, widget
);
654 if (m_rubberBand
->isActive()) {
655 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
656 m_rubberBand
->endPosition()).normalized();
658 const QPointF topLeft
= rubberBandRect
.topLeft();
659 if (scrollOrientation() == Qt::Vertical
) {
660 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
662 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
665 QStyleOptionRubberBand opt
;
666 opt
.initFrom(widget
);
667 opt
.shape
= QRubberBand::Rectangle
;
669 opt
.rect
= rubberBandRect
.toRect();
670 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
673 if (!m_dropIndicator
.isEmpty()) {
674 const QRectF r
= m_dropIndicator
.toRect();
676 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
677 painter
->setPen(color
);
679 // TODO: The following implementation works only for a vertical scroll-orientation
680 // and assumes a height of the m_draggingInsertIndicator of 1.
681 Q_ASSERT(r
.height() == 1);
682 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
685 painter
->setPen(color
);
686 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
690 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
692 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
693 if (!scene()->views().isEmpty()) {
694 m_styleOption
.palette
= scene()->views().at(0)->palette();
697 return QGraphicsItem::itemChange(change
, value
);
700 void KItemListView::setItemSize(const QSizeF
& size
)
702 const QSizeF previousSize
= m_itemSize
;
703 if (size
== previousSize
) {
707 // Skip animations when the number of rows or columns
708 // are changed in the grid layout. Although the animation
709 // engine can handle this usecase, it looks obtrusive.
710 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
712 m_layouter
->itemMargin());
714 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
715 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
716 (!m_itemSize
.isEmpty() && size
.isEmpty()));
720 if (alternateBackgroundsChanged
) {
721 // For an empty item size alternate backgrounds are drawn if more than
722 // one role is shown. Assure that the backgrounds for visible items are
723 // updated when changing the size in this context.
724 updateAlternateBackgrounds();
727 if (size
.isEmpty()) {
728 if (m_headerWidget
->automaticColumnResizing()) {
729 updatePreferredColumnWidths();
731 // Only apply the changed height and respect the header widths
733 const qreal currentWidth
= m_layouter
->itemSize().width();
734 const QSizeF
newSize(currentWidth
, size
.height());
735 m_layouter
->setItemSize(newSize
);
738 m_layouter
->setItemSize(size
);
741 m_sizeHintResolver
->clearCache();
742 doLayout(animate
? Animation
: NoAnimation
);
743 onItemSizeChanged(size
, previousSize
);
746 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
748 const KItemListStyleOption previousOption
= m_styleOption
;
749 m_styleOption
= option
;
752 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
753 if (margin
!= m_layouter
->itemMargin()) {
754 // Skip animations when the number of rows or columns
755 // are changed in the grid layout. Although the animation
756 // engine can handle this usecase, it looks obtrusive.
757 animate
= !changesItemGridLayout(m_layouter
->size(),
758 m_layouter
->itemSize(),
760 m_layouter
->setItemMargin(margin
);
764 updateGroupHeaderHeight();
768 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
769 // Animating a change of the maximum text size just results in expensive
770 // temporary eliding and clipping operations and does not look good visually.
774 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
775 while (it
.hasNext()) {
777 it
.value()->setStyleOption(option
);
780 m_sizeHintResolver
->clearCache();
781 m_layouter
->markAsDirty();
782 doLayout(animate
? Animation
: NoAnimation
);
784 if (m_itemSize
.isEmpty()) {
785 updatePreferredColumnWidths();
788 onStyleOptionChanged(option
, previousOption
);
791 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
793 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
794 if (orientation
== previousOrientation
) {
798 m_layouter
->setScrollOrientation(orientation
);
799 m_animation
->setScrollOrientation(orientation
);
800 m_sizeHintResolver
->clearCache();
803 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
804 while (it
.hasNext()) {
806 it
.value()->setScrollOrientation(orientation
);
808 updateGroupHeaderHeight();
812 doLayout(NoAnimation
);
814 onScrollOrientationChanged(orientation
, previousOrientation
);
815 emit
scrollOrientationChanged(orientation
, previousOrientation
);
818 Qt::Orientation
KItemListView::scrollOrientation() const
820 return m_layouter
->scrollOrientation();
823 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
828 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
833 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
838 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
840 Q_UNUSED(changedRoles
);
844 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
850 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
856 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
862 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
868 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
874 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
880 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
886 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
888 Q_UNUSED(supportsExpanding
);
891 void KItemListView::onTransactionBegin()
895 void KItemListView::onTransactionEnd()
899 bool KItemListView::event(QEvent
* event
)
901 switch (event
->type()) {
902 case QEvent::PaletteChange
:
906 case QEvent::FontChange
:
911 // Forward all other events to the controller and handle them there
912 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
918 return QGraphicsWidget::event(event
);
921 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
923 m_mousePos
= transform().map(event
->pos());
927 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
929 QGraphicsWidget::mouseMoveEvent(event
);
931 m_mousePos
= transform().map(event
->pos());
932 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
933 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
937 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
939 event
->setAccepted(true);
943 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
945 QGraphicsWidget::dragMoveEvent(event
);
947 m_mousePos
= transform().map(event
->pos());
948 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
949 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
953 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
955 QGraphicsWidget::dragLeaveEvent(event
);
956 setAutoScroll(false);
959 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
961 QGraphicsWidget::dropEvent(event
);
962 setAutoScroll(false);
965 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
967 return m_visibleItems
.values();
970 void KItemListView::updateFont()
972 if (scene() && !scene()->views().isEmpty()) {
973 KItemListStyleOption option
= styleOption();
974 option
.font
= scene()->views().first()->font();
975 option
.fontMetrics
= QFontMetrics(option
.font
);
977 setStyleOption(option
);
981 void KItemListView::updatePalette()
983 if (scene() && !scene()->views().isEmpty()) {
984 KItemListStyleOption option
= styleOption();
985 option
.palette
= scene()->views().first()->palette();
987 setStyleOption(option
);
991 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
993 if (m_itemSize
.isEmpty()) {
994 updatePreferredColumnWidths(itemRanges
);
997 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
998 if (hasMultipleRanges
) {
1002 m_layouter
->markAsDirty();
1004 m_sizeHintResolver
->itemsInserted(itemRanges
);
1006 int previouslyInsertedCount
= 0;
1007 foreach (const KItemRange
& range
, itemRanges
) {
1008 // range.index is related to the model before anything has been inserted.
1009 // As in each loop the current item-range gets inserted the index must
1010 // be increased by the already previously inserted items.
1011 const int index
= range
.index
+ previouslyInsertedCount
;
1012 const int count
= range
.count
;
1013 if (index
< 0 || count
<= 0) {
1014 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1017 previouslyInsertedCount
+= count
;
1019 // Determine which visible items must be moved
1020 QList
<int> itemsToMove
;
1021 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1022 while (it
.hasNext()) {
1024 const int visibleItemIndex
= it
.key();
1025 if (visibleItemIndex
>= index
) {
1026 itemsToMove
.append(visibleItemIndex
);
1030 // Update the indexes of all KItemListWidget instances that are located
1031 // after the inserted items. It is important to adjust the indexes in the order
1032 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1034 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1035 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1037 const int newIndex
= widget
->index() + count
;
1038 if (hasMultipleRanges
) {
1039 setWidgetIndex(widget
, newIndex
);
1041 // Try to animate the moving of the item
1042 moveWidgetToIndex(widget
, newIndex
);
1046 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1047 // Check whether a scrollbar is required to show the inserted items. In this case
1048 // the size of the layouter will be decreased before calling doLayout(): This prevents
1049 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1050 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1051 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1052 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1053 if (decreaseLayouterSize
) {
1054 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1056 int scrollbarSpacing
= 0;
1057 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1058 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1061 QSizeF layouterSize
= m_layouter
->size();
1062 if (verticalScrollOrientation
) {
1063 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1065 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1067 m_layouter
->setSize(layouterSize
);
1071 if (!hasMultipleRanges
) {
1072 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1073 updateSiblingsInformation();
1078 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1081 if (hasMultipleRanges
) {
1082 m_endTransactionAnimationHint
= NoAnimation
;
1085 updateSiblingsInformation();
1088 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1089 // In case if items of the same group have been inserted before an item that
1090 // currently represents the first item of the group, the group header of
1091 // this item must be removed.
1092 updateVisibleGroupHeaders();
1095 if (useAlternateBackgrounds()) {
1096 updateAlternateBackgrounds();
1100 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1102 if (m_itemSize
.isEmpty()) {
1103 // Don't pass the item-range: The preferred column-widths of
1104 // all items must be adjusted when removing items.
1105 updatePreferredColumnWidths();
1108 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1109 if (hasMultipleRanges
) {
1113 m_layouter
->markAsDirty();
1115 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1117 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1118 const KItemRange
& range
= itemRanges
[i
];
1119 const int index
= range
.index
;
1120 const int count
= range
.count
;
1121 if (index
< 0 || count
<= 0) {
1122 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1126 const int firstRemovedIndex
= index
;
1127 const int lastRemovedIndex
= index
+ count
- 1;
1129 // Remember which items have to be moved because they are behind the removed range.
1130 QVector
<int> itemsToMove
;
1132 // Remove all KItemListWidget instances that got deleted
1133 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1134 const int i
= widget
->index();
1135 if (i
< firstRemovedIndex
) {
1137 } else if (i
> lastRemovedIndex
) {
1138 itemsToMove
.append(i
);
1142 m_animation
->stop(widget
);
1143 // Stopping the animation might lead to recycling the widget if
1144 // it is invisible (see slotAnimationFinished()).
1145 // Check again whether it is still visible:
1146 if (!m_visibleItems
.contains(i
)) {
1150 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1151 // Remove the widget without animation
1152 recycleWidget(widget
);
1154 // Animate the removing of the items. Special case: When removing an item there
1155 // is no valid model index available anymore. For the
1156 // remove-animation the item gets removed from m_visibleItems but the widget
1157 // will stay alive until the animation has been finished and will
1158 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1159 m_visibleItems
.remove(i
);
1160 widget
->setIndex(-1);
1161 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1165 // Update the indexes of all KItemListWidget instances that are located
1166 // after the deleted items. It is important to update them in ascending
1167 // order to prevent overlaps when setting the new index.
1168 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1169 foreach (int i
, itemsToMove
) {
1170 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1172 const int newIndex
= i
- count
;
1173 if (hasMultipleRanges
) {
1174 setWidgetIndex(widget
, newIndex
);
1176 // Try to animate the moving of the item
1177 moveWidgetToIndex(widget
, newIndex
);
1181 if (!hasMultipleRanges
) {
1182 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1183 // assumes an updated geometry. If items are removed during an active transaction,
1184 // the transaction will be temporary deactivated so that doLayout() triggers a
1185 // geometry update if necessary.
1186 const int activeTransactions
= m_activeTransactions
;
1187 m_activeTransactions
= 0;
1188 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1189 m_activeTransactions
= activeTransactions
;
1190 updateSiblingsInformation();
1195 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1198 if (hasMultipleRanges
) {
1199 m_endTransactionAnimationHint
= NoAnimation
;
1201 updateSiblingsInformation();
1204 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1205 // In case if the first item of a group has been removed, the group header
1206 // must be applied to the next visible item.
1207 updateVisibleGroupHeaders();
1210 if (useAlternateBackgrounds()) {
1211 updateAlternateBackgrounds();
1215 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1217 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1218 m_layouter
->markAsDirty();
1221 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1224 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1225 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1227 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1228 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1230 updateWidgetProperties(widget
, index
);
1231 initializeItemListWidget(widget
);
1235 doLayout(NoAnimation
);
1236 updateSiblingsInformation();
1239 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1240 const QSet
<QByteArray
>& roles
)
1242 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1243 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1244 updatePreferredColumnWidths(itemRanges
);
1247 foreach (const KItemRange
& itemRange
, itemRanges
) {
1248 const int index
= itemRange
.index
;
1249 const int count
= itemRange
.count
;
1251 if (updateSizeHints
) {
1252 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1253 m_layouter
->markAsDirty();
1255 if (!m_layoutTimer
->isActive()) {
1256 m_layoutTimer
->start();
1260 // Apply the changed roles to the visible item-widgets
1261 const int lastIndex
= index
+ count
- 1;
1262 for (int i
= index
; i
<= lastIndex
; ++i
) {
1263 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1265 widget
->setData(m_model
->data(i
), roles
);
1269 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1270 // The sort-role has been changed which might result
1271 // in modified group headers
1272 updateVisibleGroupHeaders();
1273 doLayout(NoAnimation
);
1276 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1277 ev
.setFirstRow(itemRange
.index
);
1278 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1279 QAccessible::updateAccessibility(&ev
);
1283 void KItemListView::slotGroupsChanged()
1285 updateVisibleGroupHeaders();
1286 doLayout(NoAnimation
);
1287 updateSiblingsInformation();
1290 void KItemListView::slotGroupedSortingChanged(bool current
)
1292 m_grouped
= current
;
1293 m_layouter
->markAsDirty();
1296 updateGroupHeaderHeight();
1298 // Clear all visible headers. Note that the QHashIterator takes a copy of
1299 // m_visibleGroups. Therefore, it remains valid even if items are removed
1300 // from m_visibleGroups in recycleGroupHeaderForWidget().
1301 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1302 while (it
.hasNext()) {
1304 recycleGroupHeaderForWidget(it
.key());
1306 Q_ASSERT(m_visibleGroups
.isEmpty());
1309 if (useAlternateBackgrounds()) {
1310 // Changing the group mode requires to update the alternate backgrounds
1311 // as with the enabled group mode the altering is done on base of the first
1313 updateAlternateBackgrounds();
1315 updateSiblingsInformation();
1316 doLayout(NoAnimation
);
1319 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1324 updateVisibleGroupHeaders();
1325 doLayout(NoAnimation
);
1329 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1334 updateVisibleGroupHeaders();
1335 doLayout(NoAnimation
);
1339 void KItemListView::slotCurrentChanged(int current
, int previous
)
1343 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1344 // always the selected item. It is not necessary to highlight the current item then.
1345 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1346 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1347 if (previousWidget
) {
1348 previousWidget
->setCurrent(false);
1351 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1352 if (currentWidget
) {
1353 currentWidget
->setCurrent(true);
1357 QAccessibleEvent
ev(this, QAccessible::Focus
);
1358 ev
.setChild(current
);
1359 QAccessible::updateAccessibility(&ev
);
1362 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1366 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1367 while (it
.hasNext()) {
1369 const int index
= it
.key();
1370 KItemListWidget
* widget
= it
.value();
1371 widget
->setSelected(current
.contains(index
));
1375 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1376 KItemListViewAnimation::AnimationType type
)
1378 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1379 Q_ASSERT(itemListWidget
);
1382 case KItemListViewAnimation::DeleteAnimation
: {
1383 // As we recycle the widget in this case it is important to assure that no
1384 // other animation has been started. This is a convention in KItemListView and
1385 // not a requirement defined by KItemListViewAnimation.
1386 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1388 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1389 // by m_visibleWidgets and must be deleted manually after the animation has
1391 recycleGroupHeaderForWidget(itemListWidget
);
1392 widgetCreator()->recycle(itemListWidget
);
1396 case KItemListViewAnimation::CreateAnimation
:
1397 case KItemListViewAnimation::MovingAnimation
:
1398 case KItemListViewAnimation::ResizeAnimation
: {
1399 const int index
= itemListWidget
->index();
1400 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1401 (index
> m_layouter
->lastVisibleIndex());
1402 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1403 recycleWidget(itemListWidget
);
1412 void KItemListView::slotLayoutTimerFinished()
1414 m_layouter
->setSize(geometry().size());
1415 doLayout(Animation
);
1418 void KItemListView::slotRubberBandPosChanged()
1423 void KItemListView::slotRubberBandActivationChanged(bool active
)
1426 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1427 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1428 m_skipAutoScrollForRubberBand
= true;
1430 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1431 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1432 m_skipAutoScrollForRubberBand
= false;
1438 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1440 qreal previousWidth
)
1443 Q_UNUSED(currentWidth
);
1444 Q_UNUSED(previousWidth
);
1446 m_headerWidget
->setAutomaticColumnResizing(false);
1447 applyColumnWidthsFromHeader();
1448 doLayout(NoAnimation
);
1451 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1455 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1457 const QList
<QByteArray
> previous
= m_visibleRoles
;
1459 QList
<QByteArray
> current
= m_visibleRoles
;
1460 current
.removeAt(previousIndex
);
1461 current
.insert(currentIndex
, role
);
1463 setVisibleRoles(current
);
1465 emit
visibleRolesChanged(current
, previous
);
1468 void KItemListView::triggerAutoScrolling()
1470 if (!m_autoScrollTimer
) {
1475 int visibleSize
= 0;
1476 if (scrollOrientation() == Qt::Vertical
) {
1477 pos
= m_mousePos
.y();
1478 visibleSize
= size().height();
1480 pos
= m_mousePos
.x();
1481 visibleSize
= size().width();
1484 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1485 m_autoScrollIncrement
= 0;
1488 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1489 if (m_autoScrollIncrement
== 0) {
1490 // The mouse position is not above an autoscroll margin (the autoscroll timer
1491 // will be restarted in mouseMoveEvent())
1492 m_autoScrollTimer
->stop();
1496 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1497 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1498 // if the direction of the rubberband is similar to the autoscroll direction. This
1499 // prevents that starting to create a rubberband within the autoscroll margins starts
1500 // an autoscrolling.
1502 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1503 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1504 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1505 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1506 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1507 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1508 // been moved up although the autoscroll direction might be down)
1509 m_autoScrollTimer
->stop();
1514 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1515 // the autoscrolling may not get skipped anymore until a new rubberband is created
1516 m_skipAutoScrollForRubberBand
= false;
1518 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1519 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1520 setScrollOffset(newScrollOffset
);
1522 // Trigger the autoscroll timer which will periodically call
1523 // triggerAutoScrolling()
1524 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1527 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1529 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1531 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1532 Q_ASSERT(groupHeader
);
1533 updateGroupHeaderLayout(widget
);
1536 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1538 disconnectRoleEditingSignals(index
);
1540 emit
roleEditingCanceled(index
, role
, value
);
1541 m_editingRole
= false;
1544 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1546 disconnectRoleEditingSignals(index
);
1548 emit
roleEditingFinished(index
, role
, value
);
1549 m_editingRole
= false;
1552 void KItemListView::setController(KItemListController
* controller
)
1554 if (m_controller
!= controller
) {
1555 KItemListController
* previous
= m_controller
;
1557 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1558 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1559 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1562 m_controller
= controller
;
1565 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1566 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1567 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1570 onControllerChanged(controller
, previous
);
1574 void KItemListView::setModel(KItemModelBase
* model
)
1576 if (m_model
== model
) {
1580 KItemModelBase
* previous
= m_model
;
1583 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1584 this, &KItemListView::slotItemsChanged
);
1585 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1586 this, &KItemListView::slotItemsInserted
);
1587 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1588 this, &KItemListView::slotItemsRemoved
);
1589 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1590 this, &KItemListView::slotItemsMoved
);
1591 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1592 this, &KItemListView::slotGroupsChanged
);
1593 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1594 this, &KItemListView::slotGroupedSortingChanged
);
1595 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1596 this, &KItemListView::slotSortOrderChanged
);
1597 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1598 this, &KItemListView::slotSortRoleChanged
);
1600 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1604 m_layouter
->setModel(model
);
1605 m_grouped
= model
->groupedSorting();
1608 connect(m_model
, &KItemModelBase::itemsChanged
,
1609 this, &KItemListView::slotItemsChanged
);
1610 connect(m_model
, &KItemModelBase::itemsInserted
,
1611 this, &KItemListView::slotItemsInserted
);
1612 connect(m_model
, &KItemModelBase::itemsRemoved
,
1613 this, &KItemListView::slotItemsRemoved
);
1614 connect(m_model
, &KItemModelBase::itemsMoved
,
1615 this, &KItemListView::slotItemsMoved
);
1616 connect(m_model
, &KItemModelBase::groupsChanged
,
1617 this, &KItemListView::slotGroupsChanged
);
1618 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1619 this, &KItemListView::slotGroupedSortingChanged
);
1620 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1621 this, &KItemListView::slotSortOrderChanged
);
1622 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1623 this, &KItemListView::slotSortRoleChanged
);
1625 const int itemCount
= m_model
->count();
1626 if (itemCount
> 0) {
1627 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1631 onModelChanged(model
, previous
);
1634 KItemListRubberBand
* KItemListView::rubberBand() const
1636 return m_rubberBand
;
1639 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1641 if (m_layoutTimer
->isActive()) {
1642 m_layoutTimer
->stop();
1645 if (m_activeTransactions
> 0) {
1646 if (hint
== NoAnimation
) {
1647 // As soon as at least one property change should be done without animation,
1648 // the whole transaction will be marked as not animated.
1649 m_endTransactionAnimationHint
= NoAnimation
;
1654 if (!m_model
|| m_model
->count() < 0) {
1658 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1659 if (firstVisibleIndex
< 0) {
1660 emitOffsetChanges();
1664 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1665 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1666 // is still shown if the maximum offset got decreased.
1667 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1668 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1669 if (scrollOffset() > maxOffsetToShowFullRange
) {
1670 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1671 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1674 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1676 int firstSibblingIndex
= -1;
1677 int lastSibblingIndex
= -1;
1678 const bool supportsExpanding
= supportsItemExpanding();
1680 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1682 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1683 // instances from invisible items are reused. If no reusable items are
1684 // found then new KItemListWidget instances get created.
1685 const bool animate
= (hint
== Animation
);
1686 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1687 bool applyNewPos
= true;
1688 bool wasHidden
= false;
1690 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1691 const QPointF newPos
= itemBounds
.topLeft();
1692 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1695 if (!reusableItems
.isEmpty()) {
1696 // Reuse a KItemListWidget instance from an invisible item
1697 const int oldIndex
= reusableItems
.takeLast();
1698 widget
= m_visibleItems
.value(oldIndex
);
1699 setWidgetIndex(widget
, i
);
1700 updateWidgetProperties(widget
, i
);
1701 initializeItemListWidget(widget
);
1703 // No reusable KItemListWidget instance is available, create a new one
1704 widget
= createWidget(i
);
1706 widget
->resize(itemBounds
.size());
1708 if (animate
&& changedCount
< 0) {
1709 // Items have been deleted.
1710 if (i
>= changedIndex
) {
1711 // The item is located behind the removed range. Move the
1712 // created item to the imaginary old position outside the
1713 // view. It will get animated to the new position later.
1714 const int previousIndex
= i
- changedCount
;
1715 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1716 if (itemRect
.isEmpty()) {
1717 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1718 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1719 widget
->setPos(invisibleOldPos
);
1721 widget
->setPos(itemRect
.topLeft());
1723 applyNewPos
= false;
1727 if (supportsExpanding
&& changedCount
== 0) {
1728 if (firstSibblingIndex
< 0) {
1729 firstSibblingIndex
= i
;
1731 lastSibblingIndex
= i
;
1736 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1737 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1738 applyNewPos
= false;
1741 const bool itemsRemoved
= (changedCount
< 0);
1742 const bool itemsInserted
= (changedCount
> 0);
1743 if (itemsRemoved
&& (i
>= changedIndex
)) {
1744 // The item is located after the removed items. Animate the moving of the position.
1745 applyNewPos
= !moveWidget(widget
, newPos
);
1746 } else if (itemsInserted
&& i
>= changedIndex
) {
1747 // The item is located after the first inserted item
1748 if (i
<= changedIndex
+ changedCount
- 1) {
1749 // The item is an inserted item. Animate the appearing of the item.
1750 // For performance reasons no animation is done when changedCount is equal
1751 // to all available items.
1752 if (changedCount
< m_model
->count()) {
1753 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1755 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1756 // The item was already there before, so animate the moving of the position.
1757 // No moving animation is done if the item is animated by a create animation: This
1758 // prevents a "move animation mess" when inserting several ranges in parallel.
1759 applyNewPos
= !moveWidget(widget
, newPos
);
1761 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1762 // The size of the view might have been changed. Animate the moving of the position.
1763 applyNewPos
= !moveWidget(widget
, newPos
);
1766 m_animation
->stop(widget
);
1770 widget
->setPos(newPos
);
1773 Q_ASSERT(widget
->index() == i
);
1774 widget
->setVisible(true);
1776 if (widget
->size() != itemBounds
.size()) {
1777 // Resize the widget for the item to the changed size.
1779 // If a dynamic item size is used then no animation is done in the direction
1780 // of the dynamic size.
1781 if (m_itemSize
.width() <= 0) {
1782 // The width is dynamic, apply the new width without animation.
1783 widget
->resize(itemBounds
.width(), widget
->size().height());
1784 } else if (m_itemSize
.height() <= 0) {
1785 // The height is dynamic, apply the new height without animation.
1786 widget
->resize(widget
->size().width(), itemBounds
.height());
1788 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1790 widget
->resize(itemBounds
.size());
1794 // Updating the cell-information must be done as last step: The decision whether the
1795 // moving-animation should be started at all is based on the previous cell-information.
1796 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1797 m_visibleCells
.insert(i
, cell
);
1800 // Delete invisible KItemListWidget instances that have not been reused
1801 foreach (int index
, reusableItems
) {
1802 recycleWidget(m_visibleItems
.value(index
));
1805 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1806 Q_ASSERT(lastSibblingIndex
>= 0);
1807 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1811 // Update the layout of all visible group headers
1812 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1813 while (it
.hasNext()) {
1815 updateGroupHeaderLayout(it
.key());
1819 emitOffsetChanges();
1822 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1823 int lastVisibleIndex
,
1824 LayoutAnimationHint hint
)
1826 // Determine all items that are completely invisible and might be
1827 // reused for items that just got (at least partly) visible. If the
1828 // animation hint is set to 'Animation' items that do e.g. an animated
1829 // moving of their position are not marked as invisible: This assures
1830 // that a scrolling inside the view can be done without breaking an animation.
1834 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1835 while (it
.hasNext()) {
1838 KItemListWidget
* widget
= it
.value();
1839 const int index
= widget
->index();
1840 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1843 if (m_animation
->isStarted(widget
)) {
1844 if (hint
== NoAnimation
) {
1845 // Stopping the animation will call KItemListView::slotAnimationFinished()
1846 // and the widget will be recycled if necessary there.
1847 m_animation
->stop(widget
);
1850 widget
->setVisible(false);
1851 items
.append(index
);
1854 recycleGroupHeaderForWidget(widget
);
1863 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1865 if (widget
->pos() == newPos
) {
1869 bool startMovingAnim
= false;
1871 if (m_itemSize
.isEmpty()) {
1872 // The items are not aligned in a grid but either as columns or rows.
1873 startMovingAnim
= true;
1875 // When having a grid the moving-animation should only be started, if it is done within
1876 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1877 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1878 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1879 const int index
= widget
->index();
1880 const Cell cell
= m_visibleCells
.value(index
);
1881 if (cell
.column
>= 0 && cell
.row
>= 0) {
1882 if (scrollOrientation() == Qt::Vertical
) {
1883 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1885 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1890 if (startMovingAnim
) {
1891 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1895 m_animation
->stop(widget
);
1896 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1900 void KItemListView::emitOffsetChanges()
1902 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1903 if (m_oldScrollOffset
!= newScrollOffset
) {
1904 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1905 m_oldScrollOffset
= newScrollOffset
;
1908 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1909 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1910 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1911 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1914 const qreal newItemOffset
= m_layouter
->itemOffset();
1915 if (m_oldItemOffset
!= newItemOffset
) {
1916 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1917 m_oldItemOffset
= newItemOffset
;
1920 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1921 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1922 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1923 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1927 KItemListWidget
* KItemListView::createWidget(int index
)
1929 KItemListWidget
* widget
= widgetCreator()->create(this);
1930 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1932 m_visibleItems
.insert(index
, widget
);
1933 m_visibleCells
.insert(index
, Cell());
1934 updateWidgetProperties(widget
, index
);
1935 initializeItemListWidget(widget
);
1939 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1942 recycleGroupHeaderForWidget(widget
);
1945 const int index
= widget
->index();
1946 m_visibleItems
.remove(index
);
1947 m_visibleCells
.remove(index
);
1949 widgetCreator()->recycle(widget
);
1952 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1954 const int oldIndex
= widget
->index();
1955 m_visibleItems
.remove(oldIndex
);
1956 m_visibleCells
.remove(oldIndex
);
1958 m_visibleItems
.insert(index
, widget
);
1959 m_visibleCells
.insert(index
, Cell());
1961 widget
->setIndex(index
);
1964 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1966 const int oldIndex
= widget
->index();
1967 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1969 setWidgetIndex(widget
, index
);
1971 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1972 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1973 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1974 (!vertical
&& oldCell
.column
== newCell
.column
);
1976 m_visibleCells
.insert(index
, newCell
);
1980 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1983 case LayouterSize
: m_layouter
->setSize(size
); break;
1984 case ItemSize
: m_layouter
->setItemSize(size
); break;
1989 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1991 widget
->setVisibleRoles(m_visibleRoles
);
1992 updateWidgetColumnWidths(widget
);
1993 widget
->setStyleOption(m_styleOption
);
1995 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1997 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1998 // always the selected item. It is not necessary to highlight the current item then.
1999 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2000 widget
->setCurrent(index
== selectionManager
->currentItem());
2002 widget
->setSelected(selectionManager
->isSelected(index
));
2003 widget
->setHovered(false);
2004 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2005 widget
->setIndex(index
);
2006 widget
->setData(m_model
->data(index
));
2007 widget
->setSiblingsInformation(QBitArray());
2008 updateAlternateBackgroundForWidget(widget
);
2011 updateGroupHeaderForWidget(widget
);
2015 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2017 Q_ASSERT(m_grouped
);
2019 const int index
= widget
->index();
2020 if (!m_layouter
->isFirstGroupItem(index
)) {
2021 // The widget does not represent the first item of a group
2022 // and hence requires no header
2023 recycleGroupHeaderForWidget(widget
);
2027 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2028 if (groups
.isEmpty() || !groupHeaderCreator()) {
2032 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2034 groupHeader
= groupHeaderCreator()->create(this);
2035 groupHeader
->setParentItem(widget
);
2036 m_visibleGroups
.insert(widget
, groupHeader
);
2037 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2039 Q_ASSERT(groupHeader
->parentItem() == widget
);
2041 const int groupIndex
= groupIndexForItem(index
);
2042 Q_ASSERT(groupIndex
>= 0);
2043 groupHeader
->setData(groups
.at(groupIndex
).second
);
2044 groupHeader
->setRole(model()->sortRole());
2045 groupHeader
->setStyleOption(m_styleOption
);
2046 groupHeader
->setScrollOrientation(scrollOrientation());
2047 groupHeader
->setItemIndex(index
);
2049 groupHeader
->show();
2052 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2054 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2055 Q_ASSERT(groupHeader
);
2057 const int index
= widget
->index();
2058 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2059 const QRectF itemRect
= m_layouter
->itemRect(index
);
2061 // The group-header is a child of the itemlist widget. Translate the
2062 // group header position to the relative position.
2063 if (scrollOrientation() == Qt::Vertical
) {
2064 // In the vertical scroll orientation the group header should always span
2065 // the whole width no matter which temporary position the parent widget
2066 // has. In this case the x-position and width will be adjusted manually.
2067 const qreal x
= -widget
->x() - itemOffset();
2068 const qreal width
= maximumItemOffset();
2069 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2070 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2072 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2073 groupHeader
->resize(groupHeaderRect
.size());
2077 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2079 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2081 header
->setParentItem(0);
2082 groupHeaderCreator()->recycle(header
);
2083 m_visibleGroups
.remove(widget
);
2084 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2088 void KItemListView::updateVisibleGroupHeaders()
2090 Q_ASSERT(m_grouped
);
2091 m_layouter
->markAsDirty();
2093 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2094 while (it
.hasNext()) {
2096 updateGroupHeaderForWidget(it
.value());
2100 int KItemListView::groupIndexForItem(int index
) const
2102 Q_ASSERT(m_grouped
);
2104 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2105 if (groups
.isEmpty()) {
2110 int max
= groups
.count() - 1;
2113 mid
= (min
+ max
) / 2;
2114 if (index
> groups
[mid
].first
) {
2119 } while (groups
[mid
].first
!= index
&& min
<= max
);
2122 while (groups
[mid
].first
> index
&& mid
> 0) {
2130 void KItemListView::updateAlternateBackgrounds()
2132 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2133 while (it
.hasNext()) {
2135 updateAlternateBackgroundForWidget(it
.value());
2139 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2141 bool enabled
= useAlternateBackgrounds();
2143 const int index
= widget
->index();
2144 enabled
= (index
& 0x1) > 0;
2146 const int groupIndex
= groupIndexForItem(index
);
2147 if (groupIndex
>= 0) {
2148 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2149 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2150 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2151 enabled
= (relativeIndex
& 0x1) > 0;
2155 widget
->setAlternateBackground(enabled
);
2158 bool KItemListView::useAlternateBackgrounds() const
2160 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2163 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2165 QElapsedTimer timer
;
2168 QHash
<QByteArray
, qreal
> widths
;
2170 // Calculate the minimum width for each column that is required
2171 // to show the headline unclipped.
2172 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2173 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2174 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2175 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2176 const QString headerText
= m_model
->roleDescription(visibleRole
);
2177 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2178 widths
.insert(visibleRole
, headerWidth
);
2181 // Calculate the preferred column withs for each item and ignore values
2182 // smaller than the width for showing the headline unclipped.
2183 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2184 int calculatedItemCount
= 0;
2185 bool maxTimeExceeded
= false;
2186 foreach (const KItemRange
& itemRange
, itemRanges
) {
2187 const int startIndex
= itemRange
.index
;
2188 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2190 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2191 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2192 qreal maxWidth
= widths
.value(visibleRole
, 0);
2193 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2194 maxWidth
= qMax(width
, maxWidth
);
2195 widths
.insert(visibleRole
, maxWidth
);
2198 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2199 // When having several thousands of items calculating the sizes can get
2200 // very expensive. We accept a possibly too small role-size in favour
2201 // of having no blocking user interface.
2202 maxTimeExceeded
= true;
2205 ++calculatedItemCount
;
2207 if (maxTimeExceeded
) {
2215 void KItemListView::applyColumnWidthsFromHeader()
2217 // Apply the new size to the layouter
2218 const qreal requiredWidth
= columnWidthsSum();
2219 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2220 m_itemSize
.height());
2221 m_layouter
->setItemSize(dynamicItemSize
);
2223 // Update the role sizes for all visible widgets
2224 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2225 while (it
.hasNext()) {
2227 updateWidgetColumnWidths(it
.value());
2231 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2233 foreach (const QByteArray
& role
, m_visibleRoles
) {
2234 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2238 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2240 Q_ASSERT(m_itemSize
.isEmpty());
2241 const int itemCount
= m_model
->count();
2242 int rangesItemCount
= 0;
2243 foreach (const KItemRange
& range
, itemRanges
) {
2244 rangesItemCount
+= range
.count
;
2247 if (itemCount
== rangesItemCount
) {
2248 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2249 foreach (const QByteArray
& role
, m_visibleRoles
) {
2250 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2253 // Only a sub range of the roles need to be determined.
2254 // The chances are good that the widths of the sub ranges
2255 // already fit into the available widths and hence no
2256 // expensive update might be required.
2257 bool changed
= false;
2259 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2260 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2261 while (it
.hasNext()) {
2263 const QByteArray
& role
= it
.key();
2264 const qreal updatedWidth
= it
.value();
2265 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2266 if (updatedWidth
> currentWidth
) {
2267 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2273 // All the updated sizes are smaller than the current sizes and no change
2274 // of the stretched roles-widths is required
2279 if (m_headerWidget
->automaticColumnResizing()) {
2280 applyAutomaticColumnWidths();
2284 void KItemListView::updatePreferredColumnWidths()
2287 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2291 void KItemListView::applyAutomaticColumnWidths()
2293 Q_ASSERT(m_itemSize
.isEmpty());
2294 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2295 if (m_visibleRoles
.isEmpty()) {
2299 // Calculate the maximum size of an item by considering the
2300 // visible role sizes and apply them to the layouter. If the
2301 // size does not use the available view-size the size of the
2302 // first role will get stretched.
2304 foreach (const QByteArray
& role
, m_visibleRoles
) {
2305 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2306 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2309 const QByteArray firstRole
= m_visibleRoles
.first();
2310 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2311 QSizeF dynamicItemSize
= m_itemSize
;
2313 qreal requiredWidth
= columnWidthsSum();
2314 const qreal availableWidth
= size().width();
2315 if (requiredWidth
< availableWidth
) {
2316 // Stretch the first column to use the whole remaining width
2317 firstColumnWidth
+= availableWidth
- requiredWidth
;
2318 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2319 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2320 // Shrink the first column to be able to show as much other
2321 // columns as possible
2322 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2324 // TODO: A proper calculation of the minimum width depends on the implementation
2325 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2327 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2328 if (shrinkedFirstColumnWidth
< minWidth
) {
2329 shrinkedFirstColumnWidth
= minWidth
;
2332 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2333 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2336 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2338 m_layouter
->setItemSize(dynamicItemSize
);
2340 // Update the role sizes for all visible widgets
2341 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2342 while (it
.hasNext()) {
2344 updateWidgetColumnWidths(it
.value());
2348 qreal
KItemListView::columnWidthsSum() const
2350 qreal widthsSum
= 0;
2351 foreach (const QByteArray
& role
, m_visibleRoles
) {
2352 widthsSum
+= m_headerWidget
->columnWidth(role
);
2357 QRectF
KItemListView::headerBoundaries() const
2359 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2362 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2363 const QSizeF
& newItemSize
,
2364 const QSizeF
& newItemMargin
) const
2366 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2370 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2371 const qreal itemWidth
= m_layouter
->itemSize().width();
2372 if (itemWidth
> 0) {
2373 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2374 newItemSize
.width(),
2375 newItemMargin
.width());
2376 if (m_model
->count() > newColumnCount
) {
2377 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2379 m_layouter
->itemMargin().width());
2380 return oldColumnCount
!= newColumnCount
;
2384 const qreal itemHeight
= m_layouter
->itemSize().height();
2385 if (itemHeight
> 0) {
2386 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2387 newItemSize
.height(),
2388 newItemMargin
.height());
2389 if (m_model
->count() > newRowCount
) {
2390 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2392 m_layouter
->itemMargin().height());
2393 return oldRowCount
!= newRowCount
;
2401 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2403 if (m_itemSize
.isEmpty()) {
2404 // We have only columns or only rows, but no grid: An animation is usually
2405 // welcome when inserting or removing items.
2406 return !supportsItemExpanding();
2409 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2413 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2414 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2415 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2416 // Only animate if up to 2/3 of a row or column are inserted or removed
2417 return changedItemCount
<= maximum
* 2 / 3;
2421 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2423 const QSizeF oldSize
= m_layouter
->size();
2425 m_layouter
->setSize(size
);
2426 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2427 m_layouter
->setSize(oldSize
);
2429 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2430 : maxOffset
> size
.width();
2433 int KItemListView::showDropIndicator(const QPointF
& pos
)
2435 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2436 while (it
.hasNext()) {
2438 const KItemListWidget
* widget
= it
.value();
2440 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2441 const QRectF rect
= itemRect(widget
->index());
2442 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2443 if (m_model
->supportsDropping(widget
->index())) {
2444 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2445 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2446 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2451 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2452 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2454 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2455 if (m_dropIndicator
!= draggingInsertIndicator
) {
2456 m_dropIndicator
= draggingInsertIndicator
;
2460 int index
= widget
->index();
2468 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2469 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2472 void KItemListView::hideDropIndicator()
2474 if (!m_dropIndicator
.isNull()) {
2475 m_dropIndicator
= QRectF();
2480 void KItemListView::updateGroupHeaderHeight()
2482 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2483 qreal groupHeaderMargin
= 0;
2485 if (scrollOrientation() == Qt::Horizontal
) {
2486 // The vertical margin above and below the header should be
2487 // equal to the horizontal margin, not the vertical margin
2488 // from m_styleOption.
2489 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2490 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2491 } else if (m_itemSize
.isEmpty()){
2492 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2493 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2495 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2496 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2498 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2499 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2501 updateVisibleGroupHeaders();
2504 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2506 if (!supportsItemExpanding() || !m_model
) {
2510 if (firstIndex
< 0 || lastIndex
< 0) {
2511 firstIndex
= m_layouter
->firstVisibleIndex();
2512 lastIndex
= m_layouter
->lastVisibleIndex();
2514 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2515 lastIndex
>= m_layouter
->firstVisibleIndex());
2516 if (!isRangeVisible
) {
2521 int previousParents
= 0;
2522 QBitArray previousSiblings
;
2524 // The rootIndex describes the first index where the siblings get
2525 // calculated from. For the calculation the upper most parent item
2526 // is required. For performance reasons it is checked first whether
2527 // the visible items before or after the current range already
2528 // contain a siblings information which can be used as base.
2529 int rootIndex
= firstIndex
;
2531 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2533 // There is no visible widget before the range, check whether there
2534 // is one after the range:
2535 widget
= m_visibleItems
.value(lastIndex
+ 1);
2537 // The sibling information of the widget may only be used if
2538 // all items of the range have the same number of parents.
2539 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2540 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2541 if (m_model
->expandedParentsCount(i
) != parents
) {
2550 // Performance optimization: Use the sibling information of the visible
2551 // widget beside the given range.
2552 previousSiblings
= widget
->siblingsInformation();
2553 if (previousSiblings
.isEmpty()) {
2556 previousParents
= previousSiblings
.count() - 1;
2557 previousSiblings
.truncate(previousParents
);
2559 // Potentially slow path: Go back to the upper most parent of firstIndex
2560 // to be able to calculate the initial value for the siblings.
2561 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2566 Q_ASSERT(previousParents
>= 0);
2567 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2568 // Update the parent-siblings in case if the current item represents
2569 // a child or an upper parent.
2570 const int currentParents
= m_model
->expandedParentsCount(i
);
2571 Q_ASSERT(currentParents
>= 0);
2572 if (previousParents
< currentParents
) {
2573 previousParents
= currentParents
;
2574 previousSiblings
.resize(currentParents
);
2575 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2576 } else if (previousParents
> currentParents
) {
2577 previousParents
= currentParents
;
2578 previousSiblings
.truncate(currentParents
);
2581 if (i
>= firstIndex
) {
2582 // The index represents a visible item. Apply the parent-siblings
2583 // and update the sibling of the current item.
2584 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2589 QBitArray siblings
= previousSiblings
;
2590 siblings
.resize(siblings
.count() + 1);
2591 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2593 widget
->setSiblingsInformation(siblings
);
2598 bool KItemListView::hasSiblingSuccessor(int index
) const
2600 bool hasSuccessor
= false;
2601 const int parentsCount
= m_model
->expandedParentsCount(index
);
2602 int successorIndex
= index
+ 1;
2604 // Search the next sibling
2605 const int itemCount
= m_model
->count();
2606 while (successorIndex
< itemCount
) {
2607 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2608 if (currentParentsCount
== parentsCount
) {
2609 hasSuccessor
= true;
2611 } else if (currentParentsCount
< parentsCount
) {
2617 if (m_grouped
&& hasSuccessor
) {
2618 // If the sibling is part of another group, don't mark it as
2619 // successor as the group header is between the sibling connections.
2620 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2621 if (m_layouter
->isFirstGroupItem(i
)) {
2622 hasSuccessor
= false;
2628 return hasSuccessor
;
2631 void KItemListView::disconnectRoleEditingSignals(int index
)
2633 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2638 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2639 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2642 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2646 const int minSpeed
= 4;
2647 const int maxSpeed
= 128;
2648 const int speedLimiter
= 96;
2649 const int autoScrollBorder
= 64;
2651 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2652 // This assures that the autoscrolling speed grows gradually.
2653 const int incLimiter
= 1;
2655 if (pos
< autoScrollBorder
) {
2656 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2657 inc
= qMax(inc
, -maxSpeed
);
2658 inc
= qMax(inc
, oldInc
- incLimiter
);
2659 } else if (pos
> range
- autoScrollBorder
) {
2660 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2661 inc
= qMin(inc
, maxSpeed
);
2662 inc
= qMin(inc
, oldInc
+ incLimiter
);
2668 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2670 const qreal availableSize
= size
- itemMargin
;
2671 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2677 KItemListCreatorBase::~KItemListCreatorBase()
2679 qDeleteAll(m_recycleableWidgets
);
2680 qDeleteAll(m_createdWidgets
);
2683 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2685 m_createdWidgets
.insert(widget
);
2688 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2690 Q_ASSERT(m_createdWidgets
.contains(widget
));
2691 m_createdWidgets
.remove(widget
);
2693 if (m_recycleableWidgets
.count() < 100) {
2694 m_recycleableWidgets
.append(widget
);
2695 widget
->setVisible(false);
2701 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2703 if (m_recycleableWidgets
.isEmpty()) {
2707 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2708 m_createdWidgets
.insert(widget
);
2712 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2716 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2718 widget
->setParentItem(0);
2719 widget
->setOpacity(1.0);
2720 pushRecycleableWidget(widget
);
2723 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2727 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2729 header
->setOpacity(1.0);
2730 pushRecycleableWidget(header
);