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"
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>
47 #include "kitemlistviewaccessible.h"
50 // Time in ms until reaching the autoscroll margin triggers
51 // an initial autoscrolling
52 const int InitialAutoScrollDelay
= 700;
54 // Delay in ms for triggering the next autoscroll
55 const int RepeatingAutoScrollDelay
= 1000 / 60;
58 #ifndef QT_NO_ACCESSIBILITY
59 QAccessibleInterface
* accessibleInterfaceFactory(const QString
& key
, QObject
* object
)
63 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
64 return new KItemListContainerAccessible(container
);
65 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
66 return new KItemListViewAccessible(view
);
73 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
74 QGraphicsWidget(parent
),
75 m_enabledSelectionToggles(false),
77 m_supportsItemExpanding(false),
79 m_activeTransactions(0),
80 m_endTransactionAnimationHint(Animation
),
86 m_groupHeaderCreator(0),
91 m_sizeHintResolver(0),
96 m_oldMaximumScrollOffset(0),
98 m_oldMaximumItemOffset(0),
99 m_skipAutoScrollForRubberBand(false),
102 m_autoScrollIncrement(0),
103 m_autoScrollTimer(0),
108 setAcceptHoverEvents(true);
110 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
112 m_layouter
= new KItemListViewLayouter(m_sizeHintResolver
, this);
114 m_animation
= new KItemListViewAnimation(this);
115 connect(m_animation
, &KItemListViewAnimation::finished
,
116 this, &KItemListView::slotAnimationFinished
);
118 m_layoutTimer
= new QTimer(this);
119 m_layoutTimer
->setInterval(300);
120 m_layoutTimer
->setSingleShot(true);
121 connect(m_layoutTimer
, &QTimer::timeout
, this, &KItemListView::slotLayoutTimerFinished
);
123 m_rubberBand
= new KItemListRubberBand(this);
124 connect(m_rubberBand
, &KItemListRubberBand::activationChanged
, this, &KItemListView::slotRubberBandActivationChanged
);
126 m_headerWidget
= new KItemListHeaderWidget(this);
127 m_headerWidget
->setVisible(false);
129 m_header
= new KItemListHeader(this);
131 #ifndef QT_NO_ACCESSIBILITY
132 QAccessible::installFactory(accessibleInterfaceFactory
);
137 KItemListView::~KItemListView()
139 // The group headers are children of the widgets created by
140 // widgetCreator(). So it is mandatory to delete the group headers
142 delete m_groupHeaderCreator
;
143 m_groupHeaderCreator
= 0;
145 delete m_widgetCreator
;
148 delete m_sizeHintResolver
;
149 m_sizeHintResolver
= 0;
152 void KItemListView::setScrollOffset(qreal offset
)
158 const qreal previousOffset
= m_layouter
->scrollOffset();
159 if (offset
== previousOffset
) {
163 m_layouter
->setScrollOffset(offset
);
164 m_animation
->setScrollOffset(offset
);
166 // Don't check whether the m_layoutTimer is active: Changing the
167 // scroll offset must always trigger a synchronous layout, otherwise
168 // the smooth-scrolling might get jerky.
169 doLayout(NoAnimation
);
170 onScrollOffsetChanged(offset
, previousOffset
);
173 qreal
KItemListView::scrollOffset() const
175 return m_layouter
->scrollOffset();
178 qreal
KItemListView::maximumScrollOffset() const
180 return m_layouter
->maximumScrollOffset();
183 void KItemListView::setItemOffset(qreal offset
)
185 if (m_layouter
->itemOffset() == offset
) {
189 m_layouter
->setItemOffset(offset
);
190 if (m_headerWidget
->isVisible()) {
191 m_headerWidget
->setOffset(offset
);
194 // Don't check whether the m_layoutTimer is active: Changing the
195 // item offset must always trigger a synchronous layout, otherwise
196 // the smooth-scrolling might get jerky.
197 doLayout(NoAnimation
);
200 qreal
KItemListView::itemOffset() const
202 return m_layouter
->itemOffset();
205 qreal
KItemListView::maximumItemOffset() const
207 return m_layouter
->maximumItemOffset();
210 int KItemListView::maximumVisibleItems() const
212 return m_layouter
->maximumVisibleItems();
215 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
217 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
218 m_visibleRoles
= roles
;
219 onVisibleRolesChanged(roles
, previousRoles
);
221 m_sizeHintResolver
->clearCache();
222 m_layouter
->markAsDirty();
224 if (m_itemSize
.isEmpty()) {
225 m_headerWidget
->setColumns(roles
);
226 updatePreferredColumnWidths();
227 if (!m_headerWidget
->automaticColumnResizing()) {
228 // The column-width of new roles are still 0. Apply the preferred
229 // column-width as default with.
230 foreach (const QByteArray
& role
, m_visibleRoles
) {
231 if (m_headerWidget
->columnWidth(role
) == 0) {
232 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
233 m_headerWidget
->setColumnWidth(role
, width
);
237 applyColumnWidthsFromHeader();
241 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
242 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
243 (roles
.count() <= 1 && previousRoles
.count() > 1));
245 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
246 while (it
.hasNext()) {
248 KItemListWidget
* widget
= it
.value();
249 widget
->setVisibleRoles(roles
);
250 if (alternateBackgroundsChanged
) {
251 updateAlternateBackgroundForWidget(widget
);
255 doLayout(NoAnimation
);
258 QList
<QByteArray
> KItemListView::visibleRoles() const
260 return m_visibleRoles
;
263 void KItemListView::setAutoScroll(bool enabled
)
265 if (enabled
&& !m_autoScrollTimer
) {
266 m_autoScrollTimer
= new QTimer(this);
267 m_autoScrollTimer
->setSingleShot(true);
268 connect(m_autoScrollTimer
, &QTimer::timeout
, this, &KItemListView::triggerAutoScrolling
);
269 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
270 } else if (!enabled
&& m_autoScrollTimer
) {
271 delete m_autoScrollTimer
;
272 m_autoScrollTimer
= 0;
276 bool KItemListView::autoScroll() const
278 return m_autoScrollTimer
!= 0;
281 void KItemListView::setEnabledSelectionToggles(bool enabled
)
283 if (m_enabledSelectionToggles
!= enabled
) {
284 m_enabledSelectionToggles
= enabled
;
286 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
287 while (it
.hasNext()) {
289 it
.value()->setEnabledSelectionToggle(enabled
);
294 bool KItemListView::enabledSelectionToggles() const
296 return m_enabledSelectionToggles
;
299 KItemListController
* KItemListView::controller() const
304 KItemModelBase
* KItemListView::model() const
309 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
311 if (m_widgetCreator
) {
312 delete m_widgetCreator
;
314 m_widgetCreator
= widgetCreator
;
317 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
319 if (!m_widgetCreator
) {
320 m_widgetCreator
= defaultWidgetCreator();
322 return m_widgetCreator
;
325 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
327 if (m_groupHeaderCreator
) {
328 delete m_groupHeaderCreator
;
330 m_groupHeaderCreator
= groupHeaderCreator
;
333 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
335 if (!m_groupHeaderCreator
) {
336 m_groupHeaderCreator
= defaultGroupHeaderCreator();
338 return m_groupHeaderCreator
;
341 QSizeF
KItemListView::itemSize() const
346 const KItemListStyleOption
& KItemListView::styleOption() const
348 return m_styleOption
;
351 void KItemListView::setGeometry(const QRectF
& rect
)
353 QGraphicsWidget::setGeometry(rect
);
359 const QSizeF newSize
= rect
.size();
360 if (m_itemSize
.isEmpty()) {
361 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
362 if (m_headerWidget
->automaticColumnResizing()) {
363 applyAutomaticColumnWidths();
365 const qreal requiredWidth
= columnWidthsSum();
366 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
367 m_itemSize
.height());
368 m_layouter
->setItemSize(dynamicItemSize
);
371 // Triggering a synchronous layout is fine from a performance point of view,
372 // as with dynamic item sizes no moving animation must be done.
373 m_layouter
->setSize(newSize
);
374 doLayout(NoAnimation
);
376 const bool animate
= !changesItemGridLayout(newSize
,
377 m_layouter
->itemSize(),
378 m_layouter
->itemMargin());
379 m_layouter
->setSize(newSize
);
382 // Trigger an asynchronous relayout with m_layoutTimer to prevent
383 // performance bottlenecks. If the timer is exceeded, an animated layout
384 // will be triggered.
385 if (!m_layoutTimer
->isActive()) {
386 m_layoutTimer
->start();
389 m_layoutTimer
->stop();
390 doLayout(NoAnimation
);
395 qreal
KItemListView::verticalPageStep() const
397 qreal headerHeight
= 0;
398 if (m_headerWidget
->isVisible()) {
399 headerHeight
= m_headerWidget
->size().height();
401 return size().height() - headerHeight
;
404 int KItemListView::itemAt(const QPointF
& pos
) const
406 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
407 while (it
.hasNext()) {
410 const KItemListWidget
* widget
= it
.value();
411 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
412 if (widget
->contains(mappedPos
)) {
420 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
422 if (!m_enabledSelectionToggles
) {
426 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
428 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
429 if (!selectionToggleRect
.isEmpty()) {
430 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
431 return selectionToggleRect
.contains(mappedPos
);
437 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
439 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
441 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
442 if (!expansionToggleRect
.isEmpty()) {
443 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
444 return expansionToggleRect
.contains(mappedPos
);
450 int KItemListView::firstVisibleIndex() const
452 return m_layouter
->firstVisibleIndex();
455 int KItemListView::lastVisibleIndex() const
457 return m_layouter
->lastVisibleIndex();
460 void KItemListView::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
462 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, this);
465 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
467 if (m_supportsItemExpanding
!= supportsExpanding
) {
468 m_supportsItemExpanding
= supportsExpanding
;
469 updateSiblingsInformation();
470 onSupportsItemExpandingChanged(supportsExpanding
);
474 bool KItemListView::supportsItemExpanding() const
476 return m_supportsItemExpanding
;
479 QRectF
KItemListView::itemRect(int index
) const
481 return m_layouter
->itemRect(index
);
484 QRectF
KItemListView::itemContextRect(int index
) const
488 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
490 contextRect
= widget
->iconRect() | widget
->textRect();
491 contextRect
.translate(itemRect(index
).topLeft());
497 void KItemListView::scrollToItem(int index
)
499 QRectF viewGeometry
= geometry();
500 if (m_headerWidget
->isVisible()) {
501 const qreal headerHeight
= m_headerWidget
->size().height();
502 viewGeometry
.adjust(0, headerHeight
, 0, 0);
504 QRectF currentRect
= itemRect(index
);
506 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
507 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
508 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
510 if (!viewGeometry
.contains(currentRect
)) {
511 qreal newOffset
= scrollOffset();
512 if (scrollOrientation() == Qt::Vertical
) {
513 if (currentRect
.top() < viewGeometry
.top()) {
514 newOffset
+= currentRect
.top() - viewGeometry
.top();
515 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
516 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
519 if (currentRect
.left() < viewGeometry
.left()) {
520 newOffset
+= currentRect
.left() - viewGeometry
.left();
521 } else if (currentRect
.right() > viewGeometry
.right()) {
522 newOffset
+= currentRect
.right() - viewGeometry
.right();
526 if (newOffset
!= scrollOffset()) {
527 emit
scrollTo(newOffset
);
532 void KItemListView::beginTransaction()
534 ++m_activeTransactions
;
535 if (m_activeTransactions
== 1) {
536 onTransactionBegin();
540 void KItemListView::endTransaction()
542 --m_activeTransactions
;
543 if (m_activeTransactions
< 0) {
544 m_activeTransactions
= 0;
545 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
548 if (m_activeTransactions
== 0) {
550 doLayout(m_endTransactionAnimationHint
);
551 m_endTransactionAnimationHint
= Animation
;
555 bool KItemListView::isTransactionActive() const
557 return m_activeTransactions
> 0;
560 void KItemListView::setHeaderVisible(bool visible
)
562 if (visible
&& !m_headerWidget
->isVisible()) {
563 QStyleOptionHeader option
;
564 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
567 m_headerWidget
->setPos(0, 0);
568 m_headerWidget
->resize(size().width(), headerSize
.height());
569 m_headerWidget
->setModel(m_model
);
570 m_headerWidget
->setColumns(m_visibleRoles
);
571 m_headerWidget
->setZValue(1);
573 connect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
574 this, &KItemListView::slotHeaderColumnWidthChanged
);
575 connect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
576 this, &KItemListView::slotHeaderColumnMoved
);
577 connect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
578 this, &KItemListView::sortOrderChanged
);
579 connect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
580 this, &KItemListView::sortRoleChanged
);
582 m_layouter
->setHeaderHeight(headerSize
.height());
583 m_headerWidget
->setVisible(true);
584 } else if (!visible
&& m_headerWidget
->isVisible()) {
585 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnWidthChanged
,
586 this, &KItemListView::slotHeaderColumnWidthChanged
);
587 disconnect(m_headerWidget
, &KItemListHeaderWidget::columnMoved
,
588 this, &KItemListView::slotHeaderColumnMoved
);
589 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortOrderChanged
,
590 this, &KItemListView::sortOrderChanged
);
591 disconnect(m_headerWidget
, &KItemListHeaderWidget::sortRoleChanged
,
592 this, &KItemListView::sortRoleChanged
);
594 m_layouter
->setHeaderHeight(0);
595 m_headerWidget
->setVisible(false);
599 bool KItemListView::isHeaderVisible() const
601 return m_headerWidget
->isVisible();
604 KItemListHeader
* KItemListView::header() const
609 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
613 if (indexes
.count() == 1) {
614 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
615 QGraphicsView
* graphicsView
= scene()->views()[0];
616 if (item
&& graphicsView
) {
617 pixmap
= item
->createDragPixmap(0, graphicsView
);
620 // TODO: Not implemented yet. Probably extend the interface
621 // from KItemListWidget::createDragPixmap() to return a pixmap
622 // that can be used for multiple indexes.
628 void KItemListView::editRole(int index
, const QByteArray
& role
)
630 KItemListWidget
* widget
= m_visibleItems
.value(index
);
631 if (!widget
|| m_editingRole
) {
635 m_editingRole
= true;
636 widget
->setEditedRole(role
);
638 connect(widget
, &KItemListWidget::roleEditingCanceled
,
639 this, &KItemListView::slotRoleEditingCanceled
);
640 connect(widget
, &KItemListWidget::roleEditingFinished
,
641 this, &KItemListView::slotRoleEditingFinished
);
644 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
646 QGraphicsWidget::paint(painter
, option
, widget
);
648 if (m_rubberBand
->isActive()) {
649 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
650 m_rubberBand
->endPosition()).normalized();
652 const QPointF topLeft
= rubberBandRect
.topLeft();
653 if (scrollOrientation() == Qt::Vertical
) {
654 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
656 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
659 QStyleOptionRubberBand opt
;
660 opt
.initFrom(widget
);
661 opt
.shape
= QRubberBand::Rectangle
;
663 opt
.rect
= rubberBandRect
.toRect();
664 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
667 if (!m_dropIndicator
.isEmpty()) {
668 const QRectF r
= m_dropIndicator
.toRect();
670 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
671 painter
->setPen(color
);
673 // TODO: The following implementation works only for a vertical scroll-orientation
674 // and assumes a height of the m_draggingInsertIndicator of 1.
675 Q_ASSERT(r
.height() == 1);
676 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
679 painter
->setPen(color
);
680 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
684 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
686 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
687 if (!scene()->views().isEmpty()) {
688 m_styleOption
.palette
= scene()->views().at(0)->palette();
691 return QGraphicsItem::itemChange(change
, value
);
694 void KItemListView::setItemSize(const QSizeF
& size
)
696 const QSizeF previousSize
= m_itemSize
;
697 if (size
== previousSize
) {
701 // Skip animations when the number of rows or columns
702 // are changed in the grid layout. Although the animation
703 // engine can handle this usecase, it looks obtrusive.
704 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
706 m_layouter
->itemMargin());
708 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
709 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
710 (!m_itemSize
.isEmpty() && size
.isEmpty()));
714 if (alternateBackgroundsChanged
) {
715 // For an empty item size alternate backgrounds are drawn if more than
716 // one role is shown. Assure that the backgrounds for visible items are
717 // updated when changing the size in this context.
718 updateAlternateBackgrounds();
721 if (size
.isEmpty()) {
722 if (m_headerWidget
->automaticColumnResizing()) {
723 updatePreferredColumnWidths();
725 // Only apply the changed height and respect the header widths
727 const qreal currentWidth
= m_layouter
->itemSize().width();
728 const QSizeF
newSize(currentWidth
, size
.height());
729 m_layouter
->setItemSize(newSize
);
732 m_layouter
->setItemSize(size
);
735 m_sizeHintResolver
->clearCache();
736 doLayout(animate
? Animation
: NoAnimation
);
737 onItemSizeChanged(size
, previousSize
);
740 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
742 const KItemListStyleOption previousOption
= m_styleOption
;
743 m_styleOption
= option
;
746 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
747 if (margin
!= m_layouter
->itemMargin()) {
748 // Skip animations when the number of rows or columns
749 // are changed in the grid layout. Although the animation
750 // engine can handle this usecase, it looks obtrusive.
751 animate
= !changesItemGridLayout(m_layouter
->size(),
752 m_layouter
->itemSize(),
754 m_layouter
->setItemMargin(margin
);
758 updateGroupHeaderHeight();
762 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
763 // Animating a change of the maximum text size just results in expensive
764 // temporary eliding and clipping operations and does not look good visually.
768 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
769 while (it
.hasNext()) {
771 it
.value()->setStyleOption(option
);
774 m_sizeHintResolver
->clearCache();
775 m_layouter
->markAsDirty();
776 doLayout(animate
? Animation
: NoAnimation
);
778 if (m_itemSize
.isEmpty()) {
779 updatePreferredColumnWidths();
782 onStyleOptionChanged(option
, previousOption
);
785 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
787 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
788 if (orientation
== previousOrientation
) {
792 m_layouter
->setScrollOrientation(orientation
);
793 m_animation
->setScrollOrientation(orientation
);
794 m_sizeHintResolver
->clearCache();
797 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
798 while (it
.hasNext()) {
800 it
.value()->setScrollOrientation(orientation
);
802 updateGroupHeaderHeight();
806 doLayout(NoAnimation
);
808 onScrollOrientationChanged(orientation
, previousOrientation
);
809 emit
scrollOrientationChanged(orientation
, previousOrientation
);
812 Qt::Orientation
KItemListView::scrollOrientation() const
814 return m_layouter
->scrollOrientation();
817 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
822 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
827 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
832 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
834 Q_UNUSED(changedRoles
);
838 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
844 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
850 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
856 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
862 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
868 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
874 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
880 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
882 Q_UNUSED(supportsExpanding
);
885 void KItemListView::onTransactionBegin()
889 void KItemListView::onTransactionEnd()
893 bool KItemListView::event(QEvent
* event
)
895 switch (event
->type()) {
896 case QEvent::PaletteChange
:
900 case QEvent::FontChange
:
905 // Forward all other events to the controller and handle them there
906 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
912 return QGraphicsWidget::event(event
);
915 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
917 m_mousePos
= transform().map(event
->pos());
921 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
923 QGraphicsWidget::mouseMoveEvent(event
);
925 m_mousePos
= transform().map(event
->pos());
926 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
927 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
931 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
933 event
->setAccepted(true);
937 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
)
939 QGraphicsWidget::dragMoveEvent(event
);
941 m_mousePos
= transform().map(event
->pos());
942 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
943 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
947 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
)
949 QGraphicsWidget::dragLeaveEvent(event
);
950 setAutoScroll(false);
953 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
955 QGraphicsWidget::dropEvent(event
);
956 setAutoScroll(false);
959 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
961 return m_visibleItems
.values();
964 void KItemListView::updateFont()
966 if (scene() && !scene()->views().isEmpty()) {
967 KItemListStyleOption option
= styleOption();
968 option
.font
= scene()->views().first()->font();
969 option
.fontMetrics
= QFontMetrics(option
.font
);
971 setStyleOption(option
);
975 void KItemListView::updatePalette()
977 if (scene() && !scene()->views().isEmpty()) {
978 KItemListStyleOption option
= styleOption();
979 option
.palette
= scene()->views().first()->palette();
981 setStyleOption(option
);
985 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
987 if (m_itemSize
.isEmpty()) {
988 updatePreferredColumnWidths(itemRanges
);
991 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
992 if (hasMultipleRanges
) {
996 m_layouter
->markAsDirty();
998 m_sizeHintResolver
->itemsInserted(itemRanges
);
1000 int previouslyInsertedCount
= 0;
1001 foreach (const KItemRange
& range
, itemRanges
) {
1002 // range.index is related to the model before anything has been inserted.
1003 // As in each loop the current item-range gets inserted the index must
1004 // be increased by the already previously inserted items.
1005 const int index
= range
.index
+ previouslyInsertedCount
;
1006 const int count
= range
.count
;
1007 if (index
< 0 || count
<= 0) {
1008 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1011 previouslyInsertedCount
+= count
;
1013 // Determine which visible items must be moved
1014 QList
<int> itemsToMove
;
1015 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1016 while (it
.hasNext()) {
1018 const int visibleItemIndex
= it
.key();
1019 if (visibleItemIndex
>= index
) {
1020 itemsToMove
.append(visibleItemIndex
);
1024 // Update the indexes of all KItemListWidget instances that are located
1025 // after the inserted items. It is important to adjust the indexes in the order
1026 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1028 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1029 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1031 const int newIndex
= widget
->index() + count
;
1032 if (hasMultipleRanges
) {
1033 setWidgetIndex(widget
, newIndex
);
1035 // Try to animate the moving of the item
1036 moveWidgetToIndex(widget
, newIndex
);
1040 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1041 // Check whether a scrollbar is required to show the inserted items. In this case
1042 // the size of the layouter will be decreased before calling doLayout(): This prevents
1043 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1044 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1045 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1046 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1047 if (decreaseLayouterSize
) {
1048 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1050 int scrollbarSpacing
= 0;
1051 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1052 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1055 QSizeF layouterSize
= m_layouter
->size();
1056 if (verticalScrollOrientation
) {
1057 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1059 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1061 m_layouter
->setSize(layouterSize
);
1065 if (!hasMultipleRanges
) {
1066 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1067 updateSiblingsInformation();
1072 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1075 if (hasMultipleRanges
) {
1076 m_endTransactionAnimationHint
= NoAnimation
;
1079 updateSiblingsInformation();
1082 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1083 // In case if items of the same group have been inserted before an item that
1084 // currently represents the first item of the group, the group header of
1085 // this item must be removed.
1086 updateVisibleGroupHeaders();
1089 if (useAlternateBackgrounds()) {
1090 updateAlternateBackgrounds();
1094 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1096 if (m_itemSize
.isEmpty()) {
1097 // Don't pass the item-range: The preferred column-widths of
1098 // all items must be adjusted when removing items.
1099 updatePreferredColumnWidths();
1102 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1103 if (hasMultipleRanges
) {
1107 m_layouter
->markAsDirty();
1109 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1111 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1112 const KItemRange
& range
= itemRanges
[i
];
1113 const int index
= range
.index
;
1114 const int count
= range
.count
;
1115 if (index
< 0 || count
<= 0) {
1116 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1120 const int firstRemovedIndex
= index
;
1121 const int lastRemovedIndex
= index
+ count
- 1;
1123 // Remeber which items have to be moved because they are behind the removed range.
1124 QVector
<int> itemsToMove
;
1126 // Remove all KItemListWidget instances that got deleted
1127 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1128 const int i
= widget
->index();
1129 if (i
< firstRemovedIndex
) {
1131 } else if (i
> lastRemovedIndex
) {
1132 itemsToMove
.append(i
);
1136 m_animation
->stop(widget
);
1137 // Stopping the animation might lead to recycling the widget if
1138 // it is invisible (see slotAnimationFinished()).
1139 // Check again whether it is still visible:
1140 if (!m_visibleItems
.contains(i
)) {
1144 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1145 // Remove the widget without animation
1146 recycleWidget(widget
);
1148 // Animate the removing of the items. Special case: When removing an item there
1149 // is no valid model index available anymore. For the
1150 // remove-animation the item gets removed from m_visibleItems but the widget
1151 // will stay alive until the animation has been finished and will
1152 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1153 m_visibleItems
.remove(i
);
1154 widget
->setIndex(-1);
1155 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1159 // Update the indexes of all KItemListWidget instances that are located
1160 // after the deleted items. It is important to update them in ascending
1161 // order to prevent overlaps when setting the new index.
1162 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1163 foreach (int i
, itemsToMove
) {
1164 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1166 const int newIndex
= i
- count
;
1167 if (hasMultipleRanges
) {
1168 setWidgetIndex(widget
, newIndex
);
1170 // Try to animate the moving of the item
1171 moveWidgetToIndex(widget
, newIndex
);
1175 if (!hasMultipleRanges
) {
1176 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1177 // assumes an updated geometry. If items are removed during an active transaction,
1178 // the transaction will be temporary deactivated so that doLayout() triggers a
1179 // geometry update if necessary.
1180 const int activeTransactions
= m_activeTransactions
;
1181 m_activeTransactions
= 0;
1182 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1183 m_activeTransactions
= activeTransactions
;
1184 updateSiblingsInformation();
1189 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1192 if (hasMultipleRanges
) {
1193 m_endTransactionAnimationHint
= NoAnimation
;
1195 updateSiblingsInformation();
1198 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1199 // In case if the first item of a group has been removed, the group header
1200 // must be applied to the next visible item.
1201 updateVisibleGroupHeaders();
1204 if (useAlternateBackgrounds()) {
1205 updateAlternateBackgrounds();
1209 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1211 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1212 m_layouter
->markAsDirty();
1215 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1218 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1219 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1221 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1222 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1224 updateWidgetProperties(widget
, index
);
1225 initializeItemListWidget(widget
);
1229 doLayout(NoAnimation
);
1230 updateSiblingsInformation();
1233 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1234 const QSet
<QByteArray
>& roles
)
1236 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1237 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1238 updatePreferredColumnWidths(itemRanges
);
1241 foreach (const KItemRange
& itemRange
, itemRanges
) {
1242 const int index
= itemRange
.index
;
1243 const int count
= itemRange
.count
;
1245 if (updateSizeHints
) {
1246 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1247 m_layouter
->markAsDirty();
1249 if (!m_layoutTimer
->isActive()) {
1250 m_layoutTimer
->start();
1254 // Apply the changed roles to the visible item-widgets
1255 const int lastIndex
= index
+ count
- 1;
1256 for (int i
= index
; i
<= lastIndex
; ++i
) {
1257 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1259 widget
->setData(m_model
->data(i
), roles
);
1263 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1264 // The sort-role has been changed which might result
1265 // in modified group headers
1266 updateVisibleGroupHeaders();
1267 doLayout(NoAnimation
);
1270 QAccessibleTableModelChangeEvent
ev(this, QAccessibleTableModelChangeEvent::DataChanged
);
1271 ev
.setFirstRow(itemRange
.index
);
1272 ev
.setLastRow(itemRange
.index
+ itemRange
.count
);
1273 QAccessible::updateAccessibility(&ev
);
1277 void KItemListView::slotGroupsChanged()
1279 updateVisibleGroupHeaders();
1280 doLayout(NoAnimation
);
1281 updateSiblingsInformation();
1284 void KItemListView::slotGroupedSortingChanged(bool current
)
1286 m_grouped
= current
;
1287 m_layouter
->markAsDirty();
1290 updateGroupHeaderHeight();
1292 // Clear all visible headers. Note that the QHashIterator takes a copy of
1293 // m_visibleGroups. Therefore, it remains valid even if items are removed
1294 // from m_visibleGroups in recycleGroupHeaderForWidget().
1295 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1296 while (it
.hasNext()) {
1298 recycleGroupHeaderForWidget(it
.key());
1300 Q_ASSERT(m_visibleGroups
.isEmpty());
1303 if (useAlternateBackgrounds()) {
1304 // Changing the group mode requires to update the alternate backgrounds
1305 // as with the enabled group mode the altering is done on base of the first
1307 updateAlternateBackgrounds();
1309 updateSiblingsInformation();
1310 doLayout(NoAnimation
);
1313 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1318 updateVisibleGroupHeaders();
1319 doLayout(NoAnimation
);
1323 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1328 updateVisibleGroupHeaders();
1329 doLayout(NoAnimation
);
1333 void KItemListView::slotCurrentChanged(int current
, int previous
)
1337 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1338 // always the selected item. It is not necessary to highlight the current item then.
1339 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1340 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1341 if (previousWidget
) {
1342 previousWidget
->setCurrent(false);
1345 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1346 if (currentWidget
) {
1347 currentWidget
->setCurrent(true);
1351 QAccessibleEvent
ev(this, QAccessible::Focus
);
1352 ev
.setChild(current
);
1353 QAccessible::updateAccessibility(&ev
);
1356 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1360 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1361 while (it
.hasNext()) {
1363 const int index
= it
.key();
1364 KItemListWidget
* widget
= it
.value();
1365 widget
->setSelected(current
.contains(index
));
1369 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1370 KItemListViewAnimation::AnimationType type
)
1372 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1373 Q_ASSERT(itemListWidget
);
1376 case KItemListViewAnimation::DeleteAnimation
: {
1377 // As we recycle the widget in this case it is important to assure that no
1378 // other animation has been started. This is a convention in KItemListView and
1379 // not a requirement defined by KItemListViewAnimation.
1380 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1382 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1383 // by m_visibleWidgets and must be deleted manually after the animation has
1385 recycleGroupHeaderForWidget(itemListWidget
);
1386 widgetCreator()->recycle(itemListWidget
);
1390 case KItemListViewAnimation::CreateAnimation
:
1391 case KItemListViewAnimation::MovingAnimation
:
1392 case KItemListViewAnimation::ResizeAnimation
: {
1393 const int index
= itemListWidget
->index();
1394 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1395 (index
> m_layouter
->lastVisibleIndex());
1396 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1397 recycleWidget(itemListWidget
);
1406 void KItemListView::slotLayoutTimerFinished()
1408 m_layouter
->setSize(geometry().size());
1409 doLayout(Animation
);
1412 void KItemListView::slotRubberBandPosChanged()
1417 void KItemListView::slotRubberBandActivationChanged(bool active
)
1420 connect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1421 connect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1422 m_skipAutoScrollForRubberBand
= true;
1424 disconnect(m_rubberBand
, &KItemListRubberBand::startPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1425 disconnect(m_rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListView::slotRubberBandPosChanged
);
1426 m_skipAutoScrollForRubberBand
= false;
1432 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1434 qreal previousWidth
)
1437 Q_UNUSED(currentWidth
);
1438 Q_UNUSED(previousWidth
);
1440 m_headerWidget
->setAutomaticColumnResizing(false);
1441 applyColumnWidthsFromHeader();
1442 doLayout(NoAnimation
);
1445 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1449 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1451 const QList
<QByteArray
> previous
= m_visibleRoles
;
1453 QList
<QByteArray
> current
= m_visibleRoles
;
1454 current
.removeAt(previousIndex
);
1455 current
.insert(currentIndex
, role
);
1457 setVisibleRoles(current
);
1459 emit
visibleRolesChanged(current
, previous
);
1462 void KItemListView::triggerAutoScrolling()
1464 if (!m_autoScrollTimer
) {
1469 int visibleSize
= 0;
1470 if (scrollOrientation() == Qt::Vertical
) {
1471 pos
= m_mousePos
.y();
1472 visibleSize
= size().height();
1474 pos
= m_mousePos
.x();
1475 visibleSize
= size().width();
1478 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1479 m_autoScrollIncrement
= 0;
1482 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1483 if (m_autoScrollIncrement
== 0) {
1484 // The mouse position is not above an autoscroll margin (the autoscroll timer
1485 // will be restarted in mouseMoveEvent())
1486 m_autoScrollTimer
->stop();
1490 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1491 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1492 // if the direction of the rubberband is similar to the autoscroll direction. This
1493 // prevents that starting to create a rubberband within the autoscroll margins starts
1494 // an autoscrolling.
1496 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1497 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1498 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1499 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1500 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1501 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1502 // been moved up although the autoscroll direction might be down)
1503 m_autoScrollTimer
->stop();
1508 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1509 // the autoscrolling may not get skipped anymore until a new rubberband is created
1510 m_skipAutoScrollForRubberBand
= false;
1512 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1513 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1514 setScrollOffset(newScrollOffset
);
1516 // Trigger the autoscroll timer which will periodically call
1517 // triggerAutoScrolling()
1518 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1521 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1523 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1525 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1526 Q_ASSERT(groupHeader
);
1527 updateGroupHeaderLayout(widget
);
1530 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1532 disconnectRoleEditingSignals(index
);
1534 emit
roleEditingCanceled(index
, role
, value
);
1535 m_editingRole
= false;
1538 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1540 disconnectRoleEditingSignals(index
);
1542 emit
roleEditingFinished(index
, role
, value
);
1543 m_editingRole
= false;
1546 void KItemListView::setController(KItemListController
* controller
)
1548 if (m_controller
!= controller
) {
1549 KItemListController
* previous
= m_controller
;
1551 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1552 disconnect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1553 disconnect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1556 m_controller
= controller
;
1559 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1560 connect(selectionManager
, &KItemListSelectionManager::currentChanged
, this, &KItemListView::slotCurrentChanged
);
1561 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &KItemListView::slotSelectionChanged
);
1564 onControllerChanged(controller
, previous
);
1568 void KItemListView::setModel(KItemModelBase
* model
)
1570 if (m_model
== model
) {
1574 KItemModelBase
* previous
= m_model
;
1577 disconnect(m_model
, &KItemModelBase::itemsChanged
,
1578 this, &KItemListView::slotItemsChanged
);
1579 disconnect(m_model
, &KItemModelBase::itemsInserted
,
1580 this, &KItemListView::slotItemsInserted
);
1581 disconnect(m_model
, &KItemModelBase::itemsRemoved
,
1582 this, &KItemListView::slotItemsRemoved
);
1583 disconnect(m_model
, &KItemModelBase::itemsMoved
,
1584 this, &KItemListView::slotItemsMoved
);
1585 disconnect(m_model
, &KItemModelBase::groupsChanged
,
1586 this, &KItemListView::slotGroupsChanged
);
1587 disconnect(m_model
, &KItemModelBase::groupedSortingChanged
,
1588 this, &KItemListView::slotGroupedSortingChanged
);
1589 disconnect(m_model
, &KItemModelBase::sortOrderChanged
,
1590 this, &KItemListView::slotSortOrderChanged
);
1591 disconnect(m_model
, &KItemModelBase::sortRoleChanged
,
1592 this, &KItemListView::slotSortRoleChanged
);
1594 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1598 m_layouter
->setModel(model
);
1599 m_grouped
= model
->groupedSorting();
1602 connect(m_model
, &KItemModelBase::itemsChanged
,
1603 this, &KItemListView::slotItemsChanged
);
1604 connect(m_model
, &KItemModelBase::itemsInserted
,
1605 this, &KItemListView::slotItemsInserted
);
1606 connect(m_model
, &KItemModelBase::itemsRemoved
,
1607 this, &KItemListView::slotItemsRemoved
);
1608 connect(m_model
, &KItemModelBase::itemsMoved
,
1609 this, &KItemListView::slotItemsMoved
);
1610 connect(m_model
, &KItemModelBase::groupsChanged
,
1611 this, &KItemListView::slotGroupsChanged
);
1612 connect(m_model
, &KItemModelBase::groupedSortingChanged
,
1613 this, &KItemListView::slotGroupedSortingChanged
);
1614 connect(m_model
, &KItemModelBase::sortOrderChanged
,
1615 this, &KItemListView::slotSortOrderChanged
);
1616 connect(m_model
, &KItemModelBase::sortRoleChanged
,
1617 this, &KItemListView::slotSortRoleChanged
);
1619 const int itemCount
= m_model
->count();
1620 if (itemCount
> 0) {
1621 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1625 onModelChanged(model
, previous
);
1628 KItemListRubberBand
* KItemListView::rubberBand() const
1630 return m_rubberBand
;
1633 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1635 if (m_layoutTimer
->isActive()) {
1636 m_layoutTimer
->stop();
1639 if (m_activeTransactions
> 0) {
1640 if (hint
== NoAnimation
) {
1641 // As soon as at least one property change should be done without animation,
1642 // the whole transaction will be marked as not animated.
1643 m_endTransactionAnimationHint
= NoAnimation
;
1648 if (!m_model
|| m_model
->count() < 0) {
1652 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1653 if (firstVisibleIndex
< 0) {
1654 emitOffsetChanges();
1658 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1659 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1660 // is still shown if the maximum offset got decreased.
1661 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1662 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1663 if (scrollOffset() > maxOffsetToShowFullRange
) {
1664 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1665 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1668 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1670 int firstSibblingIndex
= -1;
1671 int lastSibblingIndex
= -1;
1672 const bool supportsExpanding
= supportsItemExpanding();
1674 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1676 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1677 // instances from invisible items are reused. If no reusable items are
1678 // found then new KItemListWidget instances get created.
1679 const bool animate
= (hint
== Animation
);
1680 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1681 bool applyNewPos
= true;
1682 bool wasHidden
= false;
1684 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1685 const QPointF newPos
= itemBounds
.topLeft();
1686 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1689 if (!reusableItems
.isEmpty()) {
1690 // Reuse a KItemListWidget instance from an invisible item
1691 const int oldIndex
= reusableItems
.takeLast();
1692 widget
= m_visibleItems
.value(oldIndex
);
1693 setWidgetIndex(widget
, i
);
1694 updateWidgetProperties(widget
, i
);
1695 initializeItemListWidget(widget
);
1697 // No reusable KItemListWidget instance is available, create a new one
1698 widget
= createWidget(i
);
1700 widget
->resize(itemBounds
.size());
1702 if (animate
&& changedCount
< 0) {
1703 // Items have been deleted.
1704 if (i
>= changedIndex
) {
1705 // The item is located behind the removed range. Move the
1706 // created item to the imaginary old position outside the
1707 // view. It will get animated to the new position later.
1708 const int previousIndex
= i
- changedCount
;
1709 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1710 if (itemRect
.isEmpty()) {
1711 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1712 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1713 widget
->setPos(invisibleOldPos
);
1715 widget
->setPos(itemRect
.topLeft());
1717 applyNewPos
= false;
1721 if (supportsExpanding
&& changedCount
== 0) {
1722 if (firstSibblingIndex
< 0) {
1723 firstSibblingIndex
= i
;
1725 lastSibblingIndex
= i
;
1730 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1731 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1732 applyNewPos
= false;
1735 const bool itemsRemoved
= (changedCount
< 0);
1736 const bool itemsInserted
= (changedCount
> 0);
1737 if (itemsRemoved
&& (i
>= changedIndex
)) {
1738 // The item is located after the removed items. Animate the moving of the position.
1739 applyNewPos
= !moveWidget(widget
, newPos
);
1740 } else if (itemsInserted
&& i
>= changedIndex
) {
1741 // The item is located after the first inserted item
1742 if (i
<= changedIndex
+ changedCount
- 1) {
1743 // The item is an inserted item. Animate the appearing of the item.
1744 // For performance reasons no animation is done when changedCount is equal
1745 // to all available items.
1746 if (changedCount
< m_model
->count()) {
1747 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1749 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1750 // The item was already there before, so animate the moving of the position.
1751 // No moving animation is done if the item is animated by a create animation: This
1752 // prevents a "move animation mess" when inserting several ranges in parallel.
1753 applyNewPos
= !moveWidget(widget
, newPos
);
1755 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1756 // The size of the view might have been changed. Animate the moving of the position.
1757 applyNewPos
= !moveWidget(widget
, newPos
);
1760 m_animation
->stop(widget
);
1764 widget
->setPos(newPos
);
1767 Q_ASSERT(widget
->index() == i
);
1768 widget
->setVisible(true);
1770 if (widget
->size() != itemBounds
.size()) {
1771 // Resize the widget for the item to the changed size.
1773 // If a dynamic item size is used then no animation is done in the direction
1774 // of the dynamic size.
1775 if (m_itemSize
.width() <= 0) {
1776 // The width is dynamic, apply the new width without animation.
1777 widget
->resize(itemBounds
.width(), widget
->size().height());
1778 } else if (m_itemSize
.height() <= 0) {
1779 // The height is dynamic, apply the new height without animation.
1780 widget
->resize(widget
->size().width(), itemBounds
.height());
1782 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1784 widget
->resize(itemBounds
.size());
1788 // Updating the cell-information must be done as last step: The decision whether the
1789 // moving-animation should be started at all is based on the previous cell-information.
1790 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1791 m_visibleCells
.insert(i
, cell
);
1794 // Delete invisible KItemListWidget instances that have not been reused
1795 foreach (int index
, reusableItems
) {
1796 recycleWidget(m_visibleItems
.value(index
));
1799 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1800 Q_ASSERT(lastSibblingIndex
>= 0);
1801 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1805 // Update the layout of all visible group headers
1806 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1807 while (it
.hasNext()) {
1809 updateGroupHeaderLayout(it
.key());
1813 emitOffsetChanges();
1816 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1817 int lastVisibleIndex
,
1818 LayoutAnimationHint hint
)
1820 // Determine all items that are completely invisible and might be
1821 // reused for items that just got (at least partly) visible. If the
1822 // animation hint is set to 'Animation' items that do e.g. an animated
1823 // moving of their position are not marked as invisible: This assures
1824 // that a scrolling inside the view can be done without breaking an animation.
1828 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1829 while (it
.hasNext()) {
1832 KItemListWidget
* widget
= it
.value();
1833 const int index
= widget
->index();
1834 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1837 if (m_animation
->isStarted(widget
)) {
1838 if (hint
== NoAnimation
) {
1839 // Stopping the animation will call KItemListView::slotAnimationFinished()
1840 // and the widget will be recycled if necessary there.
1841 m_animation
->stop(widget
);
1844 widget
->setVisible(false);
1845 items
.append(index
);
1848 recycleGroupHeaderForWidget(widget
);
1857 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1859 if (widget
->pos() == newPos
) {
1863 bool startMovingAnim
= false;
1865 if (m_itemSize
.isEmpty()) {
1866 // The items are not aligned in a grid but either as columns or rows.
1867 startMovingAnim
= true;
1869 // When having a grid the moving-animation should only be started, if it is done within
1870 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1871 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1872 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1873 const int index
= widget
->index();
1874 const Cell cell
= m_visibleCells
.value(index
);
1875 if (cell
.column
>= 0 && cell
.row
>= 0) {
1876 if (scrollOrientation() == Qt::Vertical
) {
1877 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1879 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1884 if (startMovingAnim
) {
1885 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1889 m_animation
->stop(widget
);
1890 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1894 void KItemListView::emitOffsetChanges()
1896 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1897 if (m_oldScrollOffset
!= newScrollOffset
) {
1898 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1899 m_oldScrollOffset
= newScrollOffset
;
1902 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1903 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1904 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1905 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1908 const qreal newItemOffset
= m_layouter
->itemOffset();
1909 if (m_oldItemOffset
!= newItemOffset
) {
1910 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1911 m_oldItemOffset
= newItemOffset
;
1914 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1915 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1916 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1917 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1921 KItemListWidget
* KItemListView::createWidget(int index
)
1923 KItemListWidget
* widget
= widgetCreator()->create(this);
1924 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1926 m_visibleItems
.insert(index
, widget
);
1927 m_visibleCells
.insert(index
, Cell());
1928 updateWidgetProperties(widget
, index
);
1929 initializeItemListWidget(widget
);
1933 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1936 recycleGroupHeaderForWidget(widget
);
1939 const int index
= widget
->index();
1940 m_visibleItems
.remove(index
);
1941 m_visibleCells
.remove(index
);
1943 widgetCreator()->recycle(widget
);
1946 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1948 const int oldIndex
= widget
->index();
1949 m_visibleItems
.remove(oldIndex
);
1950 m_visibleCells
.remove(oldIndex
);
1952 m_visibleItems
.insert(index
, widget
);
1953 m_visibleCells
.insert(index
, Cell());
1955 widget
->setIndex(index
);
1958 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1960 const int oldIndex
= widget
->index();
1961 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1963 setWidgetIndex(widget
, index
);
1965 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1966 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1967 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1968 (!vertical
&& oldCell
.column
== newCell
.column
);
1970 m_visibleCells
.insert(index
, newCell
);
1974 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1977 case LayouterSize
: m_layouter
->setSize(size
); break;
1978 case ItemSize
: m_layouter
->setItemSize(size
); break;
1983 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1985 widget
->setVisibleRoles(m_visibleRoles
);
1986 updateWidgetColumnWidths(widget
);
1987 widget
->setStyleOption(m_styleOption
);
1989 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1991 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1992 // always the selected item. It is not necessary to highlight the current item then.
1993 if (m_controller
->selectionBehavior() != KItemListController::SingleSelection
) {
1994 widget
->setCurrent(index
== selectionManager
->currentItem());
1996 widget
->setSelected(selectionManager
->isSelected(index
));
1997 widget
->setHovered(false);
1998 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1999 widget
->setIndex(index
);
2000 widget
->setData(m_model
->data(index
));
2001 widget
->setSiblingsInformation(QBitArray());
2002 updateAlternateBackgroundForWidget(widget
);
2005 updateGroupHeaderForWidget(widget
);
2009 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
2011 Q_ASSERT(m_grouped
);
2013 const int index
= widget
->index();
2014 if (!m_layouter
->isFirstGroupItem(index
)) {
2015 // The widget does not represent the first item of a group
2016 // and hence requires no header
2017 recycleGroupHeaderForWidget(widget
);
2021 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2022 if (groups
.isEmpty() || !groupHeaderCreator()) {
2026 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2028 groupHeader
= groupHeaderCreator()->create(this);
2029 groupHeader
->setParentItem(widget
);
2030 m_visibleGroups
.insert(widget
, groupHeader
);
2031 connect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2033 Q_ASSERT(groupHeader
->parentItem() == widget
);
2035 const int groupIndex
= groupIndexForItem(index
);
2036 Q_ASSERT(groupIndex
>= 0);
2037 groupHeader
->setData(groups
.at(groupIndex
).second
);
2038 groupHeader
->setRole(model()->sortRole());
2039 groupHeader
->setStyleOption(m_styleOption
);
2040 groupHeader
->setScrollOrientation(scrollOrientation());
2041 groupHeader
->setItemIndex(index
);
2043 groupHeader
->show();
2046 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2048 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2049 Q_ASSERT(groupHeader
);
2051 const int index
= widget
->index();
2052 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2053 const QRectF itemRect
= m_layouter
->itemRect(index
);
2055 // The group-header is a child of the itemlist widget. Translate the
2056 // group header position to the relative position.
2057 if (scrollOrientation() == Qt::Vertical
) {
2058 // In the vertical scroll orientation the group header should always span
2059 // the whole width no matter which temporary position the parent widget
2060 // has. In this case the x-position and width will be adjusted manually.
2061 const qreal x
= -widget
->x() - itemOffset();
2062 const qreal width
= maximumItemOffset();
2063 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2064 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2066 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2067 groupHeader
->resize(groupHeaderRect
.size());
2071 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2073 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2075 header
->setParentItem(0);
2076 groupHeaderCreator()->recycle(header
);
2077 m_visibleGroups
.remove(widget
);
2078 disconnect(widget
, &KItemListWidget::geometryChanged
, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged
);
2082 void KItemListView::updateVisibleGroupHeaders()
2084 Q_ASSERT(m_grouped
);
2085 m_layouter
->markAsDirty();
2087 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2088 while (it
.hasNext()) {
2090 updateGroupHeaderForWidget(it
.value());
2094 int KItemListView::groupIndexForItem(int index
) const
2096 Q_ASSERT(m_grouped
);
2098 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2099 if (groups
.isEmpty()) {
2104 int max
= groups
.count() - 1;
2107 mid
= (min
+ max
) / 2;
2108 if (index
> groups
[mid
].first
) {
2113 } while (groups
[mid
].first
!= index
&& min
<= max
);
2116 while (groups
[mid
].first
> index
&& mid
> 0) {
2124 void KItemListView::updateAlternateBackgrounds()
2126 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2127 while (it
.hasNext()) {
2129 updateAlternateBackgroundForWidget(it
.value());
2133 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2135 bool enabled
= useAlternateBackgrounds();
2137 const int index
= widget
->index();
2138 enabled
= (index
& 0x1) > 0;
2140 const int groupIndex
= groupIndexForItem(index
);
2141 if (groupIndex
>= 0) {
2142 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2143 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2144 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2145 enabled
= (relativeIndex
& 0x1) > 0;
2149 widget
->setAlternateBackground(enabled
);
2152 bool KItemListView::useAlternateBackgrounds() const
2154 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2157 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2159 QElapsedTimer timer
;
2162 QHash
<QByteArray
, qreal
> widths
;
2164 // Calculate the minimum width for each column that is required
2165 // to show the headline unclipped.
2166 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2167 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2168 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2169 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2170 const QString headerText
= m_model
->roleDescription(visibleRole
);
2171 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2172 widths
.insert(visibleRole
, headerWidth
);
2175 // Calculate the preferred column withs for each item and ignore values
2176 // smaller than the width for showing the headline unclipped.
2177 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2178 int calculatedItemCount
= 0;
2179 bool maxTimeExceeded
= false;
2180 foreach (const KItemRange
& itemRange
, itemRanges
) {
2181 const int startIndex
= itemRange
.index
;
2182 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2184 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2185 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2186 qreal maxWidth
= widths
.value(visibleRole
, 0);
2187 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2188 maxWidth
= qMax(width
, maxWidth
);
2189 widths
.insert(visibleRole
, maxWidth
);
2192 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2193 // When having several thousands of items calculating the sizes can get
2194 // very expensive. We accept a possibly too small role-size in favour
2195 // of having no blocking user interface.
2196 maxTimeExceeded
= true;
2199 ++calculatedItemCount
;
2201 if (maxTimeExceeded
) {
2209 void KItemListView::applyColumnWidthsFromHeader()
2211 // Apply the new size to the layouter
2212 const qreal requiredWidth
= columnWidthsSum();
2213 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2214 m_itemSize
.height());
2215 m_layouter
->setItemSize(dynamicItemSize
);
2217 // Update the role sizes for all visible widgets
2218 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2219 while (it
.hasNext()) {
2221 updateWidgetColumnWidths(it
.value());
2225 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2227 foreach (const QByteArray
& role
, m_visibleRoles
) {
2228 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2232 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2234 Q_ASSERT(m_itemSize
.isEmpty());
2235 const int itemCount
= m_model
->count();
2236 int rangesItemCount
= 0;
2237 foreach (const KItemRange
& range
, itemRanges
) {
2238 rangesItemCount
+= range
.count
;
2241 if (itemCount
== rangesItemCount
) {
2242 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2243 foreach (const QByteArray
& role
, m_visibleRoles
) {
2244 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2247 // Only a sub range of the roles need to be determined.
2248 // The chances are good that the widths of the sub ranges
2249 // already fit into the available widths and hence no
2250 // expensive update might be required.
2251 bool changed
= false;
2253 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2254 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2255 while (it
.hasNext()) {
2257 const QByteArray
& role
= it
.key();
2258 const qreal updatedWidth
= it
.value();
2259 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2260 if (updatedWidth
> currentWidth
) {
2261 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2267 // All the updated sizes are smaller than the current sizes and no change
2268 // of the stretched roles-widths is required
2273 if (m_headerWidget
->automaticColumnResizing()) {
2274 applyAutomaticColumnWidths();
2278 void KItemListView::updatePreferredColumnWidths()
2281 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2285 void KItemListView::applyAutomaticColumnWidths()
2287 Q_ASSERT(m_itemSize
.isEmpty());
2288 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2289 if (m_visibleRoles
.isEmpty()) {
2293 // Calculate the maximum size of an item by considering the
2294 // visible role sizes and apply them to the layouter. If the
2295 // size does not use the available view-size the size of the
2296 // first role will get stretched.
2298 foreach (const QByteArray
& role
, m_visibleRoles
) {
2299 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2300 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2303 const QByteArray firstRole
= m_visibleRoles
.first();
2304 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2305 QSizeF dynamicItemSize
= m_itemSize
;
2307 qreal requiredWidth
= columnWidthsSum();
2308 const qreal availableWidth
= size().width();
2309 if (requiredWidth
< availableWidth
) {
2310 // Stretch the first column to use the whole remaining width
2311 firstColumnWidth
+= availableWidth
- requiredWidth
;
2312 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2313 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2314 // Shrink the first column to be able to show as much other
2315 // columns as possible
2316 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2318 // TODO: A proper calculation of the minimum width depends on the implementation
2319 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2321 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2322 if (shrinkedFirstColumnWidth
< minWidth
) {
2323 shrinkedFirstColumnWidth
= minWidth
;
2326 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2327 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2330 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2332 m_layouter
->setItemSize(dynamicItemSize
);
2334 // Update the role sizes for all visible widgets
2335 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2336 while (it
.hasNext()) {
2338 updateWidgetColumnWidths(it
.value());
2342 qreal
KItemListView::columnWidthsSum() const
2344 qreal widthsSum
= 0;
2345 foreach (const QByteArray
& role
, m_visibleRoles
) {
2346 widthsSum
+= m_headerWidget
->columnWidth(role
);
2351 QRectF
KItemListView::headerBoundaries() const
2353 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2356 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2357 const QSizeF
& newItemSize
,
2358 const QSizeF
& newItemMargin
) const
2360 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2364 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2365 const qreal itemWidth
= m_layouter
->itemSize().width();
2366 if (itemWidth
> 0) {
2367 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2368 newItemSize
.width(),
2369 newItemMargin
.width());
2370 if (m_model
->count() > newColumnCount
) {
2371 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2373 m_layouter
->itemMargin().width());
2374 return oldColumnCount
!= newColumnCount
;
2378 const qreal itemHeight
= m_layouter
->itemSize().height();
2379 if (itemHeight
> 0) {
2380 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2381 newItemSize
.height(),
2382 newItemMargin
.height());
2383 if (m_model
->count() > newRowCount
) {
2384 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2386 m_layouter
->itemMargin().height());
2387 return oldRowCount
!= newRowCount
;
2395 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2397 if (m_itemSize
.isEmpty()) {
2398 // We have only columns or only rows, but no grid: An animation is usually
2399 // welcome when inserting or removing items.
2400 return !supportsItemExpanding();
2403 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2407 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2408 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2409 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2410 // Only animate if up to 2/3 of a row or column are inserted or removed
2411 return changedItemCount
<= maximum
* 2 / 3;
2415 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2417 const QSizeF oldSize
= m_layouter
->size();
2419 m_layouter
->setSize(size
);
2420 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2421 m_layouter
->setSize(oldSize
);
2423 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2424 : maxOffset
> size
.width();
2427 int KItemListView::showDropIndicator(const QPointF
& pos
)
2429 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2430 while (it
.hasNext()) {
2432 const KItemListWidget
* widget
= it
.value();
2434 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2435 const QRectF rect
= itemRect(widget
->index());
2436 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2437 if (m_model
->supportsDropping(widget
->index())) {
2438 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2439 const int gap
= qMax(4.0, 0.3 * rect
.height());
2440 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2445 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2446 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2448 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2449 if (m_dropIndicator
!= draggingInsertIndicator
) {
2450 m_dropIndicator
= draggingInsertIndicator
;
2454 int index
= widget
->index();
2462 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2463 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2466 void KItemListView::hideDropIndicator()
2468 if (!m_dropIndicator
.isNull()) {
2469 m_dropIndicator
= QRectF();
2474 void KItemListView::updateGroupHeaderHeight()
2476 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2477 qreal groupHeaderMargin
= 0;
2479 if (scrollOrientation() == Qt::Horizontal
) {
2480 // The vertical margin above and below the header should be
2481 // equal to the horizontal margin, not the vertical margin
2482 // from m_styleOption.
2483 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2484 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2485 } else if (m_itemSize
.isEmpty()){
2486 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2487 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2489 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2490 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2492 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2493 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2495 updateVisibleGroupHeaders();
2498 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2500 if (!supportsItemExpanding() || !m_model
) {
2504 if (firstIndex
< 0 || lastIndex
< 0) {
2505 firstIndex
= m_layouter
->firstVisibleIndex();
2506 lastIndex
= m_layouter
->lastVisibleIndex();
2508 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2509 lastIndex
>= m_layouter
->firstVisibleIndex());
2510 if (!isRangeVisible
) {
2515 int previousParents
= 0;
2516 QBitArray previousSiblings
;
2518 // The rootIndex describes the first index where the siblings get
2519 // calculated from. For the calculation the upper most parent item
2520 // is required. For performance reasons it is checked first whether
2521 // the visible items before or after the current range already
2522 // contain a siblings information which can be used as base.
2523 int rootIndex
= firstIndex
;
2525 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2527 // There is no visible widget before the range, check whether there
2528 // is one after the range:
2529 widget
= m_visibleItems
.value(lastIndex
+ 1);
2531 // The sibling information of the widget may only be used if
2532 // all items of the range have the same number of parents.
2533 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2534 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2535 if (m_model
->expandedParentsCount(i
) != parents
) {
2544 // Performance optimization: Use the sibling information of the visible
2545 // widget beside the given range.
2546 previousSiblings
= widget
->siblingsInformation();
2547 if (previousSiblings
.isEmpty()) {
2550 previousParents
= previousSiblings
.count() - 1;
2551 previousSiblings
.truncate(previousParents
);
2553 // Potentially slow path: Go back to the upper most parent of firstIndex
2554 // to be able to calculate the initial value for the siblings.
2555 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2560 Q_ASSERT(previousParents
>= 0);
2561 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2562 // Update the parent-siblings in case if the current item represents
2563 // a child or an upper parent.
2564 const int currentParents
= m_model
->expandedParentsCount(i
);
2565 Q_ASSERT(currentParents
>= 0);
2566 if (previousParents
< currentParents
) {
2567 previousParents
= currentParents
;
2568 previousSiblings
.resize(currentParents
);
2569 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2570 } else if (previousParents
> currentParents
) {
2571 previousParents
= currentParents
;
2572 previousSiblings
.truncate(currentParents
);
2575 if (i
>= firstIndex
) {
2576 // The index represents a visible item. Apply the parent-siblings
2577 // and update the sibling of the current item.
2578 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2583 QBitArray siblings
= previousSiblings
;
2584 siblings
.resize(siblings
.count() + 1);
2585 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2587 widget
->setSiblingsInformation(siblings
);
2592 bool KItemListView::hasSiblingSuccessor(int index
) const
2594 bool hasSuccessor
= false;
2595 const int parentsCount
= m_model
->expandedParentsCount(index
);
2596 int successorIndex
= index
+ 1;
2598 // Search the next sibling
2599 const int itemCount
= m_model
->count();
2600 while (successorIndex
< itemCount
) {
2601 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2602 if (currentParentsCount
== parentsCount
) {
2603 hasSuccessor
= true;
2605 } else if (currentParentsCount
< parentsCount
) {
2611 if (m_grouped
&& hasSuccessor
) {
2612 // If the sibling is part of another group, don't mark it as
2613 // successor as the group header is between the sibling connections.
2614 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2615 if (m_layouter
->isFirstGroupItem(i
)) {
2616 hasSuccessor
= false;
2622 return hasSuccessor
;
2625 void KItemListView::disconnectRoleEditingSignals(int index
)
2627 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2632 disconnect(widget
, &KItemListWidget::roleEditingCanceled
, this, nullptr);
2633 disconnect(widget
, &KItemListWidget::roleEditingFinished
, this, nullptr);
2636 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2640 const int minSpeed
= 4;
2641 const int maxSpeed
= 128;
2642 const int speedLimiter
= 96;
2643 const int autoScrollBorder
= 64;
2645 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2646 // This assures that the autoscrolling speed grows gradually.
2647 const int incLimiter
= 1;
2649 if (pos
< autoScrollBorder
) {
2650 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2651 inc
= qMax(inc
, -maxSpeed
);
2652 inc
= qMax(inc
, oldInc
- incLimiter
);
2653 } else if (pos
> range
- autoScrollBorder
) {
2654 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2655 inc
= qMin(inc
, maxSpeed
);
2656 inc
= qMin(inc
, oldInc
+ incLimiter
);
2662 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2664 const qreal availableSize
= size
- itemMargin
;
2665 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2671 KItemListCreatorBase::~KItemListCreatorBase()
2673 qDeleteAll(m_recycleableWidgets
);
2674 qDeleteAll(m_createdWidgets
);
2677 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2679 m_createdWidgets
.insert(widget
);
2682 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2684 Q_ASSERT(m_createdWidgets
.contains(widget
));
2685 m_createdWidgets
.remove(widget
);
2687 if (m_recycleableWidgets
.count() < 100) {
2688 m_recycleableWidgets
.append(widget
);
2689 widget
->setVisible(false);
2695 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2697 if (m_recycleableWidgets
.isEmpty()) {
2701 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2702 m_createdWidgets
.insert(widget
);
2706 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2710 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2712 widget
->setParentItem(0);
2713 widget
->setOpacity(1.0);
2714 pushRecycleableWidget(widget
);
2717 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2721 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2723 header
->setOpacity(1.0);
2724 pushRecycleableWidget(header
);