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 "kitemlistcontroller.h"
27 #include "kitemlistheader.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistwidget.h"
31 #include "private/kitemlistheaderwidget.h"
32 #include "private/kitemlistrubberband.h"
33 #include "private/kitemlistsizehintresolver.h"
34 #include "private/kitemlistviewlayouter.h"
35 #include "private/kitemlistviewanimation.h"
38 #include <QGraphicsSceneMouseEvent>
39 #include <QGraphicsView>
41 #include <QPropertyAnimation>
43 #include <QStyleOptionRubberBand>
47 // Time in ms until reaching the autoscroll margin triggers
48 // an initial autoscrolling
49 const int InitialAutoScrollDelay
= 700;
51 // Delay in ms for triggering the next autoscroll
52 const int RepeatingAutoScrollDelay
= 1000 / 60;
55 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
56 QGraphicsWidget(parent
),
57 m_enabledSelectionToggles(false),
59 m_supportsItemExpanding(false),
61 m_activeTransactions(0),
62 m_endTransactionAnimationHint(Animation
),
68 m_groupHeaderCreator(0),
73 m_sizeHintResolver(0),
78 m_oldMaximumScrollOffset(0),
80 m_oldMaximumItemOffset(0),
81 m_skipAutoScrollForRubberBand(false),
84 m_autoScrollIncrement(0),
90 setAcceptHoverEvents(true);
92 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
94 m_layouter
= new KItemListViewLayouter(this);
95 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
97 m_animation
= new KItemListViewAnimation(this);
98 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
99 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
101 m_layoutTimer
= new QTimer(this);
102 m_layoutTimer
->setInterval(300);
103 m_layoutTimer
->setSingleShot(true);
104 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
106 m_rubberBand
= new KItemListRubberBand(this);
107 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
109 m_headerWidget
= new KItemListHeaderWidget(this);
110 m_headerWidget
->setVisible(false);
112 m_header
= new KItemListHeader(this);
115 KItemListView::~KItemListView()
117 // The group headers are children of the widgets created by
118 // widgetCreator(). So it is mandatory to delete the group headers
120 delete m_groupHeaderCreator
;
121 m_groupHeaderCreator
= 0;
123 delete m_widgetCreator
;
126 delete m_sizeHintResolver
;
127 m_sizeHintResolver
= 0;
130 void KItemListView::setScrollOffset(qreal offset
)
136 const qreal previousOffset
= m_layouter
->scrollOffset();
137 if (offset
== previousOffset
) {
141 m_layouter
->setScrollOffset(offset
);
142 m_animation
->setScrollOffset(offset
);
144 // Don't check whether the m_layoutTimer is active: Changing the
145 // scroll offset must always trigger a synchronous layout, otherwise
146 // the smooth-scrolling might get jerky.
147 doLayout(NoAnimation
);
148 onScrollOffsetChanged(offset
, previousOffset
);
151 qreal
KItemListView::scrollOffset() const
153 return m_layouter
->scrollOffset();
156 qreal
KItemListView::maximumScrollOffset() const
158 return m_layouter
->maximumScrollOffset();
161 void KItemListView::setItemOffset(qreal offset
)
163 if (m_layouter
->itemOffset() == offset
) {
167 m_layouter
->setItemOffset(offset
);
168 if (m_headerWidget
->isVisible()) {
169 m_headerWidget
->setOffset(offset
);
172 // Don't check whether the m_layoutTimer is active: Changing the
173 // item offset must always trigger a synchronous layout, otherwise
174 // the smooth-scrolling might get jerky.
175 doLayout(NoAnimation
);
178 qreal
KItemListView::itemOffset() const
180 return m_layouter
->itemOffset();
183 qreal
KItemListView::maximumItemOffset() const
185 return m_layouter
->maximumItemOffset();
188 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
190 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
191 m_visibleRoles
= roles
;
192 onVisibleRolesChanged(roles
, previousRoles
);
194 m_sizeHintResolver
->clearCache();
195 m_layouter
->markAsDirty();
197 if (m_itemSize
.isEmpty()) {
198 m_headerWidget
->setColumns(roles
);
199 updatePreferredColumnWidths();
200 if (!m_headerWidget
->automaticColumnResizing()) {
201 // The column-width of new roles are still 0. Apply the preferred
202 // column-width as default with.
203 foreach (const QByteArray
& role
, m_visibleRoles
) {
204 if (m_headerWidget
->columnWidth(role
) == 0) {
205 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
206 m_headerWidget
->setColumnWidth(role
, width
);
210 applyColumnWidthsFromHeader();
214 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
215 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
216 (roles
.count() <= 1 && previousRoles
.count() > 1));
218 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
219 while (it
.hasNext()) {
221 KItemListWidget
* widget
= it
.value();
222 widget
->setVisibleRoles(roles
);
223 if (alternateBackgroundsChanged
) {
224 updateAlternateBackgroundForWidget(widget
);
228 doLayout(NoAnimation
);
231 QList
<QByteArray
> KItemListView::visibleRoles() const
233 return m_visibleRoles
;
236 void KItemListView::setAutoScroll(bool enabled
)
238 if (enabled
&& !m_autoScrollTimer
) {
239 m_autoScrollTimer
= new QTimer(this);
240 m_autoScrollTimer
->setSingleShot(true);
241 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
242 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
243 } else if (!enabled
&& m_autoScrollTimer
) {
244 delete m_autoScrollTimer
;
245 m_autoScrollTimer
= 0;
249 bool KItemListView::autoScroll() const
251 return m_autoScrollTimer
!= 0;
254 void KItemListView::setEnabledSelectionToggles(bool enabled
)
256 if (m_enabledSelectionToggles
!= enabled
) {
257 m_enabledSelectionToggles
= enabled
;
259 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
260 while (it
.hasNext()) {
262 it
.value()->setEnabledSelectionToggle(enabled
);
267 bool KItemListView::enabledSelectionToggles() const
269 return m_enabledSelectionToggles
;
272 KItemListController
* KItemListView::controller() const
277 KItemModelBase
* KItemListView::model() const
282 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
284 if (m_widgetCreator
) {
285 delete m_widgetCreator
;
287 m_widgetCreator
= widgetCreator
;
290 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
292 if (!m_widgetCreator
) {
293 m_widgetCreator
= defaultWidgetCreator();
295 return m_widgetCreator
;
298 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
300 if (m_groupHeaderCreator
) {
301 delete m_groupHeaderCreator
;
303 m_groupHeaderCreator
= groupHeaderCreator
;
306 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
308 if (!m_groupHeaderCreator
) {
309 m_groupHeaderCreator
= defaultGroupHeaderCreator();
311 return m_groupHeaderCreator
;
314 QSizeF
KItemListView::itemSize() const
319 const KItemListStyleOption
& KItemListView::styleOption() const
321 return m_styleOption
;
324 void KItemListView::setGeometry(const QRectF
& rect
)
326 QGraphicsWidget::setGeometry(rect
);
332 const QSizeF newSize
= rect
.size();
333 if (m_itemSize
.isEmpty()) {
334 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
335 if (m_headerWidget
->automaticColumnResizing()) {
336 applyAutomaticColumnWidths();
338 const qreal requiredWidth
= columnWidthsSum();
339 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
340 m_itemSize
.height());
341 m_layouter
->setItemSize(dynamicItemSize
);
344 // Triggering a synchronous layout is fine from a performance point of view,
345 // as with dynamic item sizes no moving animation must be done.
346 m_layouter
->setSize(newSize
);
347 doLayout(NoAnimation
);
349 const bool animate
= !changesItemGridLayout(newSize
,
350 m_layouter
->itemSize(),
351 m_layouter
->itemMargin());
352 m_layouter
->setSize(newSize
);
355 // Trigger an asynchronous relayout with m_layoutTimer to prevent
356 // performance bottlenecks. If the timer is exceeded, an animated layout
357 // will be triggered.
358 if (!m_layoutTimer
->isActive()) {
359 m_layoutTimer
->start();
362 m_layoutTimer
->stop();
363 doLayout(NoAnimation
);
368 int KItemListView::itemAt(const QPointF
& pos
) const
370 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
371 while (it
.hasNext()) {
374 const KItemListWidget
* widget
= it
.value();
375 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
376 if (widget
->contains(mappedPos
)) {
384 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
386 if (!m_enabledSelectionToggles
) {
390 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
392 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
393 if (!selectionToggleRect
.isEmpty()) {
394 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
395 return selectionToggleRect
.contains(mappedPos
);
401 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
403 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
405 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
406 if (!expansionToggleRect
.isEmpty()) {
407 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
408 return expansionToggleRect
.contains(mappedPos
);
414 int KItemListView::firstVisibleIndex() const
416 return m_layouter
->firstVisibleIndex();
419 int KItemListView::lastVisibleIndex() const
421 return m_layouter
->lastVisibleIndex();
424 QSizeF
KItemListView::itemSizeHint(int index
) const
426 return widgetCreator()->itemSizeHint(index
, this);
429 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
431 if (m_supportsItemExpanding
!= supportsExpanding
) {
432 m_supportsItemExpanding
= supportsExpanding
;
433 updateSiblingsInformation();
434 onSupportsItemExpandingChanged(supportsExpanding
);
438 bool KItemListView::supportsItemExpanding() const
440 return m_supportsItemExpanding
;
443 QRectF
KItemListView::itemRect(int index
) const
445 return m_layouter
->itemRect(index
);
448 QRectF
KItemListView::itemContextRect(int index
) const
452 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
454 contextRect
= widget
->iconRect() | widget
->textRect();
455 contextRect
.translate(itemRect(index
).topLeft());
461 void KItemListView::scrollToItem(int index
)
463 QRectF viewGeometry
= geometry();
464 if (m_headerWidget
->isVisible()) {
465 const qreal headerHeight
= m_headerWidget
->size().height();
466 viewGeometry
.adjust(0, headerHeight
, 0, 0);
468 const QRectF currentRect
= itemRect(index
);
470 if (!viewGeometry
.contains(currentRect
)) {
471 qreal newOffset
= scrollOffset();
472 if (scrollOrientation() == Qt::Vertical
) {
473 if (currentRect
.top() < viewGeometry
.top()) {
474 newOffset
+= currentRect
.top() - viewGeometry
.top();
475 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
476 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
479 if (currentRect
.left() < viewGeometry
.left()) {
480 newOffset
+= currentRect
.left() - viewGeometry
.left();
481 } else if (currentRect
.right() > viewGeometry
.right()) {
482 newOffset
+= currentRect
.right() - viewGeometry
.right();
486 if (newOffset
!= scrollOffset()) {
487 emit
scrollTo(newOffset
);
492 void KItemListView::beginTransaction()
494 ++m_activeTransactions
;
495 if (m_activeTransactions
== 1) {
496 onTransactionBegin();
500 void KItemListView::endTransaction()
502 --m_activeTransactions
;
503 if (m_activeTransactions
< 0) {
504 m_activeTransactions
= 0;
505 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
508 if (m_activeTransactions
== 0) {
510 doLayout(m_endTransactionAnimationHint
);
511 m_endTransactionAnimationHint
= Animation
;
515 bool KItemListView::isTransactionActive() const
517 return m_activeTransactions
> 0;
520 void KItemListView::setHeaderVisible(bool visible
)
522 if (visible
&& !m_headerWidget
->isVisible()) {
523 QStyleOptionHeader option
;
524 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
527 m_headerWidget
->setPos(0, 0);
528 m_headerWidget
->resize(size().width(), headerSize
.height());
529 m_headerWidget
->setModel(m_model
);
530 m_headerWidget
->setColumns(m_visibleRoles
);
531 m_headerWidget
->setZValue(1);
533 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
534 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
535 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
536 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
537 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
538 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
539 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
540 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
542 m_layouter
->setHeaderHeight(headerSize
.height());
543 m_headerWidget
->setVisible(true);
544 } else if (!visible
&& m_headerWidget
->isVisible()) {
545 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
546 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
547 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
548 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
549 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
550 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
551 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
552 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
554 m_layouter
->setHeaderHeight(0);
555 m_headerWidget
->setVisible(false);
559 bool KItemListView::isHeaderVisible() const
561 return m_headerWidget
->isVisible();
564 KItemListHeader
* KItemListView::header() const
569 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
573 if (indexes
.count() == 1) {
574 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
575 QGraphicsView
* graphicsView
= scene()->views()[0];
576 if (item
&& graphicsView
) {
577 pixmap
= item
->createDragPixmap(0, graphicsView
);
580 // TODO: Not implemented yet. Probably extend the interface
581 // from KItemListWidget::createDragPixmap() to return a pixmap
582 // that can be used for multiple indexes.
588 void KItemListView::editRole(int index
, const QByteArray
& role
)
590 KItemListWidget
* widget
= m_visibleItems
.value(index
);
591 if (!widget
|| m_editingRole
) {
595 m_editingRole
= true;
596 widget
->setEditedRole(role
);
598 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
599 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
600 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
601 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
604 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
606 QGraphicsWidget::paint(painter
, option
, widget
);
608 if (m_rubberBand
->isActive()) {
609 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
610 m_rubberBand
->endPosition()).normalized();
612 const QPointF topLeft
= rubberBandRect
.topLeft();
613 if (scrollOrientation() == Qt::Vertical
) {
614 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
616 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
619 QStyleOptionRubberBand opt
;
620 opt
.initFrom(widget
);
621 opt
.shape
= QRubberBand::Rectangle
;
623 opt
.rect
= rubberBandRect
.toRect();
624 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
627 if (!m_dropIndicator
.isEmpty()) {
628 const QRectF r
= m_dropIndicator
.toRect();
630 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
631 painter
->setPen(color
);
633 // TODO: The following implementation works only for a vertical scroll-orientation
634 // and assumes a height of the m_draggingInsertIndicator of 1.
635 Q_ASSERT(r
.height() == 1);
636 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
639 painter
->setPen(color
);
640 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
644 void KItemListView::setItemSize(const QSizeF
& size
)
646 const QSizeF previousSize
= m_itemSize
;
647 if (size
== previousSize
) {
651 // Skip animations when the number of rows or columns
652 // are changed in the grid layout. Although the animation
653 // engine can handle this usecase, it looks obtrusive.
654 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
656 m_layouter
->itemMargin());
658 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
659 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
660 (!m_itemSize
.isEmpty() && size
.isEmpty()));
664 if (alternateBackgroundsChanged
) {
665 // For an empty item size alternate backgrounds are drawn if more than
666 // one role is shown. Assure that the backgrounds for visible items are
667 // updated when changing the size in this context.
668 updateAlternateBackgrounds();
671 if (size
.isEmpty()) {
672 if (m_headerWidget
->automaticColumnResizing()) {
673 updatePreferredColumnWidths();
675 // Only apply the changed height and respect the header widths
677 const qreal currentWidth
= m_layouter
->itemSize().width();
678 const QSizeF
newSize(currentWidth
, size
.height());
679 m_layouter
->setItemSize(newSize
);
682 m_layouter
->setItemSize(size
);
685 m_sizeHintResolver
->clearCache();
686 doLayout(animate
? Animation
: NoAnimation
);
687 onItemSizeChanged(size
, previousSize
);
690 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
692 const KItemListStyleOption previousOption
= m_styleOption
;
693 m_styleOption
= option
;
696 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
697 if (margin
!= m_layouter
->itemMargin()) {
698 // Skip animations when the number of rows or columns
699 // are changed in the grid layout. Although the animation
700 // engine can handle this usecase, it looks obtrusive.
701 animate
= !changesItemGridLayout(m_layouter
->size(),
702 m_layouter
->itemSize(),
704 m_layouter
->setItemMargin(margin
);
708 updateGroupHeaderHeight();
711 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
712 // Animating a change of the maximum text size just results in expensive
713 // temporary eliding and clipping operations and does not look good visually.
717 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
718 while (it
.hasNext()) {
720 it
.value()->setStyleOption(option
);
723 m_sizeHintResolver
->clearCache();
724 m_layouter
->markAsDirty();
725 doLayout(animate
? Animation
: NoAnimation
);
727 if (m_itemSize
.isEmpty()) {
728 updatePreferredColumnWidths();
731 onStyleOptionChanged(option
, previousOption
);
734 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
736 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
737 if (orientation
== previousOrientation
) {
741 m_layouter
->setScrollOrientation(orientation
);
742 m_animation
->setScrollOrientation(orientation
);
743 m_sizeHintResolver
->clearCache();
746 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
747 while (it
.hasNext()) {
749 it
.value()->setScrollOrientation(orientation
);
751 updateGroupHeaderHeight();
755 doLayout(NoAnimation
);
757 onScrollOrientationChanged(orientation
, previousOrientation
);
758 emit
scrollOrientationChanged(orientation
, previousOrientation
);
761 Qt::Orientation
KItemListView::scrollOrientation() const
763 return m_layouter
->scrollOrientation();
766 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
771 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
776 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
781 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
783 Q_UNUSED(changedRoles
);
787 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
793 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
799 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
805 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
811 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
817 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
823 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
829 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
831 Q_UNUSED(supportsExpanding
);
834 void KItemListView::onTransactionBegin()
838 void KItemListView::onTransactionEnd()
842 bool KItemListView::event(QEvent
* event
)
844 // Forward all events to the controller and handle them there
845 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
849 return QGraphicsWidget::event(event
);
852 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
854 m_mousePos
= transform().map(event
->pos());
858 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
860 QGraphicsWidget::mouseMoveEvent(event
);
862 m_mousePos
= transform().map(event
->pos());
863 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
864 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
868 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
870 event
->setAccepted(true);
874 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
876 QGraphicsWidget::dragMoveEvent(event
);
878 m_mousePos
= transform().map(event
->pos());
879 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
880 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
884 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
886 QGraphicsWidget::dragLeaveEvent(event
);
887 setAutoScroll(false);
890 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
892 QGraphicsWidget::dropEvent(event
);
893 setAutoScroll(false);
896 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
898 return m_visibleItems
.values();
901 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
903 if (m_itemSize
.isEmpty()) {
904 updatePreferredColumnWidths(itemRanges
);
907 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
908 if (hasMultipleRanges
) {
912 m_layouter
->markAsDirty();
914 int previouslyInsertedCount
= 0;
915 foreach (const KItemRange
& range
, itemRanges
) {
916 // range.index is related to the model before anything has been inserted.
917 // As in each loop the current item-range gets inserted the index must
918 // be increased by the already previously inserted items.
919 const int index
= range
.index
+ previouslyInsertedCount
;
920 const int count
= range
.count
;
921 if (index
< 0 || count
<= 0) {
922 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
925 previouslyInsertedCount
+= count
;
927 m_sizeHintResolver
->itemsInserted(index
, count
);
929 // Determine which visible items must be moved
930 QList
<int> itemsToMove
;
931 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
932 while (it
.hasNext()) {
934 const int visibleItemIndex
= it
.key();
935 if (visibleItemIndex
>= index
) {
936 itemsToMove
.append(visibleItemIndex
);
940 // Update the indexes of all KItemListWidget instances that are located
941 // after the inserted items. It is important to adjust the indexes in the order
942 // from the highest index to the lowest index to prevent overlaps when setting the new index.
944 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
945 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
947 const int newIndex
= widget
->index() + count
;
948 if (hasMultipleRanges
) {
949 setWidgetIndex(widget
, newIndex
);
951 // Try to animate the moving of the item
952 moveWidgetToIndex(widget
, newIndex
);
956 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
957 // Check whether a scrollbar is required to show the inserted items. In this case
958 // the size of the layouter will be decreased before calling doLayout(): This prevents
959 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
960 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
961 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
962 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
963 if (decreaseLayouterSize
) {
964 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
965 QSizeF layouterSize
= m_layouter
->size();
966 if (verticalScrollOrientation
) {
967 layouterSize
.rwidth() -= scrollBarExtent
;
969 layouterSize
.rheight() -= scrollBarExtent
;
971 m_layouter
->setSize(layouterSize
);
975 if (!hasMultipleRanges
) {
976 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
977 updateSiblingsInformation();
982 m_controller
->selectionManager()->itemsInserted(itemRanges
);
985 if (hasMultipleRanges
) {
987 // Important: Don't read any m_layouter-property inside the for-loop in case if
988 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
989 // updated in each loop-cycle and has only a consistent state after the loop.
990 Q_ASSERT(m_layouter
->isDirty());
992 m_endTransactionAnimationHint
= NoAnimation
;
995 updateSiblingsInformation();
998 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
999 // In case if items of the same group have been inserted before an item that
1000 // currently represents the first item of the group, the group header of
1001 // this item must be removed.
1002 updateVisibleGroupHeaders();
1005 if (useAlternateBackgrounds()) {
1006 updateAlternateBackgrounds();
1010 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1012 if (m_itemSize
.isEmpty()) {
1013 // Don't pass the item-range: The preferred column-widths of
1014 // all items must be adjusted when removing items.
1015 updatePreferredColumnWidths();
1018 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1019 if (hasMultipleRanges
) {
1023 m_layouter
->markAsDirty();
1025 int removedItemsCount
= 0;
1026 for (int i
= 0; i
< itemRanges
.count(); ++i
) {
1027 removedItemsCount
+= itemRanges
[i
].count
;
1030 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1031 const KItemRange
& range
= itemRanges
[i
];
1032 const int index
= range
.index
;
1033 const int count
= range
.count
;
1034 if (index
< 0 || count
<= 0) {
1035 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1039 m_sizeHintResolver
->itemsRemoved(index
, count
);
1041 const int firstRemovedIndex
= index
;
1042 const int lastRemovedIndex
= index
+ count
- 1;
1043 const int lastIndex
= m_model
->count() - 1 + removedItemsCount
;
1044 removedItemsCount
-= count
;
1046 // Remove all KItemListWidget instances that got deleted
1047 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
1048 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1053 m_animation
->stop(widget
);
1054 // Stopping the animation might lead to recycling the widget if
1055 // it is invisible (see slotAnimationFinished()).
1056 // Check again whether it is still visible:
1057 if (!m_visibleItems
.contains(i
)) {
1061 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1062 // Remove the widget without animation
1063 recycleWidget(widget
);
1065 // Animate the removing of the items. Special case: When removing an item there
1066 // is no valid model index available anymore. For the
1067 // remove-animation the item gets removed from m_visibleItems but the widget
1068 // will stay alive until the animation has been finished and will
1069 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1070 m_visibleItems
.remove(i
);
1071 widget
->setIndex(-1);
1072 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1076 // Update the indexes of all KItemListWidget instances that are located
1077 // after the deleted items
1078 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
1079 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1081 const int newIndex
= i
- count
;
1082 if (hasMultipleRanges
) {
1083 setWidgetIndex(widget
, newIndex
);
1085 // Try to animate the moving of the item
1086 moveWidgetToIndex(widget
, newIndex
);
1091 if (!hasMultipleRanges
) {
1092 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1093 // assumes an updated geometry. If items are removed during an active transaction,
1094 // the transaction will be temporary deactivated so that doLayout() triggers a
1095 // geometry update if necessary.
1096 const int activeTransactions
= m_activeTransactions
;
1097 m_activeTransactions
= 0;
1098 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1099 m_activeTransactions
= activeTransactions
;
1100 updateSiblingsInformation();
1105 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1108 if (hasMultipleRanges
) {
1110 // Important: Don't read any m_layouter-property inside the for-loop in case if
1111 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1112 // updated in each loop-cycle and has only a consistent state after the loop.
1113 Q_ASSERT(m_layouter
->isDirty());
1115 m_endTransactionAnimationHint
= NoAnimation
;
1117 updateSiblingsInformation();
1120 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1121 // In case if the first item of a group has been removed, the group header
1122 // must be applied to the next visible item.
1123 updateVisibleGroupHeaders();
1126 if (useAlternateBackgrounds()) {
1127 updateAlternateBackgrounds();
1131 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1133 m_sizeHintResolver
->itemsMoved(itemRange
.index
, itemRange
.count
);
1134 m_layouter
->markAsDirty();
1137 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1140 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1141 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1143 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1144 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1146 updateWidgetProperties(widget
, index
);
1147 initializeItemListWidget(widget
);
1151 doLayout(NoAnimation
);
1152 updateSiblingsInformation();
1155 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1156 const QSet
<QByteArray
>& roles
)
1158 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1159 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1160 updatePreferredColumnWidths(itemRanges
);
1163 foreach (const KItemRange
& itemRange
, itemRanges
) {
1164 const int index
= itemRange
.index
;
1165 const int count
= itemRange
.count
;
1167 if (updateSizeHints
) {
1168 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1169 m_layouter
->markAsDirty();
1171 if (!m_layoutTimer
->isActive()) {
1172 m_layoutTimer
->start();
1176 // Apply the changed roles to the visible item-widgets
1177 const int lastIndex
= index
+ count
- 1;
1178 for (int i
= index
; i
<= lastIndex
; ++i
) {
1179 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1181 widget
->setData(m_model
->data(i
), roles
);
1185 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1186 // The sort-role has been changed which might result
1187 // in modified group headers
1188 updateVisibleGroupHeaders();
1189 doLayout(NoAnimation
);
1194 void KItemListView::slotGroupedSortingChanged(bool current
)
1196 m_grouped
= current
;
1197 m_layouter
->markAsDirty();
1200 updateGroupHeaderHeight();
1202 // Clear all visible headers
1203 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1204 while (it
.hasNext()) {
1206 recycleGroupHeaderForWidget(it
.key());
1208 Q_ASSERT(m_visibleGroups
.isEmpty());
1211 if (useAlternateBackgrounds()) {
1212 // Changing the group mode requires to update the alternate backgrounds
1213 // as with the enabled group mode the altering is done on base of the first
1215 updateAlternateBackgrounds();
1217 updateSiblingsInformation();
1218 doLayout(NoAnimation
);
1221 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1226 updateVisibleGroupHeaders();
1227 doLayout(NoAnimation
);
1231 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1236 updateVisibleGroupHeaders();
1237 doLayout(NoAnimation
);
1241 void KItemListView::slotCurrentChanged(int current
, int previous
)
1245 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1246 if (previousWidget
) {
1247 previousWidget
->setCurrent(false);
1250 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1251 if (currentWidget
) {
1252 currentWidget
->setCurrent(true);
1256 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1260 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1261 while (it
.hasNext()) {
1263 const int index
= it
.key();
1264 KItemListWidget
* widget
= it
.value();
1265 widget
->setSelected(current
.contains(index
));
1269 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1270 KItemListViewAnimation::AnimationType type
)
1272 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1273 Q_ASSERT(itemListWidget
);
1276 case KItemListViewAnimation::DeleteAnimation
: {
1277 // As we recycle the widget in this case it is important to assure that no
1278 // other animation has been started. This is a convention in KItemListView and
1279 // not a requirement defined by KItemListViewAnimation.
1280 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1282 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1283 // by m_visibleWidgets and must be deleted manually after the animation has
1285 recycleGroupHeaderForWidget(itemListWidget
);
1286 widgetCreator()->recycle(itemListWidget
);
1290 case KItemListViewAnimation::CreateAnimation
:
1291 case KItemListViewAnimation::MovingAnimation
:
1292 case KItemListViewAnimation::ResizeAnimation
: {
1293 const int index
= itemListWidget
->index();
1294 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1295 (index
> m_layouter
->lastVisibleIndex());
1296 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1297 recycleWidget(itemListWidget
);
1306 void KItemListView::slotLayoutTimerFinished()
1308 m_layouter
->setSize(geometry().size());
1309 doLayout(Animation
);
1312 void KItemListView::slotRubberBandPosChanged()
1317 void KItemListView::slotRubberBandActivationChanged(bool active
)
1320 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1321 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1322 m_skipAutoScrollForRubberBand
= true;
1324 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1325 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1326 m_skipAutoScrollForRubberBand
= false;
1332 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1334 qreal previousWidth
)
1337 Q_UNUSED(currentWidth
);
1338 Q_UNUSED(previousWidth
);
1340 m_headerWidget
->setAutomaticColumnResizing(false);
1341 applyColumnWidthsFromHeader();
1342 doLayout(NoAnimation
);
1345 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1349 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1351 const QList
<QByteArray
> previous
= m_visibleRoles
;
1353 QList
<QByteArray
> current
= m_visibleRoles
;
1354 current
.removeAt(previousIndex
);
1355 current
.insert(currentIndex
, role
);
1357 setVisibleRoles(current
);
1359 emit
visibleRolesChanged(current
, previous
);
1362 void KItemListView::triggerAutoScrolling()
1364 if (!m_autoScrollTimer
) {
1369 int visibleSize
= 0;
1370 if (scrollOrientation() == Qt::Vertical
) {
1371 pos
= m_mousePos
.y();
1372 visibleSize
= size().height();
1374 pos
= m_mousePos
.x();
1375 visibleSize
= size().width();
1378 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1379 m_autoScrollIncrement
= 0;
1382 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1383 if (m_autoScrollIncrement
== 0) {
1384 // The mouse position is not above an autoscroll margin (the autoscroll timer
1385 // will be restarted in mouseMoveEvent())
1386 m_autoScrollTimer
->stop();
1390 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1391 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1392 // if the direction of the rubberband is similar to the autoscroll direction. This
1393 // prevents that starting to create a rubberband within the autoscroll margins starts
1394 // an autoscrolling.
1396 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1397 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1398 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1399 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1400 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1401 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1402 // been moved up although the autoscroll direction might be down)
1403 m_autoScrollTimer
->stop();
1408 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1409 // the autoscrolling may not get skipped anymore until a new rubberband is created
1410 m_skipAutoScrollForRubberBand
= false;
1412 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1413 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1414 setScrollOffset(newScrollOffset
);
1416 // Trigger the autoscroll timer which will periodically call
1417 // triggerAutoScrolling()
1418 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1421 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1423 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1425 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1426 Q_ASSERT(groupHeader
);
1427 updateGroupHeaderLayout(widget
);
1430 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1432 emit
roleEditingCanceled(index
, role
, value
);
1433 m_editingRole
= false;
1436 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1438 emit
roleEditingFinished(index
, role
, value
);
1439 m_editingRole
= false;
1442 void KItemListView::setController(KItemListController
* controller
)
1444 if (m_controller
!= controller
) {
1445 KItemListController
* previous
= m_controller
;
1447 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1448 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1449 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1452 m_controller
= controller
;
1455 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1456 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1457 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1460 onControllerChanged(controller
, previous
);
1464 void KItemListView::setModel(KItemModelBase
* model
)
1466 if (m_model
== model
) {
1470 KItemModelBase
* previous
= m_model
;
1473 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1474 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1475 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1476 this, SLOT(slotItemsInserted(KItemRangeList
)));
1477 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1478 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1479 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1480 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1481 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1482 this, SLOT(slotGroupedSortingChanged(bool)));
1483 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1484 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1485 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1486 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1489 m_sizeHintResolver
->clearCache();
1492 m_layouter
->setModel(model
);
1493 m_grouped
= model
->groupedSorting();
1496 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1497 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1498 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1499 this, SLOT(slotItemsInserted(KItemRangeList
)));
1500 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1501 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1502 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1503 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1504 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1505 this, SLOT(slotGroupedSortingChanged(bool)));
1506 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1507 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1508 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1509 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1511 const int itemCount
= m_model
->count();
1512 if (itemCount
> 0) {
1513 m_sizeHintResolver
->itemsInserted(0, itemCount
);
1514 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1518 onModelChanged(model
, previous
);
1521 KItemListRubberBand
* KItemListView::rubberBand() const
1523 return m_rubberBand
;
1526 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1528 if (m_layoutTimer
->isActive()) {
1529 m_layoutTimer
->stop();
1532 if (m_activeTransactions
> 0) {
1533 if (hint
== NoAnimation
) {
1534 // As soon as at least one property change should be done without animation,
1535 // the whole transaction will be marked as not animated.
1536 m_endTransactionAnimationHint
= NoAnimation
;
1541 if (!m_model
|| m_model
->count() < 0) {
1545 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1546 if (firstVisibleIndex
< 0) {
1547 emitOffsetChanges();
1551 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1552 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1553 // is still shown if the maximum offset got decreased.
1554 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1555 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1556 if (scrollOffset() > maxOffsetToShowFullRange
) {
1557 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1558 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1561 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1563 int firstSibblingIndex
= -1;
1564 int lastSibblingIndex
= -1;
1565 const bool supportsExpanding
= supportsItemExpanding();
1567 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1569 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1570 // instances from invisible items are reused. If no reusable items are
1571 // found then new KItemListWidget instances get created.
1572 const bool animate
= (hint
== Animation
);
1573 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1574 bool applyNewPos
= true;
1575 bool wasHidden
= false;
1577 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1578 const QPointF newPos
= itemBounds
.topLeft();
1579 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1582 if (!reusableItems
.isEmpty()) {
1583 // Reuse a KItemListWidget instance from an invisible item
1584 const int oldIndex
= reusableItems
.takeLast();
1585 widget
= m_visibleItems
.value(oldIndex
);
1586 setWidgetIndex(widget
, i
);
1587 updateWidgetProperties(widget
, i
);
1588 initializeItemListWidget(widget
);
1590 // No reusable KItemListWidget instance is available, create a new one
1591 widget
= createWidget(i
);
1593 widget
->resize(itemBounds
.size());
1595 if (animate
&& changedCount
< 0) {
1596 // Items have been deleted, move the created item to the
1597 // imaginary old position. They will get animated to the new position
1599 const QRectF itemRect
= m_layouter
->itemRect(i
- changedCount
);
1600 if (itemRect
.isEmpty()) {
1601 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1602 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1603 widget
->setPos(invisibleOldPos
);
1605 widget
->setPos(itemRect
.topLeft());
1607 applyNewPos
= false;
1610 if (supportsExpanding
&& changedCount
== 0) {
1611 if (firstSibblingIndex
< 0) {
1612 firstSibblingIndex
= i
;
1614 lastSibblingIndex
= i
;
1619 const bool itemsRemoved
= (changedCount
< 0);
1620 const bool itemsInserted
= (changedCount
> 0);
1621 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1622 // The item is located after the removed items. Animate the moving of the position.
1623 applyNewPos
= !moveWidget(widget
, newPos
);
1624 } else if (itemsInserted
&& i
>= changedIndex
) {
1625 // The item is located after the first inserted item
1626 if (i
<= changedIndex
+ changedCount
- 1) {
1627 // The item is an inserted item. Animate the appearing of the item.
1628 // For performance reasons no animation is done when changedCount is equal
1629 // to all available items.
1630 if (changedCount
< m_model
->count()) {
1631 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1633 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1634 // The item was already there before, so animate the moving of the position.
1635 // No moving animation is done if the item is animated by a create animation: This
1636 // prevents a "move animation mess" when inserting several ranges in parallel.
1637 applyNewPos
= !moveWidget(widget
, newPos
);
1639 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1640 // The size of the view might have been changed. Animate the moving of the position.
1641 applyNewPos
= !moveWidget(widget
, newPos
);
1644 m_animation
->stop(widget
);
1648 widget
->setPos(newPos
);
1651 Q_ASSERT(widget
->index() == i
);
1652 widget
->setVisible(true);
1654 if (widget
->size() != itemBounds
.size()) {
1655 // Resize the widget for the item to the changed size.
1657 // If a dynamic item size is used then no animation is done in the direction
1658 // of the dynamic size.
1659 if (m_itemSize
.width() <= 0) {
1660 // The width is dynamic, apply the new width without animation.
1661 widget
->resize(itemBounds
.width(), widget
->size().height());
1662 } else if (m_itemSize
.height() <= 0) {
1663 // The height is dynamic, apply the new height without animation.
1664 widget
->resize(widget
->size().width(), itemBounds
.height());
1666 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1668 widget
->resize(itemBounds
.size());
1672 // Updating the cell-information must be done as last step: The decision whether the
1673 // moving-animation should be started at all is based on the previous cell-information.
1674 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1675 m_visibleCells
.insert(i
, cell
);
1678 // Delete invisible KItemListWidget instances that have not been reused
1679 foreach (int index
, reusableItems
) {
1680 recycleWidget(m_visibleItems
.value(index
));
1683 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1684 Q_ASSERT(lastSibblingIndex
>= 0);
1685 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1689 // Update the layout of all visible group headers
1690 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1691 while (it
.hasNext()) {
1693 updateGroupHeaderLayout(it
.key());
1697 emitOffsetChanges();
1700 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1701 int lastVisibleIndex
,
1702 LayoutAnimationHint hint
)
1704 // Determine all items that are completely invisible and might be
1705 // reused for items that just got (at least partly) visible. If the
1706 // animation hint is set to 'Animation' items that do e.g. an animated
1707 // moving of their position are not marked as invisible: This assures
1708 // that a scrolling inside the view can be done without breaking an animation.
1712 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1713 while (it
.hasNext()) {
1716 KItemListWidget
* widget
= it
.value();
1717 const int index
= widget
->index();
1718 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1721 if (m_animation
->isStarted(widget
)) {
1722 if (hint
== NoAnimation
) {
1723 // Stopping the animation will call KItemListView::slotAnimationFinished()
1724 // and the widget will be recycled if necessary there.
1725 m_animation
->stop(widget
);
1728 widget
->setVisible(false);
1729 items
.append(index
);
1732 recycleGroupHeaderForWidget(widget
);
1741 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1743 if (widget
->pos() == newPos
) {
1747 bool startMovingAnim
= false;
1749 if (m_itemSize
.isEmpty()) {
1750 // The items are not aligned in a grid but either as columns or rows.
1751 startMovingAnim
= !supportsItemExpanding();
1753 // When having a grid the moving-animation should only be started, if it is done within
1754 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1755 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1756 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1757 const int index
= widget
->index();
1758 const Cell cell
= m_visibleCells
.value(index
);
1759 if (cell
.column
>= 0 && cell
.row
>= 0) {
1760 if (scrollOrientation() == Qt::Vertical
) {
1761 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1763 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1768 if (startMovingAnim
) {
1769 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1773 m_animation
->stop(widget
);
1774 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1778 void KItemListView::emitOffsetChanges()
1780 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1781 if (m_oldScrollOffset
!= newScrollOffset
) {
1782 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1783 m_oldScrollOffset
= newScrollOffset
;
1786 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1787 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1788 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1789 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1792 const qreal newItemOffset
= m_layouter
->itemOffset();
1793 if (m_oldItemOffset
!= newItemOffset
) {
1794 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1795 m_oldItemOffset
= newItemOffset
;
1798 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1799 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1800 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1801 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1805 KItemListWidget
* KItemListView::createWidget(int index
)
1807 KItemListWidget
* widget
= widgetCreator()->create(this);
1808 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1810 m_visibleItems
.insert(index
, widget
);
1811 m_visibleCells
.insert(index
, Cell());
1812 updateWidgetProperties(widget
, index
);
1813 initializeItemListWidget(widget
);
1817 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1820 recycleGroupHeaderForWidget(widget
);
1823 const int index
= widget
->index();
1824 m_visibleItems
.remove(index
);
1825 m_visibleCells
.remove(index
);
1827 widgetCreator()->recycle(widget
);
1830 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1832 const int oldIndex
= widget
->index();
1833 m_visibleItems
.remove(oldIndex
);
1834 m_visibleCells
.remove(oldIndex
);
1836 m_visibleItems
.insert(index
, widget
);
1837 m_visibleCells
.insert(index
, Cell());
1839 widget
->setIndex(index
);
1842 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1844 const int oldIndex
= widget
->index();
1845 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1847 setWidgetIndex(widget
, index
);
1849 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1850 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1851 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1852 (!vertical
&& oldCell
.column
== newCell
.column
);
1854 m_visibleCells
.insert(index
, newCell
);
1858 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1861 case LayouterSize
: m_layouter
->setSize(size
); break;
1862 case ItemSize
: m_layouter
->setItemSize(size
); break;
1867 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1869 widget
->setVisibleRoles(m_visibleRoles
);
1870 updateWidgetColumnWidths(widget
);
1871 widget
->setStyleOption(m_styleOption
);
1873 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1874 widget
->setCurrent(index
== selectionManager
->currentItem());
1875 widget
->setSelected(selectionManager
->isSelected(index
));
1876 widget
->setHovered(false);
1877 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1878 widget
->setIndex(index
);
1879 widget
->setData(m_model
->data(index
));
1880 widget
->setSiblingsInformation(QBitArray());
1881 updateAlternateBackgroundForWidget(widget
);
1884 updateGroupHeaderForWidget(widget
);
1888 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1890 Q_ASSERT(m_grouped
);
1892 const int index
= widget
->index();
1893 if (!m_layouter
->isFirstGroupItem(index
)) {
1894 // The widget does not represent the first item of a group
1895 // and hence requires no header
1896 recycleGroupHeaderForWidget(widget
);
1900 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1901 if (groups
.isEmpty() || !groupHeaderCreator()) {
1905 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1907 groupHeader
= groupHeaderCreator()->create(this);
1908 groupHeader
->setParentItem(widget
);
1909 m_visibleGroups
.insert(widget
, groupHeader
);
1910 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1912 Q_ASSERT(groupHeader
->parentItem() == widget
);
1914 const int groupIndex
= groupIndexForItem(index
);
1915 Q_ASSERT(groupIndex
>= 0);
1916 groupHeader
->setData(groups
.at(groupIndex
).second
);
1917 groupHeader
->setRole(model()->sortRole());
1918 groupHeader
->setStyleOption(m_styleOption
);
1919 groupHeader
->setScrollOrientation(scrollOrientation());
1920 groupHeader
->setItemIndex(index
);
1922 groupHeader
->show();
1925 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1927 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1928 Q_ASSERT(groupHeader
);
1930 const int index
= widget
->index();
1931 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1932 const QRectF itemRect
= m_layouter
->itemRect(index
);
1934 // The group-header is a child of the itemlist widget. Translate the
1935 // group header position to the relative position.
1936 if (scrollOrientation() == Qt::Vertical
) {
1937 // In the vertical scroll orientation the group header should always span
1938 // the whole width no matter which temporary position the parent widget
1939 // has. In this case the x-position and width will be adjusted manually.
1940 const qreal x
= -widget
->x() - itemOffset();
1941 const qreal width
= maximumItemOffset();
1942 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1943 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1945 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1946 groupHeader
->resize(groupHeaderRect
.size());
1950 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
1952 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1954 header
->setParentItem(0);
1955 groupHeaderCreator()->recycle(header
);
1956 m_visibleGroups
.remove(widget
);
1957 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1961 void KItemListView::updateVisibleGroupHeaders()
1963 Q_ASSERT(m_grouped
);
1964 m_layouter
->markAsDirty();
1966 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1967 while (it
.hasNext()) {
1969 updateGroupHeaderForWidget(it
.value());
1973 int KItemListView::groupIndexForItem(int index
) const
1975 Q_ASSERT(m_grouped
);
1977 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1978 if (groups
.isEmpty()) {
1983 int max
= groups
.count() - 1;
1986 mid
= (min
+ max
) / 2;
1987 if (index
> groups
[mid
].first
) {
1992 } while (groups
[mid
].first
!= index
&& min
<= max
);
1995 while (groups
[mid
].first
> index
&& mid
> 0) {
2003 void KItemListView::updateAlternateBackgrounds()
2005 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2006 while (it
.hasNext()) {
2008 updateAlternateBackgroundForWidget(it
.value());
2012 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2014 bool enabled
= useAlternateBackgrounds();
2016 const int index
= widget
->index();
2017 enabled
= (index
& 0x1) > 0;
2019 const int groupIndex
= groupIndexForItem(index
);
2020 if (groupIndex
>= 0) {
2021 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2022 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2023 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2024 enabled
= (relativeIndex
& 0x1) > 0;
2028 widget
->setAlternateBackground(enabled
);
2031 bool KItemListView::useAlternateBackgrounds() const
2033 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2036 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2038 QElapsedTimer timer
;
2041 QHash
<QByteArray
, qreal
> widths
;
2043 // Calculate the minimum width for each column that is required
2044 // to show the headline unclipped.
2045 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2046 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2047 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2048 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2049 const QString headerText
= m_model
->roleDescription(visibleRole
);
2050 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2051 widths
.insert(visibleRole
, headerWidth
);
2054 // Calculate the preferred column withs for each item and ignore values
2055 // smaller than the width for showing the headline unclipped.
2056 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2057 int calculatedItemCount
= 0;
2058 bool maxTimeExceeded
= false;
2059 foreach (const KItemRange
& itemRange
, itemRanges
) {
2060 const int startIndex
= itemRange
.index
;
2061 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2063 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2064 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2065 qreal maxWidth
= widths
.value(visibleRole
, 0);
2066 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2067 maxWidth
= qMax(width
, maxWidth
);
2068 widths
.insert(visibleRole
, maxWidth
);
2071 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2072 // When having several thousands of items calculating the sizes can get
2073 // very expensive. We accept a possibly too small role-size in favour
2074 // of having no blocking user interface.
2075 maxTimeExceeded
= true;
2078 ++calculatedItemCount
;
2080 if (maxTimeExceeded
) {
2088 void KItemListView::applyColumnWidthsFromHeader()
2090 // Apply the new size to the layouter
2091 const qreal requiredWidth
= columnWidthsSum();
2092 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2093 m_itemSize
.height());
2094 m_layouter
->setItemSize(dynamicItemSize
);
2096 // Update the role sizes for all visible widgets
2097 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2098 while (it
.hasNext()) {
2100 updateWidgetColumnWidths(it
.value());
2104 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2106 foreach (const QByteArray
& role
, m_visibleRoles
) {
2107 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2111 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2113 Q_ASSERT(m_itemSize
.isEmpty());
2114 const int itemCount
= m_model
->count();
2115 int rangesItemCount
= 0;
2116 foreach (const KItemRange
& range
, itemRanges
) {
2117 rangesItemCount
+= range
.count
;
2120 if (itemCount
== rangesItemCount
) {
2121 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2122 foreach (const QByteArray
& role
, m_visibleRoles
) {
2123 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2126 // Only a sub range of the roles need to be determined.
2127 // The chances are good that the widths of the sub ranges
2128 // already fit into the available widths and hence no
2129 // expensive update might be required.
2130 bool changed
= false;
2132 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2133 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2134 while (it
.hasNext()) {
2136 const QByteArray
& role
= it
.key();
2137 const qreal updatedWidth
= it
.value();
2138 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2139 if (updatedWidth
> currentWidth
) {
2140 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2146 // All the updated sizes are smaller than the current sizes and no change
2147 // of the stretched roles-widths is required
2152 if (m_headerWidget
->automaticColumnResizing()) {
2153 applyAutomaticColumnWidths();
2157 void KItemListView::updatePreferredColumnWidths()
2160 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2164 void KItemListView::applyAutomaticColumnWidths()
2166 Q_ASSERT(m_itemSize
.isEmpty());
2167 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2168 if (m_visibleRoles
.isEmpty()) {
2172 // Calculate the maximum size of an item by considering the
2173 // visible role sizes and apply them to the layouter. If the
2174 // size does not use the available view-size the size of the
2175 // first role will get stretched.
2177 foreach (const QByteArray
& role
, m_visibleRoles
) {
2178 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2179 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2182 const QByteArray firstRole
= m_visibleRoles
.first();
2183 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2184 QSizeF dynamicItemSize
= m_itemSize
;
2186 qreal requiredWidth
= columnWidthsSum();
2187 const qreal availableWidth
= size().width();
2188 if (requiredWidth
< availableWidth
) {
2189 // Stretch the first column to use the whole remaining width
2190 firstColumnWidth
+= availableWidth
- requiredWidth
;
2191 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2192 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2193 // Shrink the first column to be able to show as much other
2194 // columns as possible
2195 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2197 // TODO: A proper calculation of the minimum width depends on the implementation
2198 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2200 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2201 if (shrinkedFirstColumnWidth
< minWidth
) {
2202 shrinkedFirstColumnWidth
= minWidth
;
2205 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2206 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2209 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2211 m_layouter
->setItemSize(dynamicItemSize
);
2213 // Update the role sizes for all visible widgets
2214 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2215 while (it
.hasNext()) {
2217 updateWidgetColumnWidths(it
.value());
2221 qreal
KItemListView::columnWidthsSum() const
2223 qreal widthsSum
= 0;
2224 foreach (const QByteArray
& role
, m_visibleRoles
) {
2225 widthsSum
+= m_headerWidget
->columnWidth(role
);
2230 QRectF
KItemListView::headerBoundaries() const
2232 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2235 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2236 const QSizeF
& newItemSize
,
2237 const QSizeF
& newItemMargin
) const
2239 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2243 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2244 const qreal itemWidth
= m_layouter
->itemSize().width();
2245 if (itemWidth
> 0) {
2246 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2247 newItemSize
.width(),
2248 newItemMargin
.width());
2249 if (m_model
->count() > newColumnCount
) {
2250 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2252 m_layouter
->itemMargin().width());
2253 return oldColumnCount
!= newColumnCount
;
2257 const qreal itemHeight
= m_layouter
->itemSize().height();
2258 if (itemHeight
> 0) {
2259 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2260 newItemSize
.height(),
2261 newItemMargin
.height());
2262 if (m_model
->count() > newRowCount
) {
2263 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2265 m_layouter
->itemMargin().height());
2266 return oldRowCount
!= newRowCount
;
2274 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2276 if (m_itemSize
.isEmpty()) {
2277 // We have only columns or only rows, but no grid: An animation is usually
2278 // welcome when inserting or removing items.
2279 return !supportsItemExpanding();
2282 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2286 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2287 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2288 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2289 // Only animate if up to 2/3 of a row or column are inserted or removed
2290 return changedItemCount
<= maximum
* 2 / 3;
2294 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2296 const QSizeF oldSize
= m_layouter
->size();
2298 m_layouter
->setSize(size
);
2299 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2300 m_layouter
->setSize(oldSize
);
2302 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2303 : maxOffset
> size
.width();
2306 int KItemListView::showDropIndicator(const QPointF
& pos
)
2308 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2309 while (it
.hasNext()) {
2311 const KItemListWidget
* widget
= it
.value();
2313 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2314 const QRectF rect
= itemRect(widget
->index());
2315 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2316 const qreal y
= (mappedPos
.y () < rect
.height() / 2) ?
2317 rect
.top() : rect
.bottom();
2319 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2320 if (m_dropIndicator
!= draggingInsertIndicator
) {
2321 m_dropIndicator
= draggingInsertIndicator
;
2324 return widget
->index();
2331 void KItemListView::hideDropIndicator()
2333 if (!m_dropIndicator
.isNull()) {
2334 m_dropIndicator
= QRectF();
2339 void KItemListView::updateGroupHeaderHeight()
2341 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2342 qreal groupHeaderMargin
= 0;
2344 if (scrollOrientation() == Qt::Horizontal
) {
2345 // The vertical margin above and below the header should be
2346 // equal to the horizontal margin, not the vertical margin
2347 // from m_styleOption.
2348 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2349 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2350 } else if (m_itemSize
.isEmpty()){
2351 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2352 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2354 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2355 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2357 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2358 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2360 updateVisibleGroupHeaders();
2363 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2365 if (!supportsItemExpanding() || !m_model
) {
2369 if (firstIndex
< 0 || lastIndex
< 0) {
2370 firstIndex
= m_layouter
->firstVisibleIndex();
2371 lastIndex
= m_layouter
->lastVisibleIndex();
2373 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2374 lastIndex
>= m_layouter
->firstVisibleIndex());
2375 if (!isRangeVisible
) {
2380 int previousParents
= 0;
2381 QBitArray previousSiblings
;
2383 // The rootIndex describes the first index where the siblings get
2384 // calculated from. For the calculation the upper most parent item
2385 // is required. For performance reasons it is checked first whether
2386 // the visible items before or after the current range already
2387 // contain a siblings information which can be used as base.
2388 int rootIndex
= firstIndex
;
2390 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2392 // There is no visible widget before the range, check whether there
2393 // is one after the range:
2394 widget
= m_visibleItems
.value(lastIndex
+ 1);
2396 // The sibling information of the widget may only be used if
2397 // all items of the range have the same number of parents.
2398 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2399 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2400 if (m_model
->expandedParentsCount(i
) != parents
) {
2409 // Performance optimization: Use the sibling information of the visible
2410 // widget beside the given range.
2411 previousSiblings
= widget
->siblingsInformation();
2412 if (previousSiblings
.isEmpty()) {
2415 previousParents
= previousSiblings
.count() - 1;
2416 previousSiblings
.truncate(previousParents
);
2418 // Potentially slow path: Go back to the upper most parent of firstIndex
2419 // to be able to calculate the initial value for the siblings.
2420 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2425 Q_ASSERT(previousParents
>= 0);
2426 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2427 // Update the parent-siblings in case if the current item represents
2428 // a child or an upper parent.
2429 const int currentParents
= m_model
->expandedParentsCount(i
);
2430 Q_ASSERT(currentParents
>= 0);
2431 if (previousParents
< currentParents
) {
2432 previousParents
= currentParents
;
2433 previousSiblings
.resize(currentParents
);
2434 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2435 } else if (previousParents
> currentParents
) {
2436 previousParents
= currentParents
;
2437 previousSiblings
.truncate(currentParents
);
2440 if (i
>= firstIndex
) {
2441 // The index represents a visible item. Apply the parent-siblings
2442 // and update the sibling of the current item.
2443 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2448 QBitArray siblings
= previousSiblings
;
2449 siblings
.resize(siblings
.count() + 1);
2450 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2452 widget
->setSiblingsInformation(siblings
);
2457 bool KItemListView::hasSiblingSuccessor(int index
) const
2459 bool hasSuccessor
= false;
2460 const int parentsCount
= m_model
->expandedParentsCount(index
);
2461 int successorIndex
= index
+ 1;
2463 // Search the next sibling
2464 const int itemCount
= m_model
->count();
2465 while (successorIndex
< itemCount
) {
2466 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2467 if (currentParentsCount
== parentsCount
) {
2468 hasSuccessor
= true;
2470 } else if (currentParentsCount
< parentsCount
) {
2476 if (m_grouped
&& hasSuccessor
) {
2477 // If the sibling is part of another group, don't mark it as
2478 // successor as the group header is between the sibling connections.
2479 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2480 if (m_layouter
->isFirstGroupItem(i
)) {
2481 hasSuccessor
= false;
2487 return hasSuccessor
;
2490 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2494 const int minSpeed
= 4;
2495 const int maxSpeed
= 128;
2496 const int speedLimiter
= 96;
2497 const int autoScrollBorder
= 64;
2499 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2500 // This assures that the autoscrolling speed grows gradually.
2501 const int incLimiter
= 1;
2503 if (pos
< autoScrollBorder
) {
2504 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2505 inc
= qMax(inc
, -maxSpeed
);
2506 inc
= qMax(inc
, oldInc
- incLimiter
);
2507 } else if (pos
> range
- autoScrollBorder
) {
2508 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2509 inc
= qMin(inc
, maxSpeed
);
2510 inc
= qMin(inc
, oldInc
+ incLimiter
);
2516 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2518 const qreal availableSize
= size
- itemMargin
;
2519 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2525 KItemListCreatorBase::~KItemListCreatorBase()
2527 qDeleteAll(m_recycleableWidgets
);
2528 qDeleteAll(m_createdWidgets
);
2531 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2533 m_createdWidgets
.insert(widget
);
2536 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2538 Q_ASSERT(m_createdWidgets
.contains(widget
));
2539 m_createdWidgets
.remove(widget
);
2541 if (m_recycleableWidgets
.count() < 100) {
2542 m_recycleableWidgets
.append(widget
);
2543 widget
->setVisible(false);
2549 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2551 if (m_recycleableWidgets
.isEmpty()) {
2555 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2556 m_createdWidgets
.insert(widget
);
2560 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2564 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2566 widget
->setParentItem(0);
2567 widget
->setOpacity(1.0);
2568 pushRecycleableWidget(widget
);
2571 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2575 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2577 header
->setOpacity(1.0);
2578 pushRecycleableWidget(header
);
2581 #include "kitemlistview.moc"