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"
39 #include <QGraphicsSceneMouseEvent>
40 #include <QGraphicsView>
42 #include <QPropertyAnimation>
44 #include <QStyleOptionRubberBand>
49 #include "kitemlistviewaccessible.h"
52 // Time in ms until reaching the autoscroll margin triggers
53 // an initial autoscrolling
54 const int InitialAutoScrollDelay
= 700;
56 // Delay in ms for triggering the next autoscroll
57 const int RepeatingAutoScrollDelay
= 1000 / 60;
60 #ifndef QT_NO_ACCESSIBILITY
61 QAccessibleInterface
* accessibleInterfaceFactory(const QString
&key
, QObject
*object
)
65 if (KItemListContainer
* container
= qobject_cast
<KItemListContainer
*>(object
)) {
66 return new KItemListContainerAccessible(container
);
67 } else if (KItemListView
* view
= qobject_cast
<KItemListView
*>(object
)) {
68 return new KItemListViewAccessible(view
);
75 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
76 QGraphicsWidget(parent
),
77 m_enabledSelectionToggles(false),
79 m_supportsItemExpanding(false),
81 m_activeTransactions(0),
82 m_endTransactionAnimationHint(Animation
),
88 m_groupHeaderCreator(0),
93 m_sizeHintResolver(0),
98 m_oldMaximumScrollOffset(0),
100 m_oldMaximumItemOffset(0),
101 m_skipAutoScrollForRubberBand(false),
104 m_autoScrollIncrement(0),
105 m_autoScrollTimer(0),
110 setAcceptHoverEvents(true);
112 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
114 m_layouter
= new KItemListViewLayouter(this);
115 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
117 m_animation
= new KItemListViewAnimation(this);
118 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
119 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
121 m_layoutTimer
= new QTimer(this);
122 m_layoutTimer
->setInterval(300);
123 m_layoutTimer
->setSingleShot(true);
124 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
126 m_rubberBand
= new KItemListRubberBand(this);
127 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
129 m_headerWidget
= new KItemListHeaderWidget(this);
130 m_headerWidget
->setVisible(false);
132 m_header
= new KItemListHeader(this);
134 #ifndef QT_NO_ACCESSIBILITY
135 QAccessible::installFactory(accessibleInterfaceFactory
);
140 KItemListView::~KItemListView()
142 // The group headers are children of the widgets created by
143 // widgetCreator(). So it is mandatory to delete the group headers
145 delete m_groupHeaderCreator
;
146 m_groupHeaderCreator
= 0;
148 delete m_widgetCreator
;
151 delete m_sizeHintResolver
;
152 m_sizeHintResolver
= 0;
155 void KItemListView::setScrollOffset(qreal offset
)
161 const qreal previousOffset
= m_layouter
->scrollOffset();
162 if (offset
== previousOffset
) {
166 m_layouter
->setScrollOffset(offset
);
167 m_animation
->setScrollOffset(offset
);
169 // Don't check whether the m_layoutTimer is active: Changing the
170 // scroll offset must always trigger a synchronous layout, otherwise
171 // the smooth-scrolling might get jerky.
172 doLayout(NoAnimation
);
173 onScrollOffsetChanged(offset
, previousOffset
);
176 qreal
KItemListView::scrollOffset() const
178 return m_layouter
->scrollOffset();
181 qreal
KItemListView::maximumScrollOffset() const
183 return m_layouter
->maximumScrollOffset();
186 void KItemListView::setItemOffset(qreal offset
)
188 if (m_layouter
->itemOffset() == offset
) {
192 m_layouter
->setItemOffset(offset
);
193 if (m_headerWidget
->isVisible()) {
194 m_headerWidget
->setOffset(offset
);
197 // Don't check whether the m_layoutTimer is active: Changing the
198 // item offset must always trigger a synchronous layout, otherwise
199 // the smooth-scrolling might get jerky.
200 doLayout(NoAnimation
);
203 qreal
KItemListView::itemOffset() const
205 return m_layouter
->itemOffset();
208 qreal
KItemListView::maximumItemOffset() const
210 return m_layouter
->maximumItemOffset();
213 int KItemListView::maximumVisibleItems() const
215 return m_layouter
->maximumVisibleItems();
218 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
220 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
221 m_visibleRoles
= roles
;
222 onVisibleRolesChanged(roles
, previousRoles
);
224 m_sizeHintResolver
->clearCache();
225 m_layouter
->markAsDirty();
227 if (m_itemSize
.isEmpty()) {
228 m_headerWidget
->setColumns(roles
);
229 updatePreferredColumnWidths();
230 if (!m_headerWidget
->automaticColumnResizing()) {
231 // The column-width of new roles are still 0. Apply the preferred
232 // column-width as default with.
233 foreach (const QByteArray
& role
, m_visibleRoles
) {
234 if (m_headerWidget
->columnWidth(role
) == 0) {
235 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
236 m_headerWidget
->setColumnWidth(role
, width
);
240 applyColumnWidthsFromHeader();
244 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
245 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
246 (roles
.count() <= 1 && previousRoles
.count() > 1));
248 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
249 while (it
.hasNext()) {
251 KItemListWidget
* widget
= it
.value();
252 widget
->setVisibleRoles(roles
);
253 if (alternateBackgroundsChanged
) {
254 updateAlternateBackgroundForWidget(widget
);
258 doLayout(NoAnimation
);
261 QList
<QByteArray
> KItemListView::visibleRoles() const
263 return m_visibleRoles
;
266 void KItemListView::setAutoScroll(bool enabled
)
268 if (enabled
&& !m_autoScrollTimer
) {
269 m_autoScrollTimer
= new QTimer(this);
270 m_autoScrollTimer
->setSingleShot(true);
271 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
272 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
273 } else if (!enabled
&& m_autoScrollTimer
) {
274 delete m_autoScrollTimer
;
275 m_autoScrollTimer
= 0;
279 bool KItemListView::autoScroll() const
281 return m_autoScrollTimer
!= 0;
284 void KItemListView::setEnabledSelectionToggles(bool enabled
)
286 if (m_enabledSelectionToggles
!= enabled
) {
287 m_enabledSelectionToggles
= enabled
;
289 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
290 while (it
.hasNext()) {
292 it
.value()->setEnabledSelectionToggle(enabled
);
297 bool KItemListView::enabledSelectionToggles() const
299 return m_enabledSelectionToggles
;
302 KItemListController
* KItemListView::controller() const
307 KItemModelBase
* KItemListView::model() const
312 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
314 if (m_widgetCreator
) {
315 delete m_widgetCreator
;
317 m_widgetCreator
= widgetCreator
;
320 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
322 if (!m_widgetCreator
) {
323 m_widgetCreator
= defaultWidgetCreator();
325 return m_widgetCreator
;
328 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
330 if (m_groupHeaderCreator
) {
331 delete m_groupHeaderCreator
;
333 m_groupHeaderCreator
= groupHeaderCreator
;
336 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
338 if (!m_groupHeaderCreator
) {
339 m_groupHeaderCreator
= defaultGroupHeaderCreator();
341 return m_groupHeaderCreator
;
344 QSizeF
KItemListView::itemSize() const
349 const KItemListStyleOption
& KItemListView::styleOption() const
351 return m_styleOption
;
354 void KItemListView::setGeometry(const QRectF
& rect
)
356 QGraphicsWidget::setGeometry(rect
);
362 const QSizeF newSize
= rect
.size();
363 if (m_itemSize
.isEmpty()) {
364 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
365 if (m_headerWidget
->automaticColumnResizing()) {
366 applyAutomaticColumnWidths();
368 const qreal requiredWidth
= columnWidthsSum();
369 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
370 m_itemSize
.height());
371 m_layouter
->setItemSize(dynamicItemSize
);
374 // Triggering a synchronous layout is fine from a performance point of view,
375 // as with dynamic item sizes no moving animation must be done.
376 m_layouter
->setSize(newSize
);
377 doLayout(NoAnimation
);
379 const bool animate
= !changesItemGridLayout(newSize
,
380 m_layouter
->itemSize(),
381 m_layouter
->itemMargin());
382 m_layouter
->setSize(newSize
);
385 // Trigger an asynchronous relayout with m_layoutTimer to prevent
386 // performance bottlenecks. If the timer is exceeded, an animated layout
387 // will be triggered.
388 if (!m_layoutTimer
->isActive()) {
389 m_layoutTimer
->start();
392 m_layoutTimer
->stop();
393 doLayout(NoAnimation
);
398 qreal
KItemListView::verticalPageStep() const
400 qreal headerHeight
= 0;
401 if (m_headerWidget
->isVisible()) {
402 headerHeight
= m_headerWidget
->size().height();
404 return size().height() - headerHeight
;
407 int KItemListView::itemAt(const QPointF
& pos
) const
409 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
410 while (it
.hasNext()) {
413 const KItemListWidget
* widget
= it
.value();
414 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
415 if (widget
->contains(mappedPos
)) {
423 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
425 if (!m_enabledSelectionToggles
) {
429 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
431 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
432 if (!selectionToggleRect
.isEmpty()) {
433 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
434 return selectionToggleRect
.contains(mappedPos
);
440 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
442 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
444 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
445 if (!expansionToggleRect
.isEmpty()) {
446 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
447 return expansionToggleRect
.contains(mappedPos
);
453 int KItemListView::firstVisibleIndex() const
455 return m_layouter
->firstVisibleIndex();
458 int KItemListView::lastVisibleIndex() const
460 return m_layouter
->lastVisibleIndex();
463 QSizeF
KItemListView::itemSizeHint(int index
) const
465 return widgetCreator()->itemSizeHint(index
, this);
468 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
470 if (m_supportsItemExpanding
!= supportsExpanding
) {
471 m_supportsItemExpanding
= supportsExpanding
;
472 updateSiblingsInformation();
473 onSupportsItemExpandingChanged(supportsExpanding
);
477 bool KItemListView::supportsItemExpanding() const
479 return m_supportsItemExpanding
;
482 QRectF
KItemListView::itemRect(int index
) const
484 return m_layouter
->itemRect(index
);
487 QRectF
KItemListView::itemContextRect(int index
) const
491 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
493 contextRect
= widget
->iconRect() | widget
->textRect();
494 contextRect
.translate(itemRect(index
).topLeft());
500 void KItemListView::scrollToItem(int index
)
502 QRectF viewGeometry
= geometry();
503 if (m_headerWidget
->isVisible()) {
504 const qreal headerHeight
= m_headerWidget
->size().height();
505 viewGeometry
.adjust(0, headerHeight
, 0, 0);
507 QRectF currentRect
= itemRect(index
);
509 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
510 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
511 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
513 if (!viewGeometry
.contains(currentRect
)) {
514 qreal newOffset
= scrollOffset();
515 if (scrollOrientation() == Qt::Vertical
) {
516 if (currentRect
.top() < viewGeometry
.top()) {
517 newOffset
+= currentRect
.top() - viewGeometry
.top();
518 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
519 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
522 if (currentRect
.left() < viewGeometry
.left()) {
523 newOffset
+= currentRect
.left() - viewGeometry
.left();
524 } else if (currentRect
.right() > viewGeometry
.right()) {
525 newOffset
+= currentRect
.right() - viewGeometry
.right();
529 if (newOffset
!= scrollOffset()) {
530 emit
scrollTo(newOffset
);
535 void KItemListView::beginTransaction()
537 ++m_activeTransactions
;
538 if (m_activeTransactions
== 1) {
539 onTransactionBegin();
543 void KItemListView::endTransaction()
545 --m_activeTransactions
;
546 if (m_activeTransactions
< 0) {
547 m_activeTransactions
= 0;
548 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
551 if (m_activeTransactions
== 0) {
553 doLayout(m_endTransactionAnimationHint
);
554 m_endTransactionAnimationHint
= Animation
;
558 bool KItemListView::isTransactionActive() const
560 return m_activeTransactions
> 0;
563 void KItemListView::setHeaderVisible(bool visible
)
565 if (visible
&& !m_headerWidget
->isVisible()) {
566 QStyleOptionHeader option
;
567 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
570 m_headerWidget
->setPos(0, 0);
571 m_headerWidget
->resize(size().width(), headerSize
.height());
572 m_headerWidget
->setModel(m_model
);
573 m_headerWidget
->setColumns(m_visibleRoles
);
574 m_headerWidget
->setZValue(1);
576 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
577 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
578 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
579 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
580 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
581 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
582 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
583 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
585 m_layouter
->setHeaderHeight(headerSize
.height());
586 m_headerWidget
->setVisible(true);
587 } else if (!visible
&& m_headerWidget
->isVisible()) {
588 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
589 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
590 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
591 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
592 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
593 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
594 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
595 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
597 m_layouter
->setHeaderHeight(0);
598 m_headerWidget
->setVisible(false);
602 bool KItemListView::isHeaderVisible() const
604 return m_headerWidget
->isVisible();
607 KItemListHeader
* KItemListView::header() const
612 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
616 if (indexes
.count() == 1) {
617 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
618 QGraphicsView
* graphicsView
= scene()->views()[0];
619 if (item
&& graphicsView
) {
620 pixmap
= item
->createDragPixmap(0, graphicsView
);
623 // TODO: Not implemented yet. Probably extend the interface
624 // from KItemListWidget::createDragPixmap() to return a pixmap
625 // that can be used for multiple indexes.
631 void KItemListView::editRole(int index
, const QByteArray
& role
)
633 KItemListWidget
* widget
= m_visibleItems
.value(index
);
634 if (!widget
|| m_editingRole
) {
638 m_editingRole
= true;
639 widget
->setEditedRole(role
);
641 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
642 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
643 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
644 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
647 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
649 QGraphicsWidget::paint(painter
, option
, widget
);
651 if (m_rubberBand
->isActive()) {
652 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
653 m_rubberBand
->endPosition()).normalized();
655 const QPointF topLeft
= rubberBandRect
.topLeft();
656 if (scrollOrientation() == Qt::Vertical
) {
657 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
659 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
662 QStyleOptionRubberBand opt
;
663 opt
.initFrom(widget
);
664 opt
.shape
= QRubberBand::Rectangle
;
666 opt
.rect
= rubberBandRect
.toRect();
667 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
670 if (!m_dropIndicator
.isEmpty()) {
671 const QRectF r
= m_dropIndicator
.toRect();
673 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
674 painter
->setPen(color
);
676 // TODO: The following implementation works only for a vertical scroll-orientation
677 // and assumes a height of the m_draggingInsertIndicator of 1.
678 Q_ASSERT(r
.height() == 1);
679 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
682 painter
->setPen(color
);
683 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
687 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
689 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
690 if (!scene()->views().isEmpty()) {
691 m_styleOption
.palette
= scene()->views().at(0)->palette();
694 return QGraphicsItem::itemChange(change
, value
);
697 void KItemListView::setItemSize(const QSizeF
& size
)
699 const QSizeF previousSize
= m_itemSize
;
700 if (size
== previousSize
) {
704 // Skip animations when the number of rows or columns
705 // are changed in the grid layout. Although the animation
706 // engine can handle this usecase, it looks obtrusive.
707 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
709 m_layouter
->itemMargin());
711 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
712 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
713 (!m_itemSize
.isEmpty() && size
.isEmpty()));
717 if (alternateBackgroundsChanged
) {
718 // For an empty item size alternate backgrounds are drawn if more than
719 // one role is shown. Assure that the backgrounds for visible items are
720 // updated when changing the size in this context.
721 updateAlternateBackgrounds();
724 if (size
.isEmpty()) {
725 if (m_headerWidget
->automaticColumnResizing()) {
726 updatePreferredColumnWidths();
728 // Only apply the changed height and respect the header widths
730 const qreal currentWidth
= m_layouter
->itemSize().width();
731 const QSizeF
newSize(currentWidth
, size
.height());
732 m_layouter
->setItemSize(newSize
);
735 m_layouter
->setItemSize(size
);
738 m_sizeHintResolver
->clearCache();
739 doLayout(animate
? Animation
: NoAnimation
);
740 onItemSizeChanged(size
, previousSize
);
743 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
745 const KItemListStyleOption previousOption
= m_styleOption
;
746 m_styleOption
= option
;
749 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
750 if (margin
!= m_layouter
->itemMargin()) {
751 // Skip animations when the number of rows or columns
752 // are changed in the grid layout. Although the animation
753 // engine can handle this usecase, it looks obtrusive.
754 animate
= !changesItemGridLayout(m_layouter
->size(),
755 m_layouter
->itemSize(),
757 m_layouter
->setItemMargin(margin
);
761 updateGroupHeaderHeight();
764 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
765 // Animating a change of the maximum text size just results in expensive
766 // temporary eliding and clipping operations and does not look good visually.
770 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
771 while (it
.hasNext()) {
773 it
.value()->setStyleOption(option
);
776 m_sizeHintResolver
->clearCache();
777 m_layouter
->markAsDirty();
778 doLayout(animate
? Animation
: NoAnimation
);
780 if (m_itemSize
.isEmpty()) {
781 updatePreferredColumnWidths();
784 onStyleOptionChanged(option
, previousOption
);
787 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
789 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
790 if (orientation
== previousOrientation
) {
794 m_layouter
->setScrollOrientation(orientation
);
795 m_animation
->setScrollOrientation(orientation
);
796 m_sizeHintResolver
->clearCache();
799 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
800 while (it
.hasNext()) {
802 it
.value()->setScrollOrientation(orientation
);
804 updateGroupHeaderHeight();
808 doLayout(NoAnimation
);
810 onScrollOrientationChanged(orientation
, previousOrientation
);
811 emit
scrollOrientationChanged(orientation
, previousOrientation
);
814 Qt::Orientation
KItemListView::scrollOrientation() const
816 return m_layouter
->scrollOrientation();
819 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
824 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
829 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
834 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
836 Q_UNUSED(changedRoles
);
840 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
846 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
852 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
858 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
864 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
870 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
876 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
882 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
884 Q_UNUSED(supportsExpanding
);
887 void KItemListView::onTransactionBegin()
891 void KItemListView::onTransactionEnd()
895 bool KItemListView::event(QEvent
* event
)
897 // Forward all events to the controller and handle them there
898 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
902 return QGraphicsWidget::event(event
);
905 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
907 m_mousePos
= transform().map(event
->pos());
911 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
913 QGraphicsWidget::mouseMoveEvent(event
);
915 m_mousePos
= transform().map(event
->pos());
916 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
917 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
921 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
923 event
->setAccepted(true);
927 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
929 QGraphicsWidget::dragMoveEvent(event
);
931 m_mousePos
= transform().map(event
->pos());
932 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
933 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
937 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
939 QGraphicsWidget::dragLeaveEvent(event
);
940 setAutoScroll(false);
943 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
945 QGraphicsWidget::dropEvent(event
);
946 setAutoScroll(false);
949 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
951 return m_visibleItems
.values();
954 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
956 if (m_itemSize
.isEmpty()) {
957 updatePreferredColumnWidths(itemRanges
);
960 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
961 if (hasMultipleRanges
) {
965 m_layouter
->markAsDirty();
967 m_sizeHintResolver
->itemsInserted(itemRanges
);
969 int previouslyInsertedCount
= 0;
970 foreach (const KItemRange
& range
, itemRanges
) {
971 // range.index is related to the model before anything has been inserted.
972 // As in each loop the current item-range gets inserted the index must
973 // be increased by the already previously inserted items.
974 const int index
= range
.index
+ previouslyInsertedCount
;
975 const int count
= range
.count
;
976 if (index
< 0 || count
<= 0) {
977 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
980 previouslyInsertedCount
+= count
;
982 // Determine which visible items must be moved
983 QList
<int> itemsToMove
;
984 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
985 while (it
.hasNext()) {
987 const int visibleItemIndex
= it
.key();
988 if (visibleItemIndex
>= index
) {
989 itemsToMove
.append(visibleItemIndex
);
993 // Update the indexes of all KItemListWidget instances that are located
994 // after the inserted items. It is important to adjust the indexes in the order
995 // from the highest index to the lowest index to prevent overlaps when setting the new index.
997 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
998 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1000 const int newIndex
= widget
->index() + count
;
1001 if (hasMultipleRanges
) {
1002 setWidgetIndex(widget
, newIndex
);
1004 // Try to animate the moving of the item
1005 moveWidgetToIndex(widget
, newIndex
);
1009 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1010 // Check whether a scrollbar is required to show the inserted items. In this case
1011 // the size of the layouter will be decreased before calling doLayout(): This prevents
1012 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1013 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1014 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1015 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1016 if (decreaseLayouterSize
) {
1017 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1018 QSizeF layouterSize
= m_layouter
->size();
1019 if (verticalScrollOrientation
) {
1020 layouterSize
.rwidth() -= scrollBarExtent
;
1022 layouterSize
.rheight() -= scrollBarExtent
;
1024 m_layouter
->setSize(layouterSize
);
1028 if (!hasMultipleRanges
) {
1029 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1030 updateSiblingsInformation();
1035 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1038 if (hasMultipleRanges
) {
1039 m_endTransactionAnimationHint
= NoAnimation
;
1042 updateSiblingsInformation();
1045 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1046 // In case if items of the same group have been inserted before an item that
1047 // currently represents the first item of the group, the group header of
1048 // this item must be removed.
1049 updateVisibleGroupHeaders();
1052 if (useAlternateBackgrounds()) {
1053 updateAlternateBackgrounds();
1057 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1059 if (m_itemSize
.isEmpty()) {
1060 // Don't pass the item-range: The preferred column-widths of
1061 // all items must be adjusted when removing items.
1062 updatePreferredColumnWidths();
1065 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1066 if (hasMultipleRanges
) {
1070 m_layouter
->markAsDirty();
1072 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1074 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1075 const KItemRange
& range
= itemRanges
[i
];
1076 const int index
= range
.index
;
1077 const int count
= range
.count
;
1078 if (index
< 0 || count
<= 0) {
1079 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1083 const int firstRemovedIndex
= index
;
1084 const int lastRemovedIndex
= index
+ count
- 1;
1086 // Remeber which items have to be moved because they are behind the removed range.
1087 QVector
<int> itemsToMove
;
1089 // Remove all KItemListWidget instances that got deleted
1090 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1091 const int i
= widget
->index();
1092 if (i
< firstRemovedIndex
) {
1094 } else if (i
> lastRemovedIndex
) {
1095 itemsToMove
.append(i
);
1099 m_animation
->stop(widget
);
1100 // Stopping the animation might lead to recycling the widget if
1101 // it is invisible (see slotAnimationFinished()).
1102 // Check again whether it is still visible:
1103 if (!m_visibleItems
.contains(i
)) {
1107 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1108 // Remove the widget without animation
1109 recycleWidget(widget
);
1111 // Animate the removing of the items. Special case: When removing an item there
1112 // is no valid model index available anymore. For the
1113 // remove-animation the item gets removed from m_visibleItems but the widget
1114 // will stay alive until the animation has been finished and will
1115 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1116 m_visibleItems
.remove(i
);
1117 widget
->setIndex(-1);
1118 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1122 // Update the indexes of all KItemListWidget instances that are located
1123 // after the deleted items. It is important to update them in ascending
1124 // order to prevent overlaps when setting the new index.
1125 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1126 foreach (int i
, itemsToMove
) {
1127 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1129 const int newIndex
= i
- count
;
1130 if (hasMultipleRanges
) {
1131 setWidgetIndex(widget
, newIndex
);
1133 // Try to animate the moving of the item
1134 moveWidgetToIndex(widget
, newIndex
);
1138 if (!hasMultipleRanges
) {
1139 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1140 // assumes an updated geometry. If items are removed during an active transaction,
1141 // the transaction will be temporary deactivated so that doLayout() triggers a
1142 // geometry update if necessary.
1143 const int activeTransactions
= m_activeTransactions
;
1144 m_activeTransactions
= 0;
1145 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1146 m_activeTransactions
= activeTransactions
;
1147 updateSiblingsInformation();
1152 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1155 if (hasMultipleRanges
) {
1156 m_endTransactionAnimationHint
= NoAnimation
;
1158 updateSiblingsInformation();
1161 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1162 // In case if the first item of a group has been removed, the group header
1163 // must be applied to the next visible item.
1164 updateVisibleGroupHeaders();
1167 if (useAlternateBackgrounds()) {
1168 updateAlternateBackgrounds();
1172 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1174 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1175 m_layouter
->markAsDirty();
1178 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1181 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1182 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1184 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1185 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1187 updateWidgetProperties(widget
, index
);
1188 initializeItemListWidget(widget
);
1192 doLayout(NoAnimation
);
1193 updateSiblingsInformation();
1196 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1197 const QSet
<QByteArray
>& roles
)
1199 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1200 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1201 updatePreferredColumnWidths(itemRanges
);
1204 foreach (const KItemRange
& itemRange
, itemRanges
) {
1205 const int index
= itemRange
.index
;
1206 const int count
= itemRange
.count
;
1208 if (updateSizeHints
) {
1209 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1210 m_layouter
->markAsDirty();
1212 if (!m_layoutTimer
->isActive()) {
1213 m_layoutTimer
->start();
1217 // Apply the changed roles to the visible item-widgets
1218 const int lastIndex
= index
+ count
- 1;
1219 for (int i
= index
; i
<= lastIndex
; ++i
) {
1220 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1222 widget
->setData(m_model
->data(i
), roles
);
1226 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1227 // The sort-role has been changed which might result
1228 // in modified group headers
1229 updateVisibleGroupHeaders();
1230 doLayout(NoAnimation
);
1233 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1236 void KItemListView::slotGroupedSortingChanged(bool current
)
1238 m_grouped
= current
;
1239 m_layouter
->markAsDirty();
1242 updateGroupHeaderHeight();
1244 // Clear all visible headers. Note that the QHashIterator takes a copy of
1245 // m_visibleGroups. Therefore, it remains valid even if items are removed
1246 // from m_visibleGroups in recycleGroupHeaderForWidget().
1247 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1248 while (it
.hasNext()) {
1250 recycleGroupHeaderForWidget(it
.key());
1252 Q_ASSERT(m_visibleGroups
.isEmpty());
1255 if (useAlternateBackgrounds()) {
1256 // Changing the group mode requires to update the alternate backgrounds
1257 // as with the enabled group mode the altering is done on base of the first
1259 updateAlternateBackgrounds();
1261 updateSiblingsInformation();
1262 doLayout(NoAnimation
);
1265 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1270 updateVisibleGroupHeaders();
1271 doLayout(NoAnimation
);
1275 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1280 updateVisibleGroupHeaders();
1281 doLayout(NoAnimation
);
1285 void KItemListView::slotCurrentChanged(int current
, int previous
)
1289 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1290 if (previousWidget
) {
1291 previousWidget
->setCurrent(false);
1294 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1295 if (currentWidget
) {
1296 currentWidget
->setCurrent(true);
1298 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1301 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1305 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1306 while (it
.hasNext()) {
1308 const int index
= it
.key();
1309 KItemListWidget
* widget
= it
.value();
1310 widget
->setSelected(current
.contains(index
));
1314 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1315 KItemListViewAnimation::AnimationType type
)
1317 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1318 Q_ASSERT(itemListWidget
);
1321 case KItemListViewAnimation::DeleteAnimation
: {
1322 // As we recycle the widget in this case it is important to assure that no
1323 // other animation has been started. This is a convention in KItemListView and
1324 // not a requirement defined by KItemListViewAnimation.
1325 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1327 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1328 // by m_visibleWidgets and must be deleted manually after the animation has
1330 recycleGroupHeaderForWidget(itemListWidget
);
1331 widgetCreator()->recycle(itemListWidget
);
1335 case KItemListViewAnimation::CreateAnimation
:
1336 case KItemListViewAnimation::MovingAnimation
:
1337 case KItemListViewAnimation::ResizeAnimation
: {
1338 const int index
= itemListWidget
->index();
1339 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1340 (index
> m_layouter
->lastVisibleIndex());
1341 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1342 recycleWidget(itemListWidget
);
1351 void KItemListView::slotLayoutTimerFinished()
1353 m_layouter
->setSize(geometry().size());
1354 doLayout(Animation
);
1357 void KItemListView::slotRubberBandPosChanged()
1362 void KItemListView::slotRubberBandActivationChanged(bool active
)
1365 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1366 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1367 m_skipAutoScrollForRubberBand
= true;
1369 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1370 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1371 m_skipAutoScrollForRubberBand
= false;
1377 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1379 qreal previousWidth
)
1382 Q_UNUSED(currentWidth
);
1383 Q_UNUSED(previousWidth
);
1385 m_headerWidget
->setAutomaticColumnResizing(false);
1386 applyColumnWidthsFromHeader();
1387 doLayout(NoAnimation
);
1390 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1394 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1396 const QList
<QByteArray
> previous
= m_visibleRoles
;
1398 QList
<QByteArray
> current
= m_visibleRoles
;
1399 current
.removeAt(previousIndex
);
1400 current
.insert(currentIndex
, role
);
1402 setVisibleRoles(current
);
1404 emit
visibleRolesChanged(current
, previous
);
1407 void KItemListView::triggerAutoScrolling()
1409 if (!m_autoScrollTimer
) {
1414 int visibleSize
= 0;
1415 if (scrollOrientation() == Qt::Vertical
) {
1416 pos
= m_mousePos
.y();
1417 visibleSize
= size().height();
1419 pos
= m_mousePos
.x();
1420 visibleSize
= size().width();
1423 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1424 m_autoScrollIncrement
= 0;
1427 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1428 if (m_autoScrollIncrement
== 0) {
1429 // The mouse position is not above an autoscroll margin (the autoscroll timer
1430 // will be restarted in mouseMoveEvent())
1431 m_autoScrollTimer
->stop();
1435 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1436 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1437 // if the direction of the rubberband is similar to the autoscroll direction. This
1438 // prevents that starting to create a rubberband within the autoscroll margins starts
1439 // an autoscrolling.
1441 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1442 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1443 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1444 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1445 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1446 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1447 // been moved up although the autoscroll direction might be down)
1448 m_autoScrollTimer
->stop();
1453 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1454 // the autoscrolling may not get skipped anymore until a new rubberband is created
1455 m_skipAutoScrollForRubberBand
= false;
1457 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1458 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1459 setScrollOffset(newScrollOffset
);
1461 // Trigger the autoscroll timer which will periodically call
1462 // triggerAutoScrolling()
1463 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1466 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1468 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1470 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1471 Q_ASSERT(groupHeader
);
1472 updateGroupHeaderLayout(widget
);
1475 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1477 disconnectRoleEditingSignals(index
);
1479 emit
roleEditingCanceled(index
, role
, value
);
1480 m_editingRole
= false;
1483 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1485 disconnectRoleEditingSignals(index
);
1487 emit
roleEditingFinished(index
, role
, value
);
1488 m_editingRole
= false;
1491 void KItemListView::setController(KItemListController
* controller
)
1493 if (m_controller
!= controller
) {
1494 KItemListController
* previous
= m_controller
;
1496 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1497 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1498 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1501 m_controller
= controller
;
1504 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1505 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1506 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1509 onControllerChanged(controller
, previous
);
1513 void KItemListView::setModel(KItemModelBase
* model
)
1515 if (m_model
== model
) {
1519 KItemModelBase
* previous
= m_model
;
1522 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1523 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1524 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1525 this, SLOT(slotItemsInserted(KItemRangeList
)));
1526 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1527 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1528 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1529 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1530 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1531 this, SLOT(slotGroupedSortingChanged(bool)));
1532 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1533 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1534 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1535 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1537 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1541 m_layouter
->setModel(model
);
1542 m_grouped
= model
->groupedSorting();
1545 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1546 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1547 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1548 this, SLOT(slotItemsInserted(KItemRangeList
)));
1549 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1550 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1551 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1552 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1553 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1554 this, SLOT(slotGroupedSortingChanged(bool)));
1555 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1556 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1557 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1558 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1560 const int itemCount
= m_model
->count();
1561 if (itemCount
> 0) {
1562 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1566 onModelChanged(model
, previous
);
1569 KItemListRubberBand
* KItemListView::rubberBand() const
1571 return m_rubberBand
;
1574 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1576 if (m_layoutTimer
->isActive()) {
1577 m_layoutTimer
->stop();
1580 if (m_activeTransactions
> 0) {
1581 if (hint
== NoAnimation
) {
1582 // As soon as at least one property change should be done without animation,
1583 // the whole transaction will be marked as not animated.
1584 m_endTransactionAnimationHint
= NoAnimation
;
1589 if (!m_model
|| m_model
->count() < 0) {
1593 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1594 if (firstVisibleIndex
< 0) {
1595 emitOffsetChanges();
1599 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1600 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1601 // is still shown if the maximum offset got decreased.
1602 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1603 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1604 if (scrollOffset() > maxOffsetToShowFullRange
) {
1605 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1606 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1609 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1611 int firstSibblingIndex
= -1;
1612 int lastSibblingIndex
= -1;
1613 const bool supportsExpanding
= supportsItemExpanding();
1615 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1617 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1618 // instances from invisible items are reused. If no reusable items are
1619 // found then new KItemListWidget instances get created.
1620 const bool animate
= (hint
== Animation
);
1621 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1622 bool applyNewPos
= true;
1623 bool wasHidden
= false;
1625 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1626 const QPointF newPos
= itemBounds
.topLeft();
1627 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1630 if (!reusableItems
.isEmpty()) {
1631 // Reuse a KItemListWidget instance from an invisible item
1632 const int oldIndex
= reusableItems
.takeLast();
1633 widget
= m_visibleItems
.value(oldIndex
);
1634 setWidgetIndex(widget
, i
);
1635 updateWidgetProperties(widget
, i
);
1636 initializeItemListWidget(widget
);
1638 // No reusable KItemListWidget instance is available, create a new one
1639 widget
= createWidget(i
);
1641 widget
->resize(itemBounds
.size());
1643 if (animate
&& changedCount
< 0) {
1644 // Items have been deleted.
1645 if (i
>= changedIndex
) {
1646 // The item is located behind the removed range. Move the
1647 // created item to the imaginary old position outside the
1648 // view. It will get animated to the new position later.
1649 const int previousIndex
= i
- changedCount
;
1650 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1651 if (itemRect
.isEmpty()) {
1652 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1653 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1654 widget
->setPos(invisibleOldPos
);
1656 widget
->setPos(itemRect
.topLeft());
1658 applyNewPos
= false;
1662 if (supportsExpanding
&& changedCount
== 0) {
1663 if (firstSibblingIndex
< 0) {
1664 firstSibblingIndex
= i
;
1666 lastSibblingIndex
= i
;
1671 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1672 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1673 applyNewPos
= false;
1676 const bool itemsRemoved
= (changedCount
< 0);
1677 const bool itemsInserted
= (changedCount
> 0);
1678 if (itemsRemoved
&& (i
>= changedIndex
)) {
1679 // The item is located after the removed items. Animate the moving of the position.
1680 applyNewPos
= !moveWidget(widget
, newPos
);
1681 } else if (itemsInserted
&& i
>= changedIndex
) {
1682 // The item is located after the first inserted item
1683 if (i
<= changedIndex
+ changedCount
- 1) {
1684 // The item is an inserted item. Animate the appearing of the item.
1685 // For performance reasons no animation is done when changedCount is equal
1686 // to all available items.
1687 if (changedCount
< m_model
->count()) {
1688 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1690 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1691 // The item was already there before, so animate the moving of the position.
1692 // No moving animation is done if the item is animated by a create animation: This
1693 // prevents a "move animation mess" when inserting several ranges in parallel.
1694 applyNewPos
= !moveWidget(widget
, newPos
);
1696 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1697 // The size of the view might have been changed. Animate the moving of the position.
1698 applyNewPos
= !moveWidget(widget
, newPos
);
1701 m_animation
->stop(widget
);
1705 widget
->setPos(newPos
);
1708 Q_ASSERT(widget
->index() == i
);
1709 widget
->setVisible(true);
1711 if (widget
->size() != itemBounds
.size()) {
1712 // Resize the widget for the item to the changed size.
1714 // If a dynamic item size is used then no animation is done in the direction
1715 // of the dynamic size.
1716 if (m_itemSize
.width() <= 0) {
1717 // The width is dynamic, apply the new width without animation.
1718 widget
->resize(itemBounds
.width(), widget
->size().height());
1719 } else if (m_itemSize
.height() <= 0) {
1720 // The height is dynamic, apply the new height without animation.
1721 widget
->resize(widget
->size().width(), itemBounds
.height());
1723 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1725 widget
->resize(itemBounds
.size());
1729 // Updating the cell-information must be done as last step: The decision whether the
1730 // moving-animation should be started at all is based on the previous cell-information.
1731 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1732 m_visibleCells
.insert(i
, cell
);
1735 // Delete invisible KItemListWidget instances that have not been reused
1736 foreach (int index
, reusableItems
) {
1737 recycleWidget(m_visibleItems
.value(index
));
1740 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1741 Q_ASSERT(lastSibblingIndex
>= 0);
1742 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1746 // Update the layout of all visible group headers
1747 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1748 while (it
.hasNext()) {
1750 updateGroupHeaderLayout(it
.key());
1754 emitOffsetChanges();
1757 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1758 int lastVisibleIndex
,
1759 LayoutAnimationHint hint
)
1761 // Determine all items that are completely invisible and might be
1762 // reused for items that just got (at least partly) visible. If the
1763 // animation hint is set to 'Animation' items that do e.g. an animated
1764 // moving of their position are not marked as invisible: This assures
1765 // that a scrolling inside the view can be done without breaking an animation.
1769 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1770 while (it
.hasNext()) {
1773 KItemListWidget
* widget
= it
.value();
1774 const int index
= widget
->index();
1775 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1778 if (m_animation
->isStarted(widget
)) {
1779 if (hint
== NoAnimation
) {
1780 // Stopping the animation will call KItemListView::slotAnimationFinished()
1781 // and the widget will be recycled if necessary there.
1782 m_animation
->stop(widget
);
1785 widget
->setVisible(false);
1786 items
.append(index
);
1789 recycleGroupHeaderForWidget(widget
);
1798 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1800 if (widget
->pos() == newPos
) {
1804 bool startMovingAnim
= false;
1806 if (m_itemSize
.isEmpty()) {
1807 // The items are not aligned in a grid but either as columns or rows.
1808 startMovingAnim
= true;
1810 // When having a grid the moving-animation should only be started, if it is done within
1811 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1812 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1813 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1814 const int index
= widget
->index();
1815 const Cell cell
= m_visibleCells
.value(index
);
1816 if (cell
.column
>= 0 && cell
.row
>= 0) {
1817 if (scrollOrientation() == Qt::Vertical
) {
1818 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1820 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1825 if (startMovingAnim
) {
1826 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1830 m_animation
->stop(widget
);
1831 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1835 void KItemListView::emitOffsetChanges()
1837 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1838 if (m_oldScrollOffset
!= newScrollOffset
) {
1839 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1840 m_oldScrollOffset
= newScrollOffset
;
1843 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1844 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1845 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1846 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1849 const qreal newItemOffset
= m_layouter
->itemOffset();
1850 if (m_oldItemOffset
!= newItemOffset
) {
1851 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1852 m_oldItemOffset
= newItemOffset
;
1855 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1856 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1857 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1858 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1862 KItemListWidget
* KItemListView::createWidget(int index
)
1864 KItemListWidget
* widget
= widgetCreator()->create(this);
1865 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1867 m_visibleItems
.insert(index
, widget
);
1868 m_visibleCells
.insert(index
, Cell());
1869 updateWidgetProperties(widget
, index
);
1870 initializeItemListWidget(widget
);
1874 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1877 recycleGroupHeaderForWidget(widget
);
1880 const int index
= widget
->index();
1881 m_visibleItems
.remove(index
);
1882 m_visibleCells
.remove(index
);
1884 widgetCreator()->recycle(widget
);
1887 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1889 const int oldIndex
= widget
->index();
1890 m_visibleItems
.remove(oldIndex
);
1891 m_visibleCells
.remove(oldIndex
);
1893 m_visibleItems
.insert(index
, widget
);
1894 m_visibleCells
.insert(index
, Cell());
1896 widget
->setIndex(index
);
1899 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1901 const int oldIndex
= widget
->index();
1902 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1904 setWidgetIndex(widget
, index
);
1906 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1907 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1908 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1909 (!vertical
&& oldCell
.column
== newCell
.column
);
1911 m_visibleCells
.insert(index
, newCell
);
1915 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1918 case LayouterSize
: m_layouter
->setSize(size
); break;
1919 case ItemSize
: m_layouter
->setItemSize(size
); break;
1924 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1926 widget
->setVisibleRoles(m_visibleRoles
);
1927 updateWidgetColumnWidths(widget
);
1928 widget
->setStyleOption(m_styleOption
);
1930 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1931 widget
->setCurrent(index
== selectionManager
->currentItem());
1932 widget
->setSelected(selectionManager
->isSelected(index
));
1933 widget
->setHovered(false);
1934 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1935 widget
->setIndex(index
);
1936 widget
->setData(m_model
->data(index
));
1937 widget
->setSiblingsInformation(QBitArray());
1938 updateAlternateBackgroundForWidget(widget
);
1941 updateGroupHeaderForWidget(widget
);
1945 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1947 Q_ASSERT(m_grouped
);
1949 const int index
= widget
->index();
1950 if (!m_layouter
->isFirstGroupItem(index
)) {
1951 // The widget does not represent the first item of a group
1952 // and hence requires no header
1953 recycleGroupHeaderForWidget(widget
);
1957 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1958 if (groups
.isEmpty() || !groupHeaderCreator()) {
1962 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1964 groupHeader
= groupHeaderCreator()->create(this);
1965 groupHeader
->setParentItem(widget
);
1966 m_visibleGroups
.insert(widget
, groupHeader
);
1967 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1969 Q_ASSERT(groupHeader
->parentItem() == widget
);
1971 const int groupIndex
= groupIndexForItem(index
);
1972 Q_ASSERT(groupIndex
>= 0);
1973 groupHeader
->setData(groups
.at(groupIndex
).second
);
1974 groupHeader
->setRole(model()->sortRole());
1975 groupHeader
->setStyleOption(m_styleOption
);
1976 groupHeader
->setScrollOrientation(scrollOrientation());
1977 groupHeader
->setItemIndex(index
);
1979 groupHeader
->show();
1982 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1984 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1985 Q_ASSERT(groupHeader
);
1987 const int index
= widget
->index();
1988 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1989 const QRectF itemRect
= m_layouter
->itemRect(index
);
1991 // The group-header is a child of the itemlist widget. Translate the
1992 // group header position to the relative position.
1993 if (scrollOrientation() == Qt::Vertical
) {
1994 // In the vertical scroll orientation the group header should always span
1995 // the whole width no matter which temporary position the parent widget
1996 // has. In this case the x-position and width will be adjusted manually.
1997 const qreal x
= -widget
->x() - itemOffset();
1998 const qreal width
= maximumItemOffset();
1999 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2000 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2002 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2003 groupHeader
->resize(groupHeaderRect
.size());
2007 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2009 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2011 header
->setParentItem(0);
2012 groupHeaderCreator()->recycle(header
);
2013 m_visibleGroups
.remove(widget
);
2014 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2018 void KItemListView::updateVisibleGroupHeaders()
2020 Q_ASSERT(m_grouped
);
2021 m_layouter
->markAsDirty();
2023 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2024 while (it
.hasNext()) {
2026 updateGroupHeaderForWidget(it
.value());
2030 int KItemListView::groupIndexForItem(int index
) const
2032 Q_ASSERT(m_grouped
);
2034 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2035 if (groups
.isEmpty()) {
2040 int max
= groups
.count() - 1;
2043 mid
= (min
+ max
) / 2;
2044 if (index
> groups
[mid
].first
) {
2049 } while (groups
[mid
].first
!= index
&& min
<= max
);
2052 while (groups
[mid
].first
> index
&& mid
> 0) {
2060 void KItemListView::updateAlternateBackgrounds()
2062 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2063 while (it
.hasNext()) {
2065 updateAlternateBackgroundForWidget(it
.value());
2069 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2071 bool enabled
= useAlternateBackgrounds();
2073 const int index
= widget
->index();
2074 enabled
= (index
& 0x1) > 0;
2076 const int groupIndex
= groupIndexForItem(index
);
2077 if (groupIndex
>= 0) {
2078 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2079 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2080 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2081 enabled
= (relativeIndex
& 0x1) > 0;
2085 widget
->setAlternateBackground(enabled
);
2088 bool KItemListView::useAlternateBackgrounds() const
2090 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2093 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2095 QElapsedTimer timer
;
2098 QHash
<QByteArray
, qreal
> widths
;
2100 // Calculate the minimum width for each column that is required
2101 // to show the headline unclipped.
2102 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2103 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2104 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2105 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2106 const QString headerText
= m_model
->roleDescription(visibleRole
);
2107 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2108 widths
.insert(visibleRole
, headerWidth
);
2111 // Calculate the preferred column withs for each item and ignore values
2112 // smaller than the width for showing the headline unclipped.
2113 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2114 int calculatedItemCount
= 0;
2115 bool maxTimeExceeded
= false;
2116 foreach (const KItemRange
& itemRange
, itemRanges
) {
2117 const int startIndex
= itemRange
.index
;
2118 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2120 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2121 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2122 qreal maxWidth
= widths
.value(visibleRole
, 0);
2123 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2124 maxWidth
= qMax(width
, maxWidth
);
2125 widths
.insert(visibleRole
, maxWidth
);
2128 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2129 // When having several thousands of items calculating the sizes can get
2130 // very expensive. We accept a possibly too small role-size in favour
2131 // of having no blocking user interface.
2132 maxTimeExceeded
= true;
2135 ++calculatedItemCount
;
2137 if (maxTimeExceeded
) {
2145 void KItemListView::applyColumnWidthsFromHeader()
2147 // Apply the new size to the layouter
2148 const qreal requiredWidth
= columnWidthsSum();
2149 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2150 m_itemSize
.height());
2151 m_layouter
->setItemSize(dynamicItemSize
);
2153 // Update the role sizes for all visible widgets
2154 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2155 while (it
.hasNext()) {
2157 updateWidgetColumnWidths(it
.value());
2161 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2163 foreach (const QByteArray
& role
, m_visibleRoles
) {
2164 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2168 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2170 Q_ASSERT(m_itemSize
.isEmpty());
2171 const int itemCount
= m_model
->count();
2172 int rangesItemCount
= 0;
2173 foreach (const KItemRange
& range
, itemRanges
) {
2174 rangesItemCount
+= range
.count
;
2177 if (itemCount
== rangesItemCount
) {
2178 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2179 foreach (const QByteArray
& role
, m_visibleRoles
) {
2180 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2183 // Only a sub range of the roles need to be determined.
2184 // The chances are good that the widths of the sub ranges
2185 // already fit into the available widths and hence no
2186 // expensive update might be required.
2187 bool changed
= false;
2189 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2190 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2191 while (it
.hasNext()) {
2193 const QByteArray
& role
= it
.key();
2194 const qreal updatedWidth
= it
.value();
2195 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2196 if (updatedWidth
> currentWidth
) {
2197 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2203 // All the updated sizes are smaller than the current sizes and no change
2204 // of the stretched roles-widths is required
2209 if (m_headerWidget
->automaticColumnResizing()) {
2210 applyAutomaticColumnWidths();
2214 void KItemListView::updatePreferredColumnWidths()
2217 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2221 void KItemListView::applyAutomaticColumnWidths()
2223 Q_ASSERT(m_itemSize
.isEmpty());
2224 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2225 if (m_visibleRoles
.isEmpty()) {
2229 // Calculate the maximum size of an item by considering the
2230 // visible role sizes and apply them to the layouter. If the
2231 // size does not use the available view-size the size of the
2232 // first role will get stretched.
2234 foreach (const QByteArray
& role
, m_visibleRoles
) {
2235 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2236 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2239 const QByteArray firstRole
= m_visibleRoles
.first();
2240 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2241 QSizeF dynamicItemSize
= m_itemSize
;
2243 qreal requiredWidth
= columnWidthsSum();
2244 const qreal availableWidth
= size().width();
2245 if (requiredWidth
< availableWidth
) {
2246 // Stretch the first column to use the whole remaining width
2247 firstColumnWidth
+= availableWidth
- requiredWidth
;
2248 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2249 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2250 // Shrink the first column to be able to show as much other
2251 // columns as possible
2252 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2254 // TODO: A proper calculation of the minimum width depends on the implementation
2255 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2257 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2258 if (shrinkedFirstColumnWidth
< minWidth
) {
2259 shrinkedFirstColumnWidth
= minWidth
;
2262 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2263 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2266 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2268 m_layouter
->setItemSize(dynamicItemSize
);
2270 // Update the role sizes for all visible widgets
2271 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2272 while (it
.hasNext()) {
2274 updateWidgetColumnWidths(it
.value());
2278 qreal
KItemListView::columnWidthsSum() const
2280 qreal widthsSum
= 0;
2281 foreach (const QByteArray
& role
, m_visibleRoles
) {
2282 widthsSum
+= m_headerWidget
->columnWidth(role
);
2287 QRectF
KItemListView::headerBoundaries() const
2289 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2292 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2293 const QSizeF
& newItemSize
,
2294 const QSizeF
& newItemMargin
) const
2296 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2300 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2301 const qreal itemWidth
= m_layouter
->itemSize().width();
2302 if (itemWidth
> 0) {
2303 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2304 newItemSize
.width(),
2305 newItemMargin
.width());
2306 if (m_model
->count() > newColumnCount
) {
2307 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2309 m_layouter
->itemMargin().width());
2310 return oldColumnCount
!= newColumnCount
;
2314 const qreal itemHeight
= m_layouter
->itemSize().height();
2315 if (itemHeight
> 0) {
2316 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2317 newItemSize
.height(),
2318 newItemMargin
.height());
2319 if (m_model
->count() > newRowCount
) {
2320 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2322 m_layouter
->itemMargin().height());
2323 return oldRowCount
!= newRowCount
;
2331 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2333 if (m_itemSize
.isEmpty()) {
2334 // We have only columns or only rows, but no grid: An animation is usually
2335 // welcome when inserting or removing items.
2336 return !supportsItemExpanding();
2339 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2343 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2344 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2345 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2346 // Only animate if up to 2/3 of a row or column are inserted or removed
2347 return changedItemCount
<= maximum
* 2 / 3;
2351 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2353 const QSizeF oldSize
= m_layouter
->size();
2355 m_layouter
->setSize(size
);
2356 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2357 m_layouter
->setSize(oldSize
);
2359 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2360 : maxOffset
> size
.width();
2363 int KItemListView::showDropIndicator(const QPointF
& pos
)
2365 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2366 while (it
.hasNext()) {
2368 const KItemListWidget
* widget
= it
.value();
2370 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2371 const QRectF rect
= itemRect(widget
->index());
2372 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2373 if (m_model
->supportsDropping(widget
->index())) {
2374 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2375 const int gap
= qMax(4.0, 0.3 * rect
.height());
2376 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2381 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2382 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2384 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2385 if (m_dropIndicator
!= draggingInsertIndicator
) {
2386 m_dropIndicator
= draggingInsertIndicator
;
2390 int index
= widget
->index();
2398 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2399 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2402 void KItemListView::hideDropIndicator()
2404 if (!m_dropIndicator
.isNull()) {
2405 m_dropIndicator
= QRectF();
2410 void KItemListView::updateGroupHeaderHeight()
2412 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2413 qreal groupHeaderMargin
= 0;
2415 if (scrollOrientation() == Qt::Horizontal
) {
2416 // The vertical margin above and below the header should be
2417 // equal to the horizontal margin, not the vertical margin
2418 // from m_styleOption.
2419 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2420 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2421 } else if (m_itemSize
.isEmpty()){
2422 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2423 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2425 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2426 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2428 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2429 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2431 updateVisibleGroupHeaders();
2434 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2436 if (!supportsItemExpanding() || !m_model
) {
2440 if (firstIndex
< 0 || lastIndex
< 0) {
2441 firstIndex
= m_layouter
->firstVisibleIndex();
2442 lastIndex
= m_layouter
->lastVisibleIndex();
2444 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2445 lastIndex
>= m_layouter
->firstVisibleIndex());
2446 if (!isRangeVisible
) {
2451 int previousParents
= 0;
2452 QBitArray previousSiblings
;
2454 // The rootIndex describes the first index where the siblings get
2455 // calculated from. For the calculation the upper most parent item
2456 // is required. For performance reasons it is checked first whether
2457 // the visible items before or after the current range already
2458 // contain a siblings information which can be used as base.
2459 int rootIndex
= firstIndex
;
2461 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2463 // There is no visible widget before the range, check whether there
2464 // is one after the range:
2465 widget
= m_visibleItems
.value(lastIndex
+ 1);
2467 // The sibling information of the widget may only be used if
2468 // all items of the range have the same number of parents.
2469 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2470 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2471 if (m_model
->expandedParentsCount(i
) != parents
) {
2480 // Performance optimization: Use the sibling information of the visible
2481 // widget beside the given range.
2482 previousSiblings
= widget
->siblingsInformation();
2483 if (previousSiblings
.isEmpty()) {
2486 previousParents
= previousSiblings
.count() - 1;
2487 previousSiblings
.truncate(previousParents
);
2489 // Potentially slow path: Go back to the upper most parent of firstIndex
2490 // to be able to calculate the initial value for the siblings.
2491 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2496 Q_ASSERT(previousParents
>= 0);
2497 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2498 // Update the parent-siblings in case if the current item represents
2499 // a child or an upper parent.
2500 const int currentParents
= m_model
->expandedParentsCount(i
);
2501 Q_ASSERT(currentParents
>= 0);
2502 if (previousParents
< currentParents
) {
2503 previousParents
= currentParents
;
2504 previousSiblings
.resize(currentParents
);
2505 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2506 } else if (previousParents
> currentParents
) {
2507 previousParents
= currentParents
;
2508 previousSiblings
.truncate(currentParents
);
2511 if (i
>= firstIndex
) {
2512 // The index represents a visible item. Apply the parent-siblings
2513 // and update the sibling of the current item.
2514 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2519 QBitArray siblings
= previousSiblings
;
2520 siblings
.resize(siblings
.count() + 1);
2521 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2523 widget
->setSiblingsInformation(siblings
);
2528 bool KItemListView::hasSiblingSuccessor(int index
) const
2530 bool hasSuccessor
= false;
2531 const int parentsCount
= m_model
->expandedParentsCount(index
);
2532 int successorIndex
= index
+ 1;
2534 // Search the next sibling
2535 const int itemCount
= m_model
->count();
2536 while (successorIndex
< itemCount
) {
2537 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2538 if (currentParentsCount
== parentsCount
) {
2539 hasSuccessor
= true;
2541 } else if (currentParentsCount
< parentsCount
) {
2547 if (m_grouped
&& hasSuccessor
) {
2548 // If the sibling is part of another group, don't mark it as
2549 // successor as the group header is between the sibling connections.
2550 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2551 if (m_layouter
->isFirstGroupItem(i
)) {
2552 hasSuccessor
= false;
2558 return hasSuccessor
;
2561 void KItemListView::disconnectRoleEditingSignals(int index
)
2563 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2568 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2569 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2572 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2576 const int minSpeed
= 4;
2577 const int maxSpeed
= 128;
2578 const int speedLimiter
= 96;
2579 const int autoScrollBorder
= 64;
2581 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2582 // This assures that the autoscrolling speed grows gradually.
2583 const int incLimiter
= 1;
2585 if (pos
< autoScrollBorder
) {
2586 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2587 inc
= qMax(inc
, -maxSpeed
);
2588 inc
= qMax(inc
, oldInc
- incLimiter
);
2589 } else if (pos
> range
- autoScrollBorder
) {
2590 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2591 inc
= qMin(inc
, maxSpeed
);
2592 inc
= qMin(inc
, oldInc
+ incLimiter
);
2598 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2600 const qreal availableSize
= size
- itemMargin
;
2601 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2607 KItemListCreatorBase::~KItemListCreatorBase()
2609 qDeleteAll(m_recycleableWidgets
);
2610 qDeleteAll(m_createdWidgets
);
2613 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2615 m_createdWidgets
.insert(widget
);
2618 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2620 Q_ASSERT(m_createdWidgets
.contains(widget
));
2621 m_createdWidgets
.remove(widget
);
2623 if (m_recycleableWidgets
.count() < 100) {
2624 m_recycleableWidgets
.append(widget
);
2625 widget
->setVisible(false);
2631 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2633 if (m_recycleableWidgets
.isEmpty()) {
2637 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2638 m_createdWidgets
.insert(widget
);
2642 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2646 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2648 widget
->setParentItem(0);
2649 widget
->setOpacity(1.0);
2650 pushRecycleableWidget(widget
);
2653 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2657 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2659 header
->setOpacity(1.0);
2660 pushRecycleableWidget(header
);
2663 #include "kitemlistview.moc"