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 "kstandarditemlistwidget.h"
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
36 #include "private/kitemlistviewanimation.h"
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
42 #include <QStyleOptionRubberBand>
44 #include <QElapsedTimer>
48 #include "kitemlistviewaccessible.h"
51 // Time in ms until reaching the autoscroll margin triggers
52 // an initial autoscrolling
53 const int InitialAutoScrollDelay
= 700;
55 // Delay in ms for triggering the next autoscroll
56 const int RepeatingAutoScrollDelay
= 1000 / 60;
59 #ifndef QT_NO_ACCESSIBILITY
60 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
64 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
65 return new KItemListContainerAccessible(container
);
66 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
67 return new KItemListViewAccessible(view
);
74 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
75 QGraphicsWidget(parent
),
76 m_enabledSelectionToggles(false),
78 m_supportsItemExpanding(false),
80 m_activeTransactions(0),
81 m_endTransactionAnimationHint(Animation
),
87 m_groupHeaderCreator(0),
92 m_sizeHintResolver(0),
97 m_oldMaximumScrollOffset(0),
99 m_oldMaximumItemOffset(0),
100 m_skipAutoScrollForRubberBand(false),
103 m_autoScrollIncrement(0),
104 m_autoScrollTimer(0),
109 setAcceptHoverEvents(true);
111 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
113 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
115 m_animation
= new KItemListViewAnimation(this);
116 connect(m_animation
, &KItemListViewAnimation::finished
,
117 this, &KItemListView::slotAnimationFinished
);
119 m_layoutTimer
= new QTimer(this);
120 m_layoutTimer
->setInterval(300);
121 m_layoutTimer
->setSingleShot(true);
122 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
124 m_rubberBand
= new KItemListRubberBand(this);
125 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
127 m_headerWidget
= new KItemListHeaderWidget(this);
128 m_headerWidget
->setVisible(false);
130 m_header
= new KItemListHeader(this);
132 #ifndef QT_NO_ACCESSIBILITY
133 QAccessible::installFactory(accessibleInterfaceFactory
);
138 KItemListView::~KItemListView()
140 // The group headers are children of the widgets created by
141 // widgetCreator(). So it is mandatory to delete the group headers
143 delete m_groupHeaderCreator
;
144 m_groupHeaderCreator
= 0;
146 delete m_widgetCreator
;
149 delete m_sizeHintResolver
;
150 m_sizeHintResolver
= 0;
153 void KItemListView::setScrollOffset(qreal offset
)
159 const qreal previousOffset
= m_layouter
->scrollOffset();
160 if (offset
== previousOffset
) {
164 m_layouter
->setScrollOffset(offset
);
165 m_animation
->setScrollOffset(offset
);
167 // Don't check whether the m_layoutTimer is active: Changing the
168 // scroll offset must always trigger a synchronous layout, otherwise
169 // the smooth-scrolling might get jerky.
170 doLayout(NoAnimation
);
171 onScrollOffsetChanged(offset
, previousOffset
);
174 qreal
KItemListView::scrollOffset() const
176 return m_layouter
->scrollOffset();
179 qreal
KItemListView::maximumScrollOffset() const
181 return m_layouter
->maximumScrollOffset();
184 void KItemListView::setItemOffset(qreal offset
)
186 if (m_layouter
->itemOffset() == offset
) {
190 m_layouter
->setItemOffset(offset
);
191 if (m_headerWidget
->isVisible()) {
192 m_headerWidget
->setOffset(offset
);
195 // Don't check whether the m_layoutTimer is active: Changing the
196 // item offset must always trigger a synchronous layout, otherwise
197 // the smooth-scrolling might get jerky.
198 doLayout(NoAnimation
);
201 qreal
KItemListView::itemOffset() const
203 return m_layouter
->itemOffset();
206 qreal
KItemListView::maximumItemOffset() const
208 return m_layouter
->maximumItemOffset();
211 int KItemListView::maximumVisibleItems() const
213 return m_layouter
->maximumVisibleItems();
216 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
218 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
219 m_visibleRoles
= roles
;
220 onVisibleRolesChanged(roles
, previousRoles
);
222 m_sizeHintResolver
->clearCache();
223 m_layouter
->markAsDirty();
225 if (m_itemSize
.isEmpty()) {
226 m_headerWidget
->setColumns(roles
);
227 updatePreferredColumnWidths();
228 if (!m_headerWidget
->automaticColumnResizing()) {
229 // The column-width of new roles are still 0. Apply the preferred
230 // column-width as default with.
231 foreach (const QByteArray
& role
, m_visibleRoles
) {
232 if (m_headerWidget
->columnWidth(role
) == 0) {
233 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
234 m_headerWidget
->setColumnWidth(role
, width
);
238 applyColumnWidthsFromHeader();
242 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
243 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
244 (roles
.count() <= 1 && previousRoles
.count() > 1));
246 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
247 while (it
.hasNext()) {
249 KItemListWidget
* widget
= it
.value();
250 widget
->setVisibleRoles(roles
);
251 if (alternateBackgroundsChanged
) {
252 updateAlternateBackgroundForWidget(widget
);
256 doLayout(NoAnimation
);
259 QList
<QByteArray
> KItemListView::visibleRoles() const
261 return m_visibleRoles
;
264 void KItemListView::setAutoScroll(bool enabled
)
266 if (enabled
&& !m_autoScrollTimer
) {
267 m_autoScrollTimer
= new QTimer(this);
268 m_autoScrollTimer
->setSingleShot(true);
269 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
270 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
271 } else if (!enabled
&& m_autoScrollTimer
) {
272 delete m_autoScrollTimer
;
273 m_autoScrollTimer
= 0;
277 bool KItemListView::autoScroll() const
279 return m_autoScrollTimer
!= 0;
282 void KItemListView::setEnabledSelectionToggles(bool enabled
)
284 if (m_enabledSelectionToggles
!= enabled
) {
285 m_enabledSelectionToggles
= enabled
;
287 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
288 while (it
.hasNext()) {
290 it
.value()->setEnabledSelectionToggle(enabled
);
295 bool KItemListView::enabledSelectionToggles() const
297 return m_enabledSelectionToggles
;
300 KItemListController
* KItemListView::controller() const
305 KItemModelBase
* KItemListView::model() const
310 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
312 delete m_widgetCreator
;
313 m_widgetCreator
= widgetCreator
;
316 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
318 if (!m_widgetCreator
) {
319 m_widgetCreator
= defaultWidgetCreator();
321 return m_widgetCreator
;
324 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
326 delete m_groupHeaderCreator
;
327 m_groupHeaderCreator
= groupHeaderCreator
;
330 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
332 if (!m_groupHeaderCreator
) {
333 m_groupHeaderCreator
= defaultGroupHeaderCreator();
335 return m_groupHeaderCreator
;
338 QSizeF
KItemListView::itemSize() const
343 QSizeF
KItemListView::itemSizeHint() const
345 return m_sizeHintResolver
->maxSizeHint();
348 const KItemListStyleOption
& KItemListView::styleOption() const
350 return m_styleOption
;
353 void KItemListView::setGeometry(const QRectF
& rect
)
355 QGraphicsWidget::setGeometry(rect
);
361 const QSizeF newSize
= rect
.size();
362 if (m_itemSize
.isEmpty()) {
363 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
364 if (m_headerWidget
->automaticColumnResizing()) {
365 applyAutomaticColumnWidths();
367 const qreal requiredWidth
= columnWidthsSum();
368 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
369 m_itemSize
.height());
370 m_layouter
->setItemSize(dynamicItemSize
);
373 // Triggering a synchronous layout is fine from a performance point of view,
374 // as with dynamic item sizes no moving animation must be done.
375 m_layouter
->setSize(newSize
);
376 doLayout(NoAnimation
);
378 const bool animate
= !changesItemGridLayout(newSize
,
379 m_layouter
->itemSize(),
380 m_layouter
->itemMargin());
381 m_layouter
->setSize(newSize
);
384 // Trigger an asynchronous relayout with m_layoutTimer to prevent
385 // performance bottlenecks. If the timer is exceeded, an animated layout
386 // will be triggered.
387 if (!m_layoutTimer
->isActive()) {
388 m_layoutTimer
->start();
391 m_layoutTimer
->stop();
392 doLayout(NoAnimation
);
397 qreal
KItemListView::verticalPageStep() const
399 qreal headerHeight
= 0;
400 if (m_headerWidget
->isVisible()) {
401 headerHeight
= m_headerWidget
->size().height();
403 return size().height() - headerHeight
;
406 int KItemListView::itemAt(const QPointF
& pos
) const
408 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
409 while (it
.hasNext()) {
412 const KItemListWidget
* widget
= it
.value();
413 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
414 if (widget
->contains(mappedPos
)) {
422 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
424 if (!m_enabledSelectionToggles
) {
428 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
430 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
431 if (!selectionToggleRect
.isEmpty()) {
432 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
433 return selectionToggleRect
.contains(mappedPos
);
439 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
441 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
443 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
444 if (!expansionToggleRect
.isEmpty()) {
445 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
446 return expansionToggleRect
.contains(mappedPos
);
452 bool KItemListView::isAboveText(int index
, const QPointF
&pos
) const
454 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
456 const QRectF
&textRect
= widget
->textRect();
457 if (!textRect
.isEmpty()) {
458 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
459 return textRect
.contains(mappedPos
);
465 int KItemListView::firstVisibleIndex() const
467 return m_layouter
->firstVisibleIndex();
470 int KItemListView::lastVisibleIndex() const
472 return m_layouter
->lastVisibleIndex();
475 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
477 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
480 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
482 if (m_supportsItemExpanding
!= supportsExpanding
) {
483 m_supportsItemExpanding
= supportsExpanding
;
484 updateSiblingsInformation();
485 onSupportsItemExpandingChanged(supportsExpanding
);
489 bool KItemListView::supportsItemExpanding() const
491 return m_supportsItemExpanding
;
494 QRectF
KItemListView::itemRect(int index
) const
496 return m_layouter
->itemRect(index
);
499 QRectF
KItemListView::itemContextRect(int index
) const
503 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
505 contextRect
= widget
->iconRect() | widget
->textRect();
506 contextRect
.translate(itemRect(index
).topLeft());
512 void KItemListView::scrollToItem(int index
)
514 QRectF viewGeometry
= geometry();
515 if (m_headerWidget
->isVisible()) {
516 const qreal headerHeight
= m_headerWidget
->size().height();
517 viewGeometry
.adjust(0, headerHeight
, 0, 0);
519 QRectF currentRect
= itemRect(index
);
521 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
522 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
523 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
525 if (!viewGeometry
.contains(currentRect
)) {
526 qreal newOffset
= scrollOffset();
527 if (scrollOrientation() == Qt::Vertical
) {
528 if (currentRect
.top() < viewGeometry
.top()) {
529 newOffset
+= currentRect
.top() - viewGeometry
.top();
530 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
531 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
534 if (currentRect
.left() < viewGeometry
.left()) {
535 newOffset
+= currentRect
.left() - viewGeometry
.left();
536 } else if (currentRect
.right() > viewGeometry
.right()) {
537 newOffset
+= currentRect
.right() - viewGeometry
.right();
541 if (newOffset
!= scrollOffset()) {
542 emit
scrollTo(newOffset
);
547 void KItemListView::beginTransaction()
549 ++m_activeTransactions
;
550 if (m_activeTransactions
== 1) {
551 onTransactionBegin();
555 void KItemListView::endTransaction()
557 --m_activeTransactions
;
558 if (m_activeTransactions
< 0) {
559 m_activeTransactions
= 0;
560 qCWarning(DolphinDebug
) << "Mismatch between beginTransaction()/endTransaction()";
563 if (m_activeTransactions
== 0) {
565 doLayout(m_endTransactionAnimationHint
);
566 m_endTransactionAnimationHint
= Animation
;
570 bool KItemListView::isTransactionActive() const
572 return m_activeTransactions
> 0;
575 void KItemListView::setHeaderVisible(bool visible
)
577 if (visible
&& !m_headerWidget
->isVisible()) {
578 QStyleOptionHeader option
;
579 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
582 m_headerWidget
->setPos(0, 0);
583 m_headerWidget
->resize(size().width(), headerSize
.height());
584 m_headerWidget
->setModel(m_model
);
585 m_headerWidget
->setColumns(m_visibleRoles
);
586 m_headerWidget
->setZValue(1);
588 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
589 this, &KItemListView::slotHeaderColumnWidthChanged
);
590 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
591 this, &KItemListView::slotHeaderColumnMoved
);
592 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
593 this, &KItemListView::sortOrderChanged
);
594 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
595 this, &KItemListView::sortRoleChanged
);
597 m_layouter
->setHeaderHeight(headerSize
.height());
598 m_headerWidget
->setVisible(true);
599 } else if (!visible
&& m_headerWidget
->isVisible()) {
600 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
601 this, &KItemListView::slotHeaderColumnWidthChanged
);
602 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
603 this, &KItemListView::slotHeaderColumnMoved
);
604 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
605 this, &KItemListView::sortOrderChanged
);
606 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
607 this, &KItemListView::sortRoleChanged
);
609 m_layouter
->setHeaderHeight(0);
610 m_headerWidget
->setVisible(false);
614 bool KItemListView::isHeaderVisible() const
616 return m_headerWidget
->isVisible();
619 KItemListHeader
* KItemListView::header() const
624 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
628 if (indexes
.count() == 1) {
629 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
630 QGraphicsView
* graphicsView
= scene()->views()[0];
631 if (item
&& graphicsView
) {
632 pixmap
= item
->createDragPixmap(0, graphicsView
);
635 // TODO: Not implemented yet. Probably extend the interface
636 // from KItemListWidget::createDragPixmap() to return a pixmap
637 // that can be used for multiple indexes.
643 void KItemListView::editRole(int index
, const QByteArray
& role
)
645 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
646 if (!widget
|| m_editingRole
) {
650 m_editingRole
= true;
651 widget
->setEditedRole(role
);
653 connect(widget
, &KItemListWidget::roleEditingCanceled
,
654 this, &KItemListView::slotRoleEditingCanceled
);
655 connect(widget
, &KItemListWidget::roleEditingFinished
,
656 this, &KItemListView::slotRoleEditingFinished
);
658 connect(this, &KItemListView::scrollOffsetChanged
,
659 widget
, &KStandardItemListWidget::finishRoleEditing
);
662 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
664 QGraphicsWidget::paint(painter
, option
, widget
);
666 if (m_rubberBand
->isActive()) {
667 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
668 m_rubberBand
->endPosition()).normalized();
670 const QPointF topLeft
= rubberBandRect
.topLeft();
671 if (scrollOrientation() == Qt::Vertical
) {
672 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
674 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
677 QStyleOptionRubberBand opt
;
678 opt
.initFrom(widget
);
679 opt
.shape
= QRubberBand::Rectangle
;
681 opt
.rect
= rubberBandRect
.toRect();
682 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
685 if (!m_dropIndicator
.isEmpty()) {
686 const QRectF r
= m_dropIndicator
.toRect();
688 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
689 painter
->setPen(color
);
691 // TODO: The following implementation works only for a vertical scroll-orientation
692 // and assumes a height of the m_draggingInsertIndicator of 1.
693 Q_ASSERT(r
.height() == 1);
694 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
697 painter
->setPen(color
);
698 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
702 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
704 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
705 if (!scene()->views().isEmpty()) {
706 m_styleOption
.palette
= scene()->views().at(0)->palette();
709 return QGraphicsItem::itemChange(change
, value
);
712 void KItemListView::setItemSize(const QSizeF
& size
)
714 const QSizeF previousSize
= m_itemSize
;
715 if (size
== previousSize
) {
719 // Skip animations when the number of rows or columns
720 // are changed in the grid layout. Although the animation
721 // engine can handle this usecase, it looks obtrusive.
722 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
724 m_layouter
->itemMargin());
726 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
727 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
728 (!m_itemSize
.isEmpty() && size
.isEmpty()));
732 if (alternateBackgroundsChanged
) {
733 // For an empty item size alternate backgrounds are drawn if more than
734 // one role is shown. Assure that the backgrounds for visible items are
735 // updated when changing the size in this context.
736 updateAlternateBackgrounds();
739 if (size
.isEmpty()) {
740 if (m_headerWidget
->automaticColumnResizing()) {
741 updatePreferredColumnWidths();
743 // Only apply the changed height and respect the header widths
745 const qreal currentWidth
= m_layouter
->itemSize().width();
746 const QSizeF
newSize(currentWidth
, size
.height());
747 m_layouter
->setItemSize(newSize
);
750 m_layouter
->setItemSize(size
);
753 m_sizeHintResolver
->clearCache();
754 doLayout(animate
? Animation
: NoAnimation
);
755 onItemSizeChanged(size
, previousSize
);
758 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
760 const KItemListStyleOption previousOption
= m_styleOption
;
761 m_styleOption
= option
;
764 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
765 if (margin
!= m_layouter
->itemMargin()) {
766 // Skip animations when the number of rows or columns
767 // are changed in the grid layout. Although the animation
768 // engine can handle this usecase, it looks obtrusive.
769 animate
= !changesItemGridLayout(m_layouter
->size(),
770 m_layouter
->itemSize(),
772 m_layouter
->setItemMargin(margin
);
776 updateGroupHeaderHeight();
780 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
781 // Animating a change of the maximum text size just results in expensive
782 // temporary eliding and clipping operations and does not look good visually.
786 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
787 while (it
.hasNext()) {
789 it
.value()->setStyleOption(option
);
792 m_sizeHintResolver
->clearCache();
793 m_layouter
->markAsDirty();
794 doLayout(animate
? Animation
: NoAnimation
);
796 if (m_itemSize
.isEmpty()) {
797 updatePreferredColumnWidths();
800 onStyleOptionChanged(option
, previousOption
);
803 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
805 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
806 if (orientation
== previousOrientation
) {
810 m_layouter
->setScrollOrientation(orientation
);
811 m_animation
->setScrollOrientation(orientation
);
812 m_sizeHintResolver
->clearCache();
815 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
816 while (it
.hasNext()) {
818 it
.value()->setScrollOrientation(orientation
);
820 updateGroupHeaderHeight();
824 doLayout(NoAnimation
);
826 onScrollOrientationChanged(orientation
, previousOrientation
);
827 emit
scrollOrientationChanged(orientation
, previousOrientation
);
830 Qt::Orientation
KItemListView::scrollOrientation() const
832 return m_layouter
->scrollOrientation();
835 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
840 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
845 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
850 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
852 Q_UNUSED(changedRoles
);
856 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
862 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
868 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
874 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
880 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
886 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
892 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
898 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
900 Q_UNUSED(supportsExpanding
);
903 void KItemListView::onTransactionBegin()
907 void KItemListView::onTransactionEnd()
911 bool KItemListView::event(QEvent
* event
)
913 switch (event
->type()) {
914 case QEvent::PaletteChange
:
918 case QEvent::FontChange
:
923 // Forward all other events to the controller and handle them there
924 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
930 return QGraphicsWidget::event(event
);
933 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
935 m_mousePos
= transform().map(event
->pos());
939 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
941 QGraphicsWidget::mouseMoveEvent(event
);
943 m_mousePos
= transform().map(event
->pos());
944 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
945 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
949 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
951 event
->setAccepted(true);
955 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
957 QGraphicsWidget::dragMoveEvent(event
);
959 m_mousePos
= transform().map(event
->pos());
960 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
961 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
965 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
967 QGraphicsWidget::dragLeaveEvent(event
);
968 setAutoScroll(false);
971 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
973 QGraphicsWidget::dropEvent(event
);
974 setAutoScroll(false);
977 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
979 return m_visibleItems
.values();
982 void KItemListView::updateFont()
984 if (scene() && !scene()->views().isEmpty()) {
985 KItemListStyleOption option
= styleOption();
986 option
.font
= scene()->views().first()->font();
987 option
.fontMetrics
= QFontMetrics(option
.font
);
989 setStyleOption(option
);
993 void KItemListView::updatePalette()
995 if (scene() && !scene()->views().isEmpty()) {
996 KItemListStyleOption option
= styleOption();
997 option
.palette
= scene()->views().first()->palette();
999 setStyleOption(option
);
1003 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
1005 if (m_itemSize
.isEmpty()) {
1006 updatePreferredColumnWidths(itemRanges
);
1009 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1010 if (hasMultipleRanges
) {
1014 m_layouter
->markAsDirty();
1016 m_sizeHintResolver
->itemsInserted(itemRanges
);
1018 int previouslyInsertedCount
= 0;
1019 foreach (const KItemRange
& range
, itemRanges
) {
1020 // range.index is related to the model before anything has been inserted.
1021 // As in each loop the current item-range gets inserted the index must
1022 // be increased by the already previously inserted items.
1023 const int index
= range
.index
+ previouslyInsertedCount
;
1024 const int count
= range
.count
;
1025 if (index
< 0 || count
<= 0) {
1026 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1029 previouslyInsertedCount
+= count
;
1031 // Determine which visible items must be moved
1032 QList
<int> itemsToMove
;
1033 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1034 while (it
.hasNext()) {
1036 const int visibleItemIndex
= it
.key();
1037 if (visibleItemIndex
>= index
) {
1038 itemsToMove
.append(visibleItemIndex
);
1042 // Update the indexes of all KItemListWidget instances that are located
1043 // after the inserted items. It is important to adjust the indexes in the order
1044 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1046 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1047 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1049 const int newIndex
= widget
->index() + count
;
1050 if (hasMultipleRanges
) {
1051 setWidgetIndex(widget
, newIndex
);
1053 // Try to animate the moving of the item
1054 moveWidgetToIndex(widget
, newIndex
);
1058 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1059 // Check whether a scrollbar is required to show the inserted items. In this case
1060 // the size of the layouter will be decreased before calling doLayout(): This prevents
1061 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1062 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1063 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1064 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1065 if (decreaseLayouterSize
) {
1066 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1068 int scrollbarSpacing
= 0;
1069 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1070 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1073 QSizeF layouterSize
= m_layouter
->size();
1074 if (verticalScrollOrientation
) {
1075 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1077 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1079 m_layouter
->setSize(layouterSize
);
1083 if (!hasMultipleRanges
) {
1084 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1085 updateSiblingsInformation();
1090 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1093 if (hasMultipleRanges
) {
1094 m_endTransactionAnimationHint
= NoAnimation
;
1097 updateSiblingsInformation();
1100 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1101 // In case if items of the same group have been inserted before an item that
1102 // currently represents the first item of the group, the group header of
1103 // this item must be removed.
1104 updateVisibleGroupHeaders();
1107 if (useAlternateBackgrounds()) {
1108 updateAlternateBackgrounds();
1112 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1114 if (m_itemSize
.isEmpty()) {
1115 // Don't pass the item-range: The preferred column-widths of
1116 // all items must be adjusted when removing items.
1117 updatePreferredColumnWidths();
1120 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1121 if (hasMultipleRanges
) {
1125 m_layouter
->markAsDirty();
1127 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1129 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1130 const KItemRange
& range
= itemRanges
[i
];
1131 const int index
= range
.index
;
1132 const int count
= range
.count
;
1133 if (index
< 0 || count
<= 0) {
1134 qCWarning(DolphinDebug
) << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1138 const int firstRemovedIndex
= index
;
1139 const int lastRemovedIndex
= index
+ count
- 1;
1141 // Remember which items have to be moved because they are behind the removed range.
1142 QVector
<int> itemsToMove
;
1144 // Remove all KItemListWidget instances that got deleted
1145 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1146 const int i
= widget
->index();
1147 if (i
< firstRemovedIndex
) {
1149 } else if (i
> lastRemovedIndex
) {
1150 itemsToMove
.append(i
);
1154 m_animation
->stop(widget
);
1155 // Stopping the animation might lead to recycling the widget if
1156 // it is invisible (see slotAnimationFinished()).
1157 // Check again whether it is still visible:
1158 if (!m_visibleItems
.contains(i
)) {
1162 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1163 // Remove the widget without animation
1164 recycleWidget(widget
);
1166 // Animate the removing of the items. Special case: When removing an item there
1167 // is no valid model index available anymore. For the
1168 // remove-animation the item gets removed from m_visibleItems but the widget
1169 // will stay alive until the animation has been finished and will
1170 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1171 m_visibleItems
.remove(i
);
1172 widget
->setIndex(-1);
1173 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1177 // Update the indexes of all KItemListWidget instances that are located
1178 // after the deleted items. It is important to update them in ascending
1179 // order to prevent overlaps when setting the new index.
1180 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1181 foreach (int i
, itemsToMove
) {
1182 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1184 const int newIndex
= i
- count
;
1185 if (hasMultipleRanges
) {
1186 setWidgetIndex(widget
, newIndex
);
1188 // Try to animate the moving of the item
1189 moveWidgetToIndex(widget
, newIndex
);
1193 if (!hasMultipleRanges
) {
1194 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1195 // assumes an updated geometry. If items are removed during an active transaction,
1196 // the transaction will be temporary deactivated so that doLayout() triggers a
1197 // geometry update if necessary.
1198 const int activeTransactions
= m_activeTransactions
;
1199 m_activeTransactions
= 0;
1200 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1201 m_activeTransactions
= activeTransactions
;
1202 updateSiblingsInformation();
1207 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1210 if (hasMultipleRanges
) {
1211 m_endTransactionAnimationHint
= NoAnimation
;
1213 updateSiblingsInformation();
1216 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1217 // In case if the first item of a group has been removed, the group header
1218 // must be applied to the next visible item.
1219 updateVisibleGroupHeaders();
1222 if (useAlternateBackgrounds()) {
1223 updateAlternateBackgrounds();
1227 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1229 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1230 m_layouter
->markAsDirty();
1233 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1236 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1237 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1239 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1240 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1242 updateWidgetProperties(widget
, index
);
1243 initializeItemListWidget(widget
);
1247 doLayout(NoAnimation
);
1248 updateSiblingsInformation();
1251 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1252 const QSet
<QByteArray
>& roles
)
1254 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1255 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1256 updatePreferredColumnWidths(itemRanges
);
1259 foreach (const KItemRange
& itemRange
, itemRanges
) {
1260 const int index
= itemRange
.index
;
1261 const int count
= itemRange
.count
;
1263 if (updateSizeHints
) {
1264 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1265 m_layouter
->markAsDirty();
1267 if (!m_layoutTimer
->isActive()) {
1268 m_layoutTimer
->start();
1272 // Apply the changed roles to the visible item-widgets
1273 const int lastIndex
= index
+ count
- 1;
1274 for (int i
= index
; i
<= lastIndex
; ++i
) {
1275 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1277 widget
->setData(m_model
->data(i
), roles
);
1281 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1282 // The sort-role has been changed which might result
1283 // in modified group headers
1284 updateVisibleGroupHeaders();
1285 doLayout(NoAnimation
);
1288 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1289 ev
.setFirstRow(itemRange
.index
);
1290 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1291 QAccessible::updateAccessibility(&ev
);
1295 void KItemListView::slotGroupsChanged()
1297 updateVisibleGroupHeaders();
1298 doLayout(NoAnimation
);
1299 updateSiblingsInformation();
1302 void KItemListView::slotGroupedSortingChanged(bool current
)
1304 m_grouped
= current
;
1305 m_layouter
->markAsDirty();
1308 updateGroupHeaderHeight();
1310 // Clear all visible headers. Note that the QHashIterator takes a copy of
1311 // m_visibleGroups. Therefore, it remains valid even if items are removed
1312 // from m_visibleGroups in recycleGroupHeaderForWidget().
1313 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1314 while (it
.hasNext()) {
1316 recycleGroupHeaderForWidget(it
.key());
1318 Q_ASSERT(m_visibleGroups
.isEmpty());
1321 if (useAlternateBackgrounds()) {
1322 // Changing the group mode requires to update the alternate backgrounds
1323 // as with the enabled group mode the altering is done on base of the first
1325 updateAlternateBackgrounds();
1327 updateSiblingsInformation();
1328 doLayout(NoAnimation
);
1331 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1336 updateVisibleGroupHeaders();
1337 doLayout(NoAnimation
);
1341 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1346 updateVisibleGroupHeaders();
1347 doLayout(NoAnimation
);
1351 void KItemListView::slotCurrentChanged(int current
, int previous
)
1355 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1356 // always the selected item. It is not necessary to highlight the current item then.
1357 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1358 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1359 if (previousWidget
) {
1360 previousWidget
->setCurrent(false);
1363 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1364 if (currentWidget
) {
1365 currentWidget
->setCurrent(true);
1369 QAccessibleEvent
ev(this, QAccessible::Focus
);
1370 ev
.setChild(current
);
1371 QAccessible::updateAccessibility(&ev
);
1374 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1378 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1379 while (it
.hasNext()) {
1381 const int index
= it
.key();
1382 KItemListWidget
* widget
= it
.value();
1383 widget
->setSelected(current
.contains(index
));
1387 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1388 KItemListViewAnimation::AnimationType type
)
1390 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1391 Q_ASSERT(itemListWidget
);
1394 case KItemListViewAnimation::DeleteAnimation
: {
1395 // As we recycle the widget in this case it is important to assure that no
1396 // other animation has been started. This is a convention in KItemListView and
1397 // not a requirement defined by KItemListViewAnimation.
1398 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1400 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1401 // by m_visibleWidgets and must be deleted manually after the animation has
1403 recycleGroupHeaderForWidget(itemListWidget
);
1404 widgetCreator()->recycle(itemListWidget
);
1408 case KItemListViewAnimation::CreateAnimation
:
1409 case KItemListViewAnimation::MovingAnimation
:
1410 case KItemListViewAnimation::ResizeAnimation
: {
1411 const int index
= itemListWidget
->index();
1412 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1413 (index
> m_layouter
->lastVisibleIndex());
1414 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1415 recycleWidget(itemListWidget
);
1424 void KItemListView::slotLayoutTimerFinished()
1426 m_layouter
->setSize(geometry().size());
1427 doLayout(Animation
);
1430 void KItemListView::slotRubberBandPosChanged()
1435 void KItemListView::slotRubberBandActivationChanged(bool active
)
1438 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1439 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1440 m_skipAutoScrollForRubberBand
= true;
1442 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1443 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1444 m_skipAutoScrollForRubberBand
= false;
1450 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1452 qreal previousWidth
)
1455 Q_UNUSED(currentWidth
);
1456 Q_UNUSED(previousWidth
);
1458 m_headerWidget
->setAutomaticColumnResizing(false);
1459 applyColumnWidthsFromHeader();
1460 doLayout(NoAnimation
);
1463 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1467 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1469 const QList
<QByteArray
> previous
= m_visibleRoles
;
1471 QList
<QByteArray
> current
= m_visibleRoles
;
1472 current
.removeAt(previousIndex
);
1473 current
.insert(currentIndex
, role
);
1475 setVisibleRoles(current
);
1477 emit
visibleRolesChanged(current
, previous
);
1480 void KItemListView::triggerAutoScrolling()
1482 if (!m_autoScrollTimer
) {
1487 int visibleSize
= 0;
1488 if (scrollOrientation() == Qt::Vertical
) {
1489 pos
= m_mousePos
.y();
1490 visibleSize
= size().height();
1492 pos
= m_mousePos
.x();
1493 visibleSize
= size().width();
1496 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1497 m_autoScrollIncrement
= 0;
1500 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1501 if (m_autoScrollIncrement
== 0) {
1502 // The mouse position is not above an autoscroll margin (the autoscroll timer
1503 // will be restarted in mouseMoveEvent())
1504 m_autoScrollTimer
->stop();
1508 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1509 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1510 // if the direction of the rubberband is similar to the autoscroll direction. This
1511 // prevents that starting to create a rubberband within the autoscroll margins starts
1512 // an autoscrolling.
1514 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1515 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1516 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1517 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1518 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1519 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1520 // been moved up although the autoscroll direction might be down)
1521 m_autoScrollTimer
->stop();
1526 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1527 // the autoscrolling may not get skipped anymore until a new rubberband is created
1528 m_skipAutoScrollForRubberBand
= false;
1530 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1531 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1532 setScrollOffset(newScrollOffset
);
1534 // Trigger the autoscroll timer which will periodically call
1535 // triggerAutoScrolling()
1536 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1539 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1541 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1543 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1544 Q_ASSERT(groupHeader
);
1545 updateGroupHeaderLayout(widget
);
1548 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1550 disconnectRoleEditingSignals(index
);
1552 emit
roleEditingCanceled(index
, role
, value
);
1553 m_editingRole
= false;
1556 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1558 disconnectRoleEditingSignals(index
);
1560 emit
roleEditingFinished(index
, role
, value
);
1561 m_editingRole
= false;
1564 void KItemListView::setController(KItemListController
* controller
)
1566 if (m_controller
!= controller
) {
1567 KItemListController
* previous
= m_controller
;
1569 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1570 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1571 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1574 m_controller
= controller
;
1577 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1578 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1579 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1582 onControllerChanged(controller
, previous
);
1586 void KItemListView::setModel(KItemModelBase
* model
)
1588 if (m_model
== model
) {
1592 KItemModelBase
* previous
= m_model
;
1595 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1596 this, &KItemListView::slotItemsChanged
);
1597 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1598 this, &KItemListView::slotItemsInserted
);
1599 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1600 this, &KItemListView::slotItemsRemoved
);
1601 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1602 this, &KItemListView::slotItemsMoved
);
1603 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1604 this, &KItemListView::slotGroupsChanged
);
1605 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1606 this, &KItemListView::slotGroupedSortingChanged
);
1607 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1608 this, &KItemListView::slotSortOrderChanged
);
1609 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1610 this, &KItemListView::slotSortRoleChanged
);
1612 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1616 m_layouter
->setModel(model
);
1617 m_grouped
= model
->groupedSorting();
1620 connect(m_model
, &KItemModelBase::itemsChanged
,
1621 this, &KItemListView::slotItemsChanged
);
1622 connect(m_model
, &KItemModelBase::itemsInserted
,
1623 this, &KItemListView::slotItemsInserted
);
1624 connect(m_model
, &KItemModelBase::itemsRemoved
,
1625 this, &KItemListView::slotItemsRemoved
);
1626 connect(m_model
, &KItemModelBase::itemsMoved
,
1627 this, &KItemListView::slotItemsMoved
);
1628 connect(m_model
, &KItemModelBase::groupsChanged
,
1629 this, &KItemListView::slotGroupsChanged
);
1630 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1631 this, &KItemListView::slotGroupedSortingChanged
);
1632 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1633 this, &KItemListView::slotSortOrderChanged
);
1634 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1635 this, &KItemListView::slotSortRoleChanged
);
1637 const int itemCount
= m_model
->count();
1638 if (itemCount
> 0) {
1639 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1643 onModelChanged(model
, previous
);
1646 KItemListRubberBand
* KItemListView::rubberBand() const
1648 return m_rubberBand
;
1651 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1653 if (m_layoutTimer
->isActive()) {
1654 m_layoutTimer
->stop();
1657 if (m_activeTransactions
> 0) {
1658 if (hint
== NoAnimation
) {
1659 // As soon as at least one property change should be done without animation,
1660 // the whole transaction will be marked as not animated.
1661 m_endTransactionAnimationHint
= NoAnimation
;
1666 if (!m_model
|| m_model
->count() < 0) {
1670 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1671 if (firstVisibleIndex
< 0) {
1672 emitOffsetChanges();
1676 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1677 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1678 // is still shown if the maximum offset got decreased.
1679 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1680 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1681 if (scrollOffset() > maxOffsetToShowFullRange
) {
1682 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1683 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1686 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1688 int firstSibblingIndex
= -1;
1689 int lastSibblingIndex
= -1;
1690 const bool supportsExpanding
= supportsItemExpanding();
1692 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1694 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1695 // instances from invisible items are reused. If no reusable items are
1696 // found then new KItemListWidget instances get created.
1697 const bool animate
= (hint
== Animation
);
1698 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1699 bool applyNewPos
= true;
1700 bool wasHidden
= false;
1702 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1703 const QPointF newPos
= itemBounds
.topLeft();
1704 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1707 if (!reusableItems
.isEmpty()) {
1708 // Reuse a KItemListWidget instance from an invisible item
1709 const int oldIndex
= reusableItems
.takeLast();
1710 widget
= m_visibleItems
.value(oldIndex
);
1711 setWidgetIndex(widget
, i
);
1712 updateWidgetProperties(widget
, i
);
1713 initializeItemListWidget(widget
);
1715 // No reusable KItemListWidget instance is available, create a new one
1716 widget
= createWidget(i
);
1718 widget
->resize(itemBounds
.size());
1720 if (animate
&& changedCount
< 0) {
1721 // Items have been deleted.
1722 if (i
>= changedIndex
) {
1723 // The item is located behind the removed range. Move the
1724 // created item to the imaginary old position outside the
1725 // view. It will get animated to the new position later.
1726 const int previousIndex
= i
- changedCount
;
1727 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1728 if (itemRect
.isEmpty()) {
1729 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1730 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1731 widget
->setPos(invisibleOldPos
);
1733 widget
->setPos(itemRect
.topLeft());
1735 applyNewPos
= false;
1739 if (supportsExpanding
&& changedCount
== 0) {
1740 if (firstSibblingIndex
< 0) {
1741 firstSibblingIndex
= i
;
1743 lastSibblingIndex
= i
;
1748 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1749 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1750 applyNewPos
= false;
1753 const bool itemsRemoved
= (changedCount
< 0);
1754 const bool itemsInserted
= (changedCount
> 0);
1755 if (itemsRemoved
&& (i
>= changedIndex
)) {
1756 // The item is located after the removed items. Animate the moving of the position.
1757 applyNewPos
= !moveWidget(widget
, newPos
);
1758 } else if (itemsInserted
&& i
>= changedIndex
) {
1759 // The item is located after the first inserted item
1760 if (i
<= changedIndex
+ changedCount
- 1) {
1761 // The item is an inserted item. Animate the appearing of the item.
1762 // For performance reasons no animation is done when changedCount is equal
1763 // to all available items.
1764 if (changedCount
< m_model
->count()) {
1765 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1767 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1768 // The item was already there before, so animate the moving of the position.
1769 // No moving animation is done if the item is animated by a create animation: This
1770 // prevents a "move animation mess" when inserting several ranges in parallel.
1771 applyNewPos
= !moveWidget(widget
, newPos
);
1773 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1774 // The size of the view might have been changed. Animate the moving of the position.
1775 applyNewPos
= !moveWidget(widget
, newPos
);
1778 m_animation
->stop(widget
);
1782 widget
->setPos(newPos
);
1785 Q_ASSERT(widget
->index() == i
);
1786 widget
->setVisible(true);
1788 if (widget
->size() != itemBounds
.size()) {
1789 // Resize the widget for the item to the changed size.
1791 // If a dynamic item size is used then no animation is done in the direction
1792 // of the dynamic size.
1793 if (m_itemSize
.width() <= 0) {
1794 // The width is dynamic, apply the new width without animation.
1795 widget
->resize(itemBounds
.width(), widget
->size().height());
1796 } else if (m_itemSize
.height() <= 0) {
1797 // The height is dynamic, apply the new height without animation.
1798 widget
->resize(widget
->size().width(), itemBounds
.height());
1800 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1802 widget
->resize(itemBounds
.size());
1806 // Updating the cell-information must be done as last step: The decision whether the
1807 // moving-animation should be started at all is based on the previous cell-information.
1808 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1809 m_visibleCells
.insert(i
, cell
);
1812 // Delete invisible KItemListWidget instances that have not been reused
1813 foreach (int index
, reusableItems
) {
1814 recycleWidget(m_visibleItems
.value(index
));
1817 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1818 Q_ASSERT(lastSibblingIndex
>= 0);
1819 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1823 // Update the layout of all visible group headers
1824 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1825 while (it
.hasNext()) {
1827 updateGroupHeaderLayout(it
.key());
1831 emitOffsetChanges();
1834 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1835 int lastVisibleIndex
,
1836 LayoutAnimationHint hint
)
1838 // Determine all items that are completely invisible and might be
1839 // reused for items that just got (at least partly) visible. If the
1840 // animation hint is set to 'Animation' items that do e.g. an animated
1841 // moving of their position are not marked as invisible: This assures
1842 // that a scrolling inside the view can be done without breaking an animation.
1846 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1847 while (it
.hasNext()) {
1850 KItemListWidget
* widget
= it
.value();
1851 const int index
= widget
->index();
1852 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1855 if (m_animation
->isStarted(widget
)) {
1856 if (hint
== NoAnimation
) {
1857 // Stopping the animation will call KItemListView::slotAnimationFinished()
1858 // and the widget will be recycled if necessary there.
1859 m_animation
->stop(widget
);
1862 widget
->setVisible(false);
1863 items
.append(index
);
1866 recycleGroupHeaderForWidget(widget
);
1875 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1877 if (widget
->pos() == newPos
) {
1881 bool startMovingAnim
= false;
1883 if (m_itemSize
.isEmpty()) {
1884 // The items are not aligned in a grid but either as columns or rows.
1885 startMovingAnim
= true;
1887 // When having a grid the moving-animation should only be started, if it is done within
1888 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1889 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1890 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1891 const int index
= widget
->index();
1892 const Cell cell
= m_visibleCells
.value(index
);
1893 if (cell
.column
>= 0 && cell
.row
>= 0) {
1894 if (scrollOrientation() == Qt::Vertical
) {
1895 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1897 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1902 if (startMovingAnim
) {
1903 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1907 m_animation
->stop(widget
);
1908 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1912 void KItemListView::emitOffsetChanges()
1914 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1915 if (m_oldScrollOffset
!= newScrollOffset
) {
1916 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1917 m_oldScrollOffset
= newScrollOffset
;
1920 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1921 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1922 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1923 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1926 const qreal newItemOffset
= m_layouter
->itemOffset();
1927 if (m_oldItemOffset
!= newItemOffset
) {
1928 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1929 m_oldItemOffset
= newItemOffset
;
1932 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1933 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1934 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1935 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1939 KItemListWidget
* KItemListView::createWidget(int index
)
1941 KItemListWidget
* widget
= widgetCreator()->create(this);
1942 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1944 m_visibleItems
.insert(index
, widget
);
1945 m_visibleCells
.insert(index
, Cell());
1946 updateWidgetProperties(widget
, index
);
1947 initializeItemListWidget(widget
);
1951 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1954 recycleGroupHeaderForWidget(widget
);
1957 const int index
= widget
->index();
1958 m_visibleItems
.remove(index
);
1959 m_visibleCells
.remove(index
);
1961 widgetCreator()->recycle(widget
);
1964 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1966 const int oldIndex
= widget
->index();
1967 m_visibleItems
.remove(oldIndex
);
1968 m_visibleCells
.remove(oldIndex
);
1970 m_visibleItems
.insert(index
, widget
);
1971 m_visibleCells
.insert(index
, Cell());
1973 widget
->setIndex(index
);
1976 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1978 const int oldIndex
= widget
->index();
1979 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1981 setWidgetIndex(widget
, index
);
1983 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1984 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1985 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1986 (!vertical
&& oldCell
.column
== newCell
.column
);
1988 m_visibleCells
.insert(index
, newCell
);
1992 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1995 case LayouterSize
: m_layouter
->setSize(size
); break;
1996 case ItemSize
: m_layouter
->setItemSize(size
); break;
2001 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
2003 widget
->setVisibleRoles(m_visibleRoles
);
2004 updateWidgetColumnWidths(widget
);
2005 widget
->setStyleOption(m_styleOption
);
2007 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
2009 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2010 // always the selected item. It is not necessary to highlight the current item then.
2011 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
2012 widget
->setCurrent(index
== selectionManager
->currentItem());
2014 widget
->setSelected(selectionManager
->isSelected(index
));
2015 widget
->setHovered(false);
2016 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
2017 widget
->setIndex(index
);
2018 widget
->setData(m_model
->data(index
));
2019 widget
->setSiblingsInformation(QBitArray());
2020 updateAlternateBackgroundForWidget(widget
);
2023 updateGroupHeaderForWidget(widget
);
2027 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2029 Q_ASSERT(m_grouped
);
2031 const int index
= widget
->index();
2032 if (!m_layouter
->isFirstGroupItem(index
)) {
2033 // The widget does not represent the first item of a group
2034 // and hence requires no header
2035 recycleGroupHeaderForWidget(widget
);
2039 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2040 if (groups
.isEmpty() || !groupHeaderCreator()) {
2044 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2046 groupHeader
= groupHeaderCreator()->create(this);
2047 groupHeader
->setParentItem(widget
);
2048 m_visibleGroups
.insert(widget
, groupHeader
);
2049 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2051 Q_ASSERT(groupHeader
->parentItem() == widget
);
2053 const int groupIndex
= groupIndexForItem(index
);
2054 Q_ASSERT(groupIndex
>= 0);
2055 groupHeader
->setData(groups
.at(groupIndex
).second
);
2056 groupHeader
->setRole(model()->sortRole());
2057 groupHeader
->setStyleOption(m_styleOption
);
2058 groupHeader
->setScrollOrientation(scrollOrientation());
2059 groupHeader
->setItemIndex(index
);
2061 groupHeader
->show();
2064 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2066 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2067 Q_ASSERT(groupHeader
);
2069 const int index
= widget
->index();
2070 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2071 const QRectF itemRect
= m_layouter
->itemRect(index
);
2073 // The group-header is a child of the itemlist widget. Translate the
2074 // group header position to the relative position.
2075 if (scrollOrientation() == Qt::Vertical
) {
2076 // In the vertical scroll orientation the group header should always span
2077 // the whole width no matter which temporary position the parent widget
2078 // has. In this case the x-position and width will be adjusted manually.
2079 const qreal x
= -widget
->x() - itemOffset();
2080 const qreal width
= maximumItemOffset();
2081 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2082 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2084 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2085 groupHeader
->resize(groupHeaderRect
.size());
2089 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2091 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2093 header
->setParentItem(0);
2094 groupHeaderCreator()->recycle(header
);
2095 m_visibleGroups
.remove(widget
);
2096 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2100 void KItemListView::updateVisibleGroupHeaders()
2102 Q_ASSERT(m_grouped
);
2103 m_layouter
->markAsDirty();
2105 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2106 while (it
.hasNext()) {
2108 updateGroupHeaderForWidget(it
.value());
2112 int KItemListView::groupIndexForItem(int index
) const
2114 Q_ASSERT(m_grouped
);
2116 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2117 if (groups
.isEmpty()) {
2122 int max
= groups
.count() - 1;
2125 mid
= (min
+ max
) / 2;
2126 if (index
> groups
[mid
].first
) {
2131 } while (groups
[mid
].first
!= index
&& min
<= max
);
2134 while (groups
[mid
].first
> index
&& mid
> 0) {
2142 void KItemListView::updateAlternateBackgrounds()
2144 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2145 while (it
.hasNext()) {
2147 updateAlternateBackgroundForWidget(it
.value());
2151 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2153 bool enabled
= useAlternateBackgrounds();
2155 const int index
= widget
->index();
2156 enabled
= (index
& 0x1) > 0;
2158 const int groupIndex
= groupIndexForItem(index
);
2159 if (groupIndex
>= 0) {
2160 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2161 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2162 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2163 enabled
= (relativeIndex
& 0x1) > 0;
2167 widget
->setAlternateBackground(enabled
);
2170 bool KItemListView::useAlternateBackgrounds() const
2172 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2175 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2177 QElapsedTimer timer
;
2180 QHash
<QByteArray
, qreal
> widths
;
2182 // Calculate the minimum width for each column that is required
2183 // to show the headline unclipped.
2184 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2185 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2186 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2187 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2188 const QString headerText
= m_model
->roleDescription(visibleRole
);
2189 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2190 widths
.insert(visibleRole
, headerWidth
);
2193 // Calculate the preferred column withs for each item and ignore values
2194 // smaller than the width for showing the headline unclipped.
2195 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2196 int calculatedItemCount
= 0;
2197 bool maxTimeExceeded
= false;
2198 foreach (const KItemRange
& itemRange
, itemRanges
) {
2199 const int startIndex
= itemRange
.index
;
2200 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2202 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2203 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2204 qreal maxWidth
= widths
.value(visibleRole
, 0);
2205 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2206 maxWidth
= qMax(width
, maxWidth
);
2207 widths
.insert(visibleRole
, maxWidth
);
2210 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2211 // When having several thousands of items calculating the sizes can get
2212 // very expensive. We accept a possibly too small role-size in favour
2213 // of having no blocking user interface.
2214 maxTimeExceeded
= true;
2217 ++calculatedItemCount
;
2219 if (maxTimeExceeded
) {
2227 void KItemListView::applyColumnWidthsFromHeader()
2229 // Apply the new size to the layouter
2230 const qreal requiredWidth
= columnWidthsSum();
2231 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2232 m_itemSize
.height());
2233 m_layouter
->setItemSize(dynamicItemSize
);
2235 // Update the role sizes for all visible widgets
2236 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2237 while (it
.hasNext()) {
2239 updateWidgetColumnWidths(it
.value());
2243 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2245 foreach (const QByteArray
& role
, m_visibleRoles
) {
2246 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2250 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2252 Q_ASSERT(m_itemSize
.isEmpty());
2253 const int itemCount
= m_model
->count();
2254 int rangesItemCount
= 0;
2255 foreach (const KItemRange
& range
, itemRanges
) {
2256 rangesItemCount
+= range
.count
;
2259 if (itemCount
== rangesItemCount
) {
2260 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2261 foreach (const QByteArray
& role
, m_visibleRoles
) {
2262 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2265 // Only a sub range of the roles need to be determined.
2266 // The chances are good that the widths of the sub ranges
2267 // already fit into the available widths and hence no
2268 // expensive update might be required.
2269 bool changed
= false;
2271 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2272 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2273 while (it
.hasNext()) {
2275 const QByteArray
& role
= it
.key();
2276 const qreal updatedWidth
= it
.value();
2277 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2278 if (updatedWidth
> currentWidth
) {
2279 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2285 // All the updated sizes are smaller than the current sizes and no change
2286 // of the stretched roles-widths is required
2291 if (m_headerWidget
->automaticColumnResizing()) {
2292 applyAutomaticColumnWidths();
2296 void KItemListView::updatePreferredColumnWidths()
2299 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2303 void KItemListView::applyAutomaticColumnWidths()
2305 Q_ASSERT(m_itemSize
.isEmpty());
2306 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2307 if (m_visibleRoles
.isEmpty()) {
2311 // Calculate the maximum size of an item by considering the
2312 // visible role sizes and apply them to the layouter. If the
2313 // size does not use the available view-size the size of the
2314 // first role will get stretched.
2316 foreach (const QByteArray
& role
, m_visibleRoles
) {
2317 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2318 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2321 const QByteArray firstRole
= m_visibleRoles
.first();
2322 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2323 QSizeF dynamicItemSize
= m_itemSize
;
2325 qreal requiredWidth
= columnWidthsSum();
2326 const qreal availableWidth
= size().width();
2327 if (requiredWidth
< availableWidth
) {
2328 // Stretch the first column to use the whole remaining width
2329 firstColumnWidth
+= availableWidth
- requiredWidth
;
2330 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2331 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2332 // Shrink the first column to be able to show as much other
2333 // columns as possible
2334 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2336 // TODO: A proper calculation of the minimum width depends on the implementation
2337 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2339 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2340 if (shrinkedFirstColumnWidth
< minWidth
) {
2341 shrinkedFirstColumnWidth
= minWidth
;
2344 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2345 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2348 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2350 m_layouter
->setItemSize(dynamicItemSize
);
2352 // Update the role sizes for all visible widgets
2353 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2354 while (it
.hasNext()) {
2356 updateWidgetColumnWidths(it
.value());
2360 qreal
KItemListView::columnWidthsSum() const
2362 qreal widthsSum
= 0;
2363 foreach (const QByteArray
& role
, m_visibleRoles
) {
2364 widthsSum
+= m_headerWidget
->columnWidth(role
);
2369 QRectF
KItemListView::headerBoundaries() const
2371 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2374 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2375 const QSizeF
& newItemSize
,
2376 const QSizeF
& newItemMargin
) const
2378 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2382 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2383 const qreal itemWidth
= m_layouter
->itemSize().width();
2384 if (itemWidth
> 0) {
2385 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2386 newItemSize
.width(),
2387 newItemMargin
.width());
2388 if (m_model
->count() > newColumnCount
) {
2389 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2391 m_layouter
->itemMargin().width());
2392 return oldColumnCount
!= newColumnCount
;
2396 const qreal itemHeight
= m_layouter
->itemSize().height();
2397 if (itemHeight
> 0) {
2398 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2399 newItemSize
.height(),
2400 newItemMargin
.height());
2401 if (m_model
->count() > newRowCount
) {
2402 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2404 m_layouter
->itemMargin().height());
2405 return oldRowCount
!= newRowCount
;
2413 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2415 if (m_itemSize
.isEmpty()) {
2416 // We have only columns or only rows, but no grid: An animation is usually
2417 // welcome when inserting or removing items.
2418 return !supportsItemExpanding();
2421 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2425 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2426 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2427 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2428 // Only animate if up to 2/3 of a row or column are inserted or removed
2429 return changedItemCount
<= maximum
* 2 / 3;
2433 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2435 const QSizeF oldSize
= m_layouter
->size();
2437 m_layouter
->setSize(size
);
2438 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2439 m_layouter
->setSize(oldSize
);
2441 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2442 : maxOffset
> size
.width();
2445 int KItemListView::showDropIndicator(const QPointF
& pos
)
2447 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2448 while (it
.hasNext()) {
2450 const KItemListWidget
* widget
= it
.value();
2452 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2453 const QRectF rect
= itemRect(widget
->index());
2454 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2455 if (m_model
->supportsDropping(widget
->index())) {
2456 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2457 const int gap
= qMax(qreal(4.0), qreal(0.3) * rect
.height());
2458 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2463 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2464 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2466 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2467 if (m_dropIndicator
!= draggingInsertIndicator
) {
2468 m_dropIndicator
= draggingInsertIndicator
;
2472 int index
= widget
->index();
2480 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2481 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2484 void KItemListView::hideDropIndicator()
2486 if (!m_dropIndicator
.isNull()) {
2487 m_dropIndicator
= QRectF();
2492 void KItemListView::updateGroupHeaderHeight()
2494 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2495 qreal groupHeaderMargin
= 0;
2497 if (scrollOrientation() == Qt::Horizontal
) {
2498 // The vertical margin above and below the header should be
2499 // equal to the horizontal margin, not the vertical margin
2500 // from m_styleOption.
2501 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2502 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2503 } else if (m_itemSize
.isEmpty()){
2504 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2505 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2507 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2508 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2510 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2511 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2513 updateVisibleGroupHeaders();
2516 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2518 if (!supportsItemExpanding() || !m_model
) {
2522 if (firstIndex
< 0 || lastIndex
< 0) {
2523 firstIndex
= m_layouter
->firstVisibleIndex();
2524 lastIndex
= m_layouter
->lastVisibleIndex();
2526 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2527 lastIndex
>= m_layouter
->firstVisibleIndex());
2528 if (!isRangeVisible
) {
2533 int previousParents
= 0;
2534 QBitArray previousSiblings
;
2536 // The rootIndex describes the first index where the siblings get
2537 // calculated from. For the calculation the upper most parent item
2538 // is required. For performance reasons it is checked first whether
2539 // the visible items before or after the current range already
2540 // contain a siblings information which can be used as base.
2541 int rootIndex
= firstIndex
;
2543 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2545 // There is no visible widget before the range, check whether there
2546 // is one after the range:
2547 widget
= m_visibleItems
.value(lastIndex
+ 1);
2549 // The sibling information of the widget may only be used if
2550 // all items of the range have the same number of parents.
2551 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2552 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2553 if (m_model
->expandedParentsCount(i
) != parents
) {
2562 // Performance optimization: Use the sibling information of the visible
2563 // widget beside the given range.
2564 previousSiblings
= widget
->siblingsInformation();
2565 if (previousSiblings
.isEmpty()) {
2568 previousParents
= previousSiblings
.count() - 1;
2569 previousSiblings
.truncate(previousParents
);
2571 // Potentially slow path: Go back to the upper most parent of firstIndex
2572 // to be able to calculate the initial value for the siblings.
2573 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2578 Q_ASSERT(previousParents
>= 0);
2579 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2580 // Update the parent-siblings in case if the current item represents
2581 // a child or an upper parent.
2582 const int currentParents
= m_model
->expandedParentsCount(i
);
2583 Q_ASSERT(currentParents
>= 0);
2584 if (previousParents
< currentParents
) {
2585 previousParents
= currentParents
;
2586 previousSiblings
.resize(currentParents
);
2587 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2588 } else if (previousParents
> currentParents
) {
2589 previousParents
= currentParents
;
2590 previousSiblings
.truncate(currentParents
);
2593 if (i
>= firstIndex
) {
2594 // The index represents a visible item. Apply the parent-siblings
2595 // and update the sibling of the current item.
2596 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2601 QBitArray siblings
= previousSiblings
;
2602 siblings
.resize(siblings
.count() + 1);
2603 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2605 widget
->setSiblingsInformation(siblings
);
2610 bool KItemListView::hasSiblingSuccessor(int index
) const
2612 bool hasSuccessor
= false;
2613 const int parentsCount
= m_model
->expandedParentsCount(index
);
2614 int successorIndex
= index
+ 1;
2616 // Search the next sibling
2617 const int itemCount
= m_model
->count();
2618 while (successorIndex
< itemCount
) {
2619 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2620 if (currentParentsCount
== parentsCount
) {
2621 hasSuccessor
= true;
2623 } else if (currentParentsCount
< parentsCount
) {
2629 if (m_grouped
&& hasSuccessor
) {
2630 // If the sibling is part of another group, don't mark it as
2631 // successor as the group header is between the sibling connections.
2632 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2633 if (m_layouter
->isFirstGroupItem(i
)) {
2634 hasSuccessor
= false;
2640 return hasSuccessor
;
2643 void KItemListView::disconnectRoleEditingSignals(int index
)
2645 KStandardItemListWidget
* widget
= qobject_cast
<KStandardItemListWidget
*>(m_visibleItems
.value(index
));
2650 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2651 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2652 disconnect(this, &KItemListView::scrollOffsetChanged
, widget
, nullptr);
2655 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2659 const int minSpeed
= 4;
2660 const int maxSpeed
= 128;
2661 const int speedLimiter
= 96;
2662 const int autoScrollBorder
= 64;
2664 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2665 // This assures that the autoscrolling speed grows gradually.
2666 const int incLimiter
= 1;
2668 if (pos
< autoScrollBorder
) {
2669 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2670 inc
= qMax(inc
, -maxSpeed
);
2671 inc
= qMax(inc
, oldInc
- incLimiter
);
2672 } else if (pos
> range
- autoScrollBorder
) {
2673 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2674 inc
= qMin(inc
, maxSpeed
);
2675 inc
= qMin(inc
, oldInc
+ incLimiter
);
2681 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2683 const qreal availableSize
= size
- itemMargin
;
2684 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2690 KItemListCreatorBase::~KItemListCreatorBase()
2692 qDeleteAll(m_recycleableWidgets
);
2693 qDeleteAll(m_createdWidgets
);
2696 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2698 m_createdWidgets
.insert(widget
);
2701 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2703 Q_ASSERT(m_createdWidgets
.contains(widget
));
2704 m_createdWidgets
.remove(widget
);
2706 if (m_recycleableWidgets
.count() < 100) {
2707 m_recycleableWidgets
.append(widget
);
2708 widget
->setVisible(false);
2714 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2716 if (m_recycleableWidgets
.isEmpty()) {
2720 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2721 m_createdWidgets
.insert(widget
);
2725 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2729 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2731 widget
->setParentItem(0);
2732 widget
->setOpacity(1.0);
2733 pushRecycleableWidget(widget
);
2736 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2740 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2742 header
->setOpacity(1.0);
2743 pushRecycleableWidget(header
);