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(m_sizeHintResolver
, this);
116 m_animation
= new KItemListViewAnimation(this);
117 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
118 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
120 m_layoutTimer
= new QTimer(this);
121 m_layoutTimer
->setInterval(300);
122 m_layoutTimer
->setSingleShot(true);
123 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
125 m_rubberBand
= new KItemListRubberBand(this);
126 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
128 m_headerWidget
= new KItemListHeaderWidget(this);
129 m_headerWidget
->setVisible(false);
131 m_header
= new KItemListHeader(this);
133 #ifndef QT_NO_ACCESSIBILITY
134 QAccessible::installFactory(accessibleInterfaceFactory
);
139 KItemListView::~KItemListView()
141 // The group headers are children of the widgets created by
142 // widgetCreator(). So it is mandatory to delete the group headers
144 delete m_groupHeaderCreator
;
145 m_groupHeaderCreator
= 0;
147 delete m_widgetCreator
;
150 delete m_sizeHintResolver
;
151 m_sizeHintResolver
= 0;
154 void KItemListView::setScrollOffset(qreal offset
)
160 const qreal previousOffset
= m_layouter
->scrollOffset();
161 if (offset
== previousOffset
) {
165 m_layouter
->setScrollOffset(offset
);
166 m_animation
->setScrollOffset(offset
);
168 // Don't check whether the m_layoutTimer is active: Changing the
169 // scroll offset must always trigger a synchronous layout, otherwise
170 // the smooth-scrolling might get jerky.
171 doLayout(NoAnimation
);
172 onScrollOffsetChanged(offset
, previousOffset
);
175 qreal
KItemListView::scrollOffset() const
177 return m_layouter
->scrollOffset();
180 qreal
KItemListView::maximumScrollOffset() const
182 return m_layouter
->maximumScrollOffset();
185 void KItemListView::setItemOffset(qreal offset
)
187 if (m_layouter
->itemOffset() == offset
) {
191 m_layouter
->setItemOffset(offset
);
192 if (m_headerWidget
->isVisible()) {
193 m_headerWidget
->setOffset(offset
);
196 // Don't check whether the m_layoutTimer is active: Changing the
197 // item offset must always trigger a synchronous layout, otherwise
198 // the smooth-scrolling might get jerky.
199 doLayout(NoAnimation
);
202 qreal
KItemListView::itemOffset() const
204 return m_layouter
->itemOffset();
207 qreal
KItemListView::maximumItemOffset() const
209 return m_layouter
->maximumItemOffset();
212 int KItemListView::maximumVisibleItems() const
214 return m_layouter
->maximumVisibleItems();
217 void KItemListView::setVisibleRoles(const QList
<QByteArray
>& roles
)
219 const QList
<QByteArray
> previousRoles
= m_visibleRoles
;
220 m_visibleRoles
= roles
;
221 onVisibleRolesChanged(roles
, previousRoles
);
223 m_sizeHintResolver
->clearCache();
224 m_layouter
->markAsDirty();
226 if (m_itemSize
.isEmpty()) {
227 m_headerWidget
->setColumns(roles
);
228 updatePreferredColumnWidths();
229 if (!m_headerWidget
->automaticColumnResizing()) {
230 // The column-width of new roles are still 0. Apply the preferred
231 // column-width as default with.
232 foreach (const QByteArray
& role
, m_visibleRoles
) {
233 if (m_headerWidget
->columnWidth(role
) == 0) {
234 const qreal width
= m_headerWidget
->preferredColumnWidth(role
);
235 m_headerWidget
->setColumnWidth(role
, width
);
239 applyColumnWidthsFromHeader();
243 const bool alternateBackgroundsChanged
= m_itemSize
.isEmpty() &&
244 ((roles
.count() > 1 && previousRoles
.count() <= 1) ||
245 (roles
.count() <= 1 && previousRoles
.count() > 1));
247 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
248 while (it
.hasNext()) {
250 KItemListWidget
* widget
= it
.value();
251 widget
->setVisibleRoles(roles
);
252 if (alternateBackgroundsChanged
) {
253 updateAlternateBackgroundForWidget(widget
);
257 doLayout(NoAnimation
);
260 QList
<QByteArray
> KItemListView::visibleRoles() const
262 return m_visibleRoles
;
265 void KItemListView::setAutoScroll(bool enabled
)
267 if (enabled
&& !m_autoScrollTimer
) {
268 m_autoScrollTimer
= new QTimer(this);
269 m_autoScrollTimer
->setSingleShot(true);
270 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
271 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
272 } else if (!enabled
&& m_autoScrollTimer
) {
273 delete m_autoScrollTimer
;
274 m_autoScrollTimer
= 0;
278 bool KItemListView::autoScroll() const
280 return m_autoScrollTimer
!= 0;
283 void KItemListView::setEnabledSelectionToggles(bool enabled
)
285 if (m_enabledSelectionToggles
!= enabled
) {
286 m_enabledSelectionToggles
= enabled
;
288 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
289 while (it
.hasNext()) {
291 it
.value()->setEnabledSelectionToggle(enabled
);
296 bool KItemListView::enabledSelectionToggles() const
298 return m_enabledSelectionToggles
;
301 KItemListController
* KItemListView::controller() const
306 KItemModelBase
* KItemListView::model() const
311 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
313 if (m_widgetCreator
) {
314 delete m_widgetCreator
;
316 m_widgetCreator
= widgetCreator
;
319 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
321 if (!m_widgetCreator
) {
322 m_widgetCreator
= defaultWidgetCreator();
324 return m_widgetCreator
;
327 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
329 if (m_groupHeaderCreator
) {
330 delete m_groupHeaderCreator
;
332 m_groupHeaderCreator
= groupHeaderCreator
;
335 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
337 if (!m_groupHeaderCreator
) {
338 m_groupHeaderCreator
= defaultGroupHeaderCreator();
340 return m_groupHeaderCreator
;
343 QSizeF
KItemListView::itemSize() const
348 const KItemListStyleOption
& KItemListView::styleOption() const
350 return m_styleOption
;
353 void KItemListView::setGeometry(const QRectF
& rect
)
355 QGraphicsWidget::setGeometry(rect
);
361 const QSizeF newSize
= rect
.size();
362 if (m_itemSize
.isEmpty()) {
363 m_headerWidget
->resize(rect
.width(), m_headerWidget
->size().height());
364 if (m_headerWidget
->automaticColumnResizing()) {
365 applyAutomaticColumnWidths();
367 const qreal requiredWidth
= columnWidthsSum();
368 const QSizeF
dynamicItemSize(qMax(newSize
.width(), requiredWidth
),
369 m_itemSize
.height());
370 m_layouter
->setItemSize(dynamicItemSize
);
373 // Triggering a synchronous layout is fine from a performance point of view,
374 // as with dynamic item sizes no moving animation must be done.
375 m_layouter
->setSize(newSize
);
376 doLayout(NoAnimation
);
378 const bool animate
= !changesItemGridLayout(newSize
,
379 m_layouter
->itemSize(),
380 m_layouter
->itemMargin());
381 m_layouter
->setSize(newSize
);
384 // Trigger an asynchronous relayout with m_layoutTimer to prevent
385 // performance bottlenecks. If the timer is exceeded, an animated layout
386 // will be triggered.
387 if (!m_layoutTimer
->isActive()) {
388 m_layoutTimer
->start();
391 m_layoutTimer
->stop();
392 doLayout(NoAnimation
);
397 qreal
KItemListView::verticalPageStep() const
399 qreal headerHeight
= 0;
400 if (m_headerWidget
->isVisible()) {
401 headerHeight
= m_headerWidget
->size().height();
403 return size().height() - headerHeight
;
406 int KItemListView::itemAt(const QPointF
& pos
) const
408 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
409 while (it
.hasNext()) {
412 const KItemListWidget
* widget
= it
.value();
413 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
414 if (widget
->contains(mappedPos
)) {
422 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
424 if (!m_enabledSelectionToggles
) {
428 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
430 const QRectF selectionToggleRect
= widget
->selectionToggleRect();
431 if (!selectionToggleRect
.isEmpty()) {
432 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
433 return selectionToggleRect
.contains(mappedPos
);
439 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
441 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
443 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
444 if (!expansionToggleRect
.isEmpty()) {
445 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
446 return expansionToggleRect
.contains(mappedPos
);
452 int KItemListView::firstVisibleIndex() const
454 return m_layouter
->firstVisibleIndex();
457 int KItemListView::lastVisibleIndex() const
459 return m_layouter
->lastVisibleIndex();
462 void KItemListView::calculateItemSizeHints(QVector
<QSizeF
>& sizeHints
) const
464 widgetCreator()->calculateItemSizeHints(sizeHints
, this);
467 void KItemListView::setSupportsItemExpanding(bool supportsExpanding
)
469 if (m_supportsItemExpanding
!= supportsExpanding
) {
470 m_supportsItemExpanding
= supportsExpanding
;
471 updateSiblingsInformation();
472 onSupportsItemExpandingChanged(supportsExpanding
);
476 bool KItemListView::supportsItemExpanding() const
478 return m_supportsItemExpanding
;
481 QRectF
KItemListView::itemRect(int index
) const
483 return m_layouter
->itemRect(index
);
486 QRectF
KItemListView::itemContextRect(int index
) const
490 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
492 contextRect
= widget
->iconRect() | widget
->textRect();
493 contextRect
.translate(itemRect(index
).topLeft());
499 void KItemListView::scrollToItem(int index
)
501 QRectF viewGeometry
= geometry();
502 if (m_headerWidget
->isVisible()) {
503 const qreal headerHeight
= m_headerWidget
->size().height();
504 viewGeometry
.adjust(0, headerHeight
, 0, 0);
506 QRectF currentRect
= itemRect(index
);
508 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
509 currentRect
.adjust(-m_styleOption
.horizontalMargin
, -m_styleOption
.verticalMargin
,
510 m_styleOption
.horizontalMargin
, m_styleOption
.verticalMargin
);
512 if (!viewGeometry
.contains(currentRect
)) {
513 qreal newOffset
= scrollOffset();
514 if (scrollOrientation() == Qt::Vertical
) {
515 if (currentRect
.top() < viewGeometry
.top()) {
516 newOffset
+= currentRect
.top() - viewGeometry
.top();
517 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
518 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
521 if (currentRect
.left() < viewGeometry
.left()) {
522 newOffset
+= currentRect
.left() - viewGeometry
.left();
523 } else if (currentRect
.right() > viewGeometry
.right()) {
524 newOffset
+= currentRect
.right() - viewGeometry
.right();
528 if (newOffset
!= scrollOffset()) {
529 emit
scrollTo(newOffset
);
534 void KItemListView::beginTransaction()
536 ++m_activeTransactions
;
537 if (m_activeTransactions
== 1) {
538 onTransactionBegin();
542 void KItemListView::endTransaction()
544 --m_activeTransactions
;
545 if (m_activeTransactions
< 0) {
546 m_activeTransactions
= 0;
547 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
550 if (m_activeTransactions
== 0) {
552 doLayout(m_endTransactionAnimationHint
);
553 m_endTransactionAnimationHint
= Animation
;
557 bool KItemListView::isTransactionActive() const
559 return m_activeTransactions
> 0;
562 void KItemListView::setHeaderVisible(bool visible
)
564 if (visible
&& !m_headerWidget
->isVisible()) {
565 QStyleOptionHeader option
;
566 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
569 m_headerWidget
->setPos(0, 0);
570 m_headerWidget
->resize(size().width(), headerSize
.height());
571 m_headerWidget
->setModel(m_model
);
572 m_headerWidget
->setColumns(m_visibleRoles
);
573 m_headerWidget
->setZValue(1);
575 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
576 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
577 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
578 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
579 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
580 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
581 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
582 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
584 m_layouter
->setHeaderHeight(headerSize
.height());
585 m_headerWidget
->setVisible(true);
586 } else if (!visible
&& m_headerWidget
->isVisible()) {
587 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
588 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
589 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
590 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
591 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
592 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
593 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
594 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
596 m_layouter
->setHeaderHeight(0);
597 m_headerWidget
->setVisible(false);
601 bool KItemListView::isHeaderVisible() const
603 return m_headerWidget
->isVisible();
606 KItemListHeader
* KItemListView::header() const
611 QPixmap
KItemListView::createDragPixmap(const KItemSet
& indexes
) const
615 if (indexes
.count() == 1) {
616 KItemListWidget
* item
= m_visibleItems
.value(indexes
.first());
617 QGraphicsView
* graphicsView
= scene()->views()[0];
618 if (item
&& graphicsView
) {
619 pixmap
= item
->createDragPixmap(0, graphicsView
);
622 // TODO: Not implemented yet. Probably extend the interface
623 // from KItemListWidget::createDragPixmap() to return a pixmap
624 // that can be used for multiple indexes.
630 void KItemListView::editRole(int index
, const QByteArray
& role
)
632 KItemListWidget
* widget
= m_visibleItems
.value(index
);
633 if (!widget
|| m_editingRole
) {
637 m_editingRole
= true;
638 widget
->setEditedRole(role
);
640 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
641 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
642 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
643 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
646 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
648 QGraphicsWidget::paint(painter
, option
, widget
);
650 if (m_rubberBand
->isActive()) {
651 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
652 m_rubberBand
->endPosition()).normalized();
654 const QPointF topLeft
= rubberBandRect
.topLeft();
655 if (scrollOrientation() == Qt::Vertical
) {
656 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
658 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
661 QStyleOptionRubberBand opt
;
662 opt
.initFrom(widget
);
663 opt
.shape
= QRubberBand::Rectangle
;
665 opt
.rect
= rubberBandRect
.toRect();
666 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
669 if (!m_dropIndicator
.isEmpty()) {
670 const QRectF r
= m_dropIndicator
.toRect();
672 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
673 painter
->setPen(color
);
675 // TODO: The following implementation works only for a vertical scroll-orientation
676 // and assumes a height of the m_draggingInsertIndicator of 1.
677 Q_ASSERT(r
.height() == 1);
678 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
681 painter
->setPen(color
);
682 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
686 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
688 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
689 if (!scene()->views().isEmpty()) {
690 m_styleOption
.palette
= scene()->views().at(0)->palette();
693 return QGraphicsItem::itemChange(change
, value
);
696 void KItemListView::setItemSize(const QSizeF
& size
)
698 const QSizeF previousSize
= m_itemSize
;
699 if (size
== previousSize
) {
703 // Skip animations when the number of rows or columns
704 // are changed in the grid layout. Although the animation
705 // engine can handle this usecase, it looks obtrusive.
706 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
708 m_layouter
->itemMargin());
710 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
711 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
712 (!m_itemSize
.isEmpty() && size
.isEmpty()));
716 if (alternateBackgroundsChanged
) {
717 // For an empty item size alternate backgrounds are drawn if more than
718 // one role is shown. Assure that the backgrounds for visible items are
719 // updated when changing the size in this context.
720 updateAlternateBackgrounds();
723 if (size
.isEmpty()) {
724 if (m_headerWidget
->automaticColumnResizing()) {
725 updatePreferredColumnWidths();
727 // Only apply the changed height and respect the header widths
729 const qreal currentWidth
= m_layouter
->itemSize().width();
730 const QSizeF
newSize(currentWidth
, size
.height());
731 m_layouter
->setItemSize(newSize
);
734 m_layouter
->setItemSize(size
);
737 m_sizeHintResolver
->clearCache();
738 doLayout(animate
? Animation
: NoAnimation
);
739 onItemSizeChanged(size
, previousSize
);
742 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
744 const KItemListStyleOption previousOption
= m_styleOption
;
745 m_styleOption
= option
;
748 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
749 if (margin
!= m_layouter
->itemMargin()) {
750 // Skip animations when the number of rows or columns
751 // are changed in the grid layout. Although the animation
752 // engine can handle this usecase, it looks obtrusive.
753 animate
= !changesItemGridLayout(m_layouter
->size(),
754 m_layouter
->itemSize(),
756 m_layouter
->setItemMargin(margin
);
760 updateGroupHeaderHeight();
763 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
764 // Animating a change of the maximum text size just results in expensive
765 // temporary eliding and clipping operations and does not look good visually.
769 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
770 while (it
.hasNext()) {
772 it
.value()->setStyleOption(option
);
775 m_sizeHintResolver
->clearCache();
776 m_layouter
->markAsDirty();
777 doLayout(animate
? Animation
: NoAnimation
);
779 if (m_itemSize
.isEmpty()) {
780 updatePreferredColumnWidths();
783 onStyleOptionChanged(option
, previousOption
);
786 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
788 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
789 if (orientation
== previousOrientation
) {
793 m_layouter
->setScrollOrientation(orientation
);
794 m_animation
->setScrollOrientation(orientation
);
795 m_sizeHintResolver
->clearCache();
798 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
799 while (it
.hasNext()) {
801 it
.value()->setScrollOrientation(orientation
);
803 updateGroupHeaderHeight();
807 doLayout(NoAnimation
);
809 onScrollOrientationChanged(orientation
, previousOrientation
);
810 emit
scrollOrientationChanged(orientation
, previousOrientation
);
813 Qt::Orientation
KItemListView::scrollOrientation() const
815 return m_layouter
->scrollOrientation();
818 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
823 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
828 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
833 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
835 Q_UNUSED(changedRoles
);
839 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
845 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
851 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
857 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
863 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
869 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
875 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
881 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
883 Q_UNUSED(supportsExpanding
);
886 void KItemListView::onTransactionBegin()
890 void KItemListView::onTransactionEnd()
894 bool KItemListView::event(QEvent
* event
)
896 switch (event
->type()) {
897 case QEvent::PaletteChange
:
901 case QEvent::FontChange
:
906 // Forward all other events to the controller and handle them there
907 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
913 return QGraphicsWidget::event(event
);
916 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
918 m_mousePos
= transform().map(event
->pos());
922 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
924 QGraphicsWidget::mouseMoveEvent(event
);
926 m_mousePos
= transform().map(event
->pos());
927 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
928 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
932 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
934 event
->setAccepted(true);
938 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
940 QGraphicsWidget::dragMoveEvent(event
);
942 m_mousePos
= transform().map(event
->pos());
943 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
944 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
948 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
950 QGraphicsWidget::dragLeaveEvent(event
);
951 setAutoScroll(false);
954 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
956 QGraphicsWidget::dropEvent(event
);
957 setAutoScroll(false);
960 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
962 return m_visibleItems
.values();
965 void KItemListView::updateFont()
967 if (scene() && !scene()->views().isEmpty()) {
968 KItemListStyleOption option
= styleOption();
969 option
.font
= scene()->views().first()->font();
970 option
.fontMetrics
= QFontMetrics(option
.font
);
972 setStyleOption(option
);
976 void KItemListView::updatePalette()
978 if (scene() && !scene()->views().isEmpty()) {
979 KItemListStyleOption option
= styleOption();
980 option
.palette
= scene()->views().first()->palette();
982 setStyleOption(option
);
986 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
988 if (m_itemSize
.isEmpty()) {
989 updatePreferredColumnWidths(itemRanges
);
992 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
993 if (hasMultipleRanges
) {
997 m_layouter
->markAsDirty();
999 m_sizeHintResolver
->itemsInserted(itemRanges
);
1001 int previouslyInsertedCount
= 0;
1002 foreach (const KItemRange
& range
, itemRanges
) {
1003 // range.index is related to the model before anything has been inserted.
1004 // As in each loop the current item-range gets inserted the index must
1005 // be increased by the already previously inserted items.
1006 const int index
= range
.index
+ previouslyInsertedCount
;
1007 const int count
= range
.count
;
1008 if (index
< 0 || count
<= 0) {
1009 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1012 previouslyInsertedCount
+= count
;
1014 // Determine which visible items must be moved
1015 QList
<int> itemsToMove
;
1016 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1017 while (it
.hasNext()) {
1019 const int visibleItemIndex
= it
.key();
1020 if (visibleItemIndex
>= index
) {
1021 itemsToMove
.append(visibleItemIndex
);
1025 // Update the indexes of all KItemListWidget instances that are located
1026 // after the inserted items. It is important to adjust the indexes in the order
1027 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1029 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1030 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1032 const int newIndex
= widget
->index() + count
;
1033 if (hasMultipleRanges
) {
1034 setWidgetIndex(widget
, newIndex
);
1036 // Try to animate the moving of the item
1037 moveWidgetToIndex(widget
, newIndex
);
1041 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1042 // Check whether a scrollbar is required to show the inserted items. In this case
1043 // the size of the layouter will be decreased before calling doLayout(): This prevents
1044 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1045 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1046 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1047 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1048 if (decreaseLayouterSize
) {
1049 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1050 QSizeF layouterSize
= m_layouter
->size();
1051 if (verticalScrollOrientation
) {
1052 layouterSize
.rwidth() -= scrollBarExtent
;
1054 layouterSize
.rheight() -= scrollBarExtent
;
1056 m_layouter
->setSize(layouterSize
);
1060 if (!hasMultipleRanges
) {
1061 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1062 updateSiblingsInformation();
1067 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1070 if (hasMultipleRanges
) {
1071 m_endTransactionAnimationHint
= NoAnimation
;
1074 updateSiblingsInformation();
1077 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1078 // In case if items of the same group have been inserted before an item that
1079 // currently represents the first item of the group, the group header of
1080 // this item must be removed.
1081 updateVisibleGroupHeaders();
1084 if (useAlternateBackgrounds()) {
1085 updateAlternateBackgrounds();
1089 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1091 if (m_itemSize
.isEmpty()) {
1092 // Don't pass the item-range: The preferred column-widths of
1093 // all items must be adjusted when removing items.
1094 updatePreferredColumnWidths();
1097 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1098 if (hasMultipleRanges
) {
1102 m_layouter
->markAsDirty();
1104 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1106 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1107 const KItemRange
& range
= itemRanges
[i
];
1108 const int index
= range
.index
;
1109 const int count
= range
.count
;
1110 if (index
< 0 || count
<= 0) {
1111 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1115 const int firstRemovedIndex
= index
;
1116 const int lastRemovedIndex
= index
+ count
- 1;
1118 // Remeber which items have to be moved because they are behind the removed range.
1119 QVector
<int> itemsToMove
;
1121 // Remove all KItemListWidget instances that got deleted
1122 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1123 const int i
= widget
->index();
1124 if (i
< firstRemovedIndex
) {
1126 } else if (i
> lastRemovedIndex
) {
1127 itemsToMove
.append(i
);
1131 m_animation
->stop(widget
);
1132 // Stopping the animation might lead to recycling the widget if
1133 // it is invisible (see slotAnimationFinished()).
1134 // Check again whether it is still visible:
1135 if (!m_visibleItems
.contains(i
)) {
1139 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1140 // Remove the widget without animation
1141 recycleWidget(widget
);
1143 // Animate the removing of the items. Special case: When removing an item there
1144 // is no valid model index available anymore. For the
1145 // remove-animation the item gets removed from m_visibleItems but the widget
1146 // will stay alive until the animation has been finished and will
1147 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1148 m_visibleItems
.remove(i
);
1149 widget
->setIndex(-1);
1150 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1154 // Update the indexes of all KItemListWidget instances that are located
1155 // after the deleted items. It is important to update them in ascending
1156 // order to prevent overlaps when setting the new index.
1157 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1158 foreach (int i
, itemsToMove
) {
1159 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1161 const int newIndex
= i
- count
;
1162 if (hasMultipleRanges
) {
1163 setWidgetIndex(widget
, newIndex
);
1165 // Try to animate the moving of the item
1166 moveWidgetToIndex(widget
, newIndex
);
1170 if (!hasMultipleRanges
) {
1171 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1172 // assumes an updated geometry. If items are removed during an active transaction,
1173 // the transaction will be temporary deactivated so that doLayout() triggers a
1174 // geometry update if necessary.
1175 const int activeTransactions
= m_activeTransactions
;
1176 m_activeTransactions
= 0;
1177 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1178 m_activeTransactions
= activeTransactions
;
1179 updateSiblingsInformation();
1184 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1187 if (hasMultipleRanges
) {
1188 m_endTransactionAnimationHint
= NoAnimation
;
1190 updateSiblingsInformation();
1193 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1194 // In case if the first item of a group has been removed, the group header
1195 // must be applied to the next visible item.
1196 updateVisibleGroupHeaders();
1199 if (useAlternateBackgrounds()) {
1200 updateAlternateBackgrounds();
1204 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1206 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1207 m_layouter
->markAsDirty();
1210 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1213 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1214 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1216 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1217 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1219 updateWidgetProperties(widget
, index
);
1220 initializeItemListWidget(widget
);
1224 doLayout(NoAnimation
);
1225 updateSiblingsInformation();
1228 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1229 const QSet
<QByteArray
>& roles
)
1231 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1232 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1233 updatePreferredColumnWidths(itemRanges
);
1236 foreach (const KItemRange
& itemRange
, itemRanges
) {
1237 const int index
= itemRange
.index
;
1238 const int count
= itemRange
.count
;
1240 if (updateSizeHints
) {
1241 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1242 m_layouter
->markAsDirty();
1244 if (!m_layoutTimer
->isActive()) {
1245 m_layoutTimer
->start();
1249 // Apply the changed roles to the visible item-widgets
1250 const int lastIndex
= index
+ count
- 1;
1251 for (int i
= index
; i
<= lastIndex
; ++i
) {
1252 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1254 widget
->setData(m_model
->data(i
), roles
);
1258 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1259 // The sort-role has been changed which might result
1260 // in modified group headers
1261 updateVisibleGroupHeaders();
1262 doLayout(NoAnimation
);
1265 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1268 void KItemListView::slotGroupsChanged()
1270 updateVisibleGroupHeaders();
1271 doLayout(NoAnimation
);
1272 updateSiblingsInformation();
1275 void KItemListView::slotGroupedSortingChanged(bool current
)
1277 m_grouped
= current
;
1278 m_layouter
->markAsDirty();
1281 updateGroupHeaderHeight();
1283 // Clear all visible headers. Note that the QHashIterator takes a copy of
1284 // m_visibleGroups. Therefore, it remains valid even if items are removed
1285 // from m_visibleGroups in recycleGroupHeaderForWidget().
1286 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1287 while (it
.hasNext()) {
1289 recycleGroupHeaderForWidget(it
.key());
1291 Q_ASSERT(m_visibleGroups
.isEmpty());
1294 if (useAlternateBackgrounds()) {
1295 // Changing the group mode requires to update the alternate backgrounds
1296 // as with the enabled group mode the altering is done on base of the first
1298 updateAlternateBackgrounds();
1300 updateSiblingsInformation();
1301 doLayout(NoAnimation
);
1304 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1309 updateVisibleGroupHeaders();
1310 doLayout(NoAnimation
);
1314 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1319 updateVisibleGroupHeaders();
1320 doLayout(NoAnimation
);
1324 void KItemListView::slotCurrentChanged(int current
, int previous
)
1328 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1329 if (previousWidget
) {
1330 previousWidget
->setCurrent(false);
1333 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1334 if (currentWidget
) {
1335 currentWidget
->setCurrent(true);
1337 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1340 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1344 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1345 while (it
.hasNext()) {
1347 const int index
= it
.key();
1348 KItemListWidget
* widget
= it
.value();
1349 widget
->setSelected(current
.contains(index
));
1353 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1354 KItemListViewAnimation::AnimationType type
)
1356 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1357 Q_ASSERT(itemListWidget
);
1360 case KItemListViewAnimation::DeleteAnimation
: {
1361 // As we recycle the widget in this case it is important to assure that no
1362 // other animation has been started. This is a convention in KItemListView and
1363 // not a requirement defined by KItemListViewAnimation.
1364 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1366 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1367 // by m_visibleWidgets and must be deleted manually after the animation has
1369 recycleGroupHeaderForWidget(itemListWidget
);
1370 widgetCreator()->recycle(itemListWidget
);
1374 case KItemListViewAnimation::CreateAnimation
:
1375 case KItemListViewAnimation::MovingAnimation
:
1376 case KItemListViewAnimation::ResizeAnimation
: {
1377 const int index
= itemListWidget
->index();
1378 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1379 (index
> m_layouter
->lastVisibleIndex());
1380 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1381 recycleWidget(itemListWidget
);
1390 void KItemListView::slotLayoutTimerFinished()
1392 m_layouter
->setSize(geometry().size());
1393 doLayout(Animation
);
1396 void KItemListView::slotRubberBandPosChanged()
1401 void KItemListView::slotRubberBandActivationChanged(bool active
)
1404 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1405 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1406 m_skipAutoScrollForRubberBand
= true;
1408 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1409 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1410 m_skipAutoScrollForRubberBand
= false;
1416 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1418 qreal previousWidth
)
1421 Q_UNUSED(currentWidth
);
1422 Q_UNUSED(previousWidth
);
1424 m_headerWidget
->setAutomaticColumnResizing(false);
1425 applyColumnWidthsFromHeader();
1426 doLayout(NoAnimation
);
1429 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1433 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1435 const QList
<QByteArray
> previous
= m_visibleRoles
;
1437 QList
<QByteArray
> current
= m_visibleRoles
;
1438 current
.removeAt(previousIndex
);
1439 current
.insert(currentIndex
, role
);
1441 setVisibleRoles(current
);
1443 emit
visibleRolesChanged(current
, previous
);
1446 void KItemListView::triggerAutoScrolling()
1448 if (!m_autoScrollTimer
) {
1453 int visibleSize
= 0;
1454 if (scrollOrientation() == Qt::Vertical
) {
1455 pos
= m_mousePos
.y();
1456 visibleSize
= size().height();
1458 pos
= m_mousePos
.x();
1459 visibleSize
= size().width();
1462 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1463 m_autoScrollIncrement
= 0;
1466 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1467 if (m_autoScrollIncrement
== 0) {
1468 // The mouse position is not above an autoscroll margin (the autoscroll timer
1469 // will be restarted in mouseMoveEvent())
1470 m_autoScrollTimer
->stop();
1474 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1475 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1476 // if the direction of the rubberband is similar to the autoscroll direction. This
1477 // prevents that starting to create a rubberband within the autoscroll margins starts
1478 // an autoscrolling.
1480 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1481 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1482 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1483 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1484 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1485 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1486 // been moved up although the autoscroll direction might be down)
1487 m_autoScrollTimer
->stop();
1492 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1493 // the autoscrolling may not get skipped anymore until a new rubberband is created
1494 m_skipAutoScrollForRubberBand
= false;
1496 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1497 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1498 setScrollOffset(newScrollOffset
);
1500 // Trigger the autoscroll timer which will periodically call
1501 // triggerAutoScrolling()
1502 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1505 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1507 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1509 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1510 Q_ASSERT(groupHeader
);
1511 updateGroupHeaderLayout(widget
);
1514 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1516 disconnectRoleEditingSignals(index
);
1518 emit
roleEditingCanceled(index
, role
, value
);
1519 m_editingRole
= false;
1522 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1524 disconnectRoleEditingSignals(index
);
1526 emit
roleEditingFinished(index
, role
, value
);
1527 m_editingRole
= false;
1530 void KItemListView::setController(KItemListController
* controller
)
1532 if (m_controller
!= controller
) {
1533 KItemListController
* previous
= m_controller
;
1535 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1536 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1537 disconnect(selectionManager
, SIGNAL(selectionChanged(KItemSet
,KItemSet
)), this, SLOT(slotSelectionChanged(KItemSet
,KItemSet
)));
1540 m_controller
= controller
;
1543 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1544 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1545 connect(selectionManager
, SIGNAL(selectionChanged(KItemSet
,KItemSet
)), this, SLOT(slotSelectionChanged(KItemSet
,KItemSet
)));
1548 onControllerChanged(controller
, previous
);
1552 void KItemListView::setModel(KItemModelBase
* model
)
1554 if (m_model
== model
) {
1558 KItemModelBase
* previous
= m_model
;
1561 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1562 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1563 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1564 this, SLOT(slotItemsInserted(KItemRangeList
)));
1565 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1566 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1567 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1568 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1569 disconnect(m_model
, SIGNAL(groupsChanged()),
1570 this, SLOT(slotGroupsChanged()));
1571 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1572 this, SLOT(slotGroupedSortingChanged(bool)));
1573 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1574 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1575 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1576 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1578 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1582 m_layouter
->setModel(model
);
1583 m_grouped
= model
->groupedSorting();
1586 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1587 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1588 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1589 this, SLOT(slotItemsInserted(KItemRangeList
)));
1590 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1591 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1592 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1593 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1594 connect(m_model
, SIGNAL(groupsChanged()),
1595 this, SLOT(slotGroupsChanged()));
1596 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1597 this, SLOT(slotGroupedSortingChanged(bool)));
1598 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1599 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1600 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1601 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1603 const int itemCount
= m_model
->count();
1604 if (itemCount
> 0) {
1605 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1609 onModelChanged(model
, previous
);
1612 KItemListRubberBand
* KItemListView::rubberBand() const
1614 return m_rubberBand
;
1617 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1619 if (m_layoutTimer
->isActive()) {
1620 m_layoutTimer
->stop();
1623 if (m_activeTransactions
> 0) {
1624 if (hint
== NoAnimation
) {
1625 // As soon as at least one property change should be done without animation,
1626 // the whole transaction will be marked as not animated.
1627 m_endTransactionAnimationHint
= NoAnimation
;
1632 if (!m_model
|| m_model
->count() < 0) {
1636 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1637 if (firstVisibleIndex
< 0) {
1638 emitOffsetChanges();
1642 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1643 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1644 // is still shown if the maximum offset got decreased.
1645 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1646 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1647 if (scrollOffset() > maxOffsetToShowFullRange
) {
1648 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1649 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1652 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1654 int firstSibblingIndex
= -1;
1655 int lastSibblingIndex
= -1;
1656 const bool supportsExpanding
= supportsItemExpanding();
1658 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1660 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1661 // instances from invisible items are reused. If no reusable items are
1662 // found then new KItemListWidget instances get created.
1663 const bool animate
= (hint
== Animation
);
1664 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1665 bool applyNewPos
= true;
1666 bool wasHidden
= false;
1668 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1669 const QPointF newPos
= itemBounds
.topLeft();
1670 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1673 if (!reusableItems
.isEmpty()) {
1674 // Reuse a KItemListWidget instance from an invisible item
1675 const int oldIndex
= reusableItems
.takeLast();
1676 widget
= m_visibleItems
.value(oldIndex
);
1677 setWidgetIndex(widget
, i
);
1678 updateWidgetProperties(widget
, i
);
1679 initializeItemListWidget(widget
);
1681 // No reusable KItemListWidget instance is available, create a new one
1682 widget
= createWidget(i
);
1684 widget
->resize(itemBounds
.size());
1686 if (animate
&& changedCount
< 0) {
1687 // Items have been deleted.
1688 if (i
>= changedIndex
) {
1689 // The item is located behind the removed range. Move the
1690 // created item to the imaginary old position outside the
1691 // view. It will get animated to the new position later.
1692 const int previousIndex
= i
- changedCount
;
1693 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1694 if (itemRect
.isEmpty()) {
1695 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1696 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1697 widget
->setPos(invisibleOldPos
);
1699 widget
->setPos(itemRect
.topLeft());
1701 applyNewPos
= false;
1705 if (supportsExpanding
&& changedCount
== 0) {
1706 if (firstSibblingIndex
< 0) {
1707 firstSibblingIndex
= i
;
1709 lastSibblingIndex
= i
;
1714 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1715 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1716 applyNewPos
= false;
1719 const bool itemsRemoved
= (changedCount
< 0);
1720 const bool itemsInserted
= (changedCount
> 0);
1721 if (itemsRemoved
&& (i
>= changedIndex
)) {
1722 // The item is located after the removed items. Animate the moving of the position.
1723 applyNewPos
= !moveWidget(widget
, newPos
);
1724 } else if (itemsInserted
&& i
>= changedIndex
) {
1725 // The item is located after the first inserted item
1726 if (i
<= changedIndex
+ changedCount
- 1) {
1727 // The item is an inserted item. Animate the appearing of the item.
1728 // For performance reasons no animation is done when changedCount is equal
1729 // to all available items.
1730 if (changedCount
< m_model
->count()) {
1731 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1733 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1734 // The item was already there before, so animate the moving of the position.
1735 // No moving animation is done if the item is animated by a create animation: This
1736 // prevents a "move animation mess" when inserting several ranges in parallel.
1737 applyNewPos
= !moveWidget(widget
, newPos
);
1739 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1740 // The size of the view might have been changed. Animate the moving of the position.
1741 applyNewPos
= !moveWidget(widget
, newPos
);
1744 m_animation
->stop(widget
);
1748 widget
->setPos(newPos
);
1751 Q_ASSERT(widget
->index() == i
);
1752 widget
->setVisible(true);
1754 if (widget
->size() != itemBounds
.size()) {
1755 // Resize the widget for the item to the changed size.
1757 // If a dynamic item size is used then no animation is done in the direction
1758 // of the dynamic size.
1759 if (m_itemSize
.width() <= 0) {
1760 // The width is dynamic, apply the new width without animation.
1761 widget
->resize(itemBounds
.width(), widget
->size().height());
1762 } else if (m_itemSize
.height() <= 0) {
1763 // The height is dynamic, apply the new height without animation.
1764 widget
->resize(widget
->size().width(), itemBounds
.height());
1766 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1768 widget
->resize(itemBounds
.size());
1772 // Updating the cell-information must be done as last step: The decision whether the
1773 // moving-animation should be started at all is based on the previous cell-information.
1774 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1775 m_visibleCells
.insert(i
, cell
);
1778 // Delete invisible KItemListWidget instances that have not been reused
1779 foreach (int index
, reusableItems
) {
1780 recycleWidget(m_visibleItems
.value(index
));
1783 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1784 Q_ASSERT(lastSibblingIndex
>= 0);
1785 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1789 // Update the layout of all visible group headers
1790 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1791 while (it
.hasNext()) {
1793 updateGroupHeaderLayout(it
.key());
1797 emitOffsetChanges();
1800 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1801 int lastVisibleIndex
,
1802 LayoutAnimationHint hint
)
1804 // Determine all items that are completely invisible and might be
1805 // reused for items that just got (at least partly) visible. If the
1806 // animation hint is set to 'Animation' items that do e.g. an animated
1807 // moving of their position are not marked as invisible: This assures
1808 // that a scrolling inside the view can be done without breaking an animation.
1812 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1813 while (it
.hasNext()) {
1816 KItemListWidget
* widget
= it
.value();
1817 const int index
= widget
->index();
1818 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1821 if (m_animation
->isStarted(widget
)) {
1822 if (hint
== NoAnimation
) {
1823 // Stopping the animation will call KItemListView::slotAnimationFinished()
1824 // and the widget will be recycled if necessary there.
1825 m_animation
->stop(widget
);
1828 widget
->setVisible(false);
1829 items
.append(index
);
1832 recycleGroupHeaderForWidget(widget
);
1841 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1843 if (widget
->pos() == newPos
) {
1847 bool startMovingAnim
= false;
1849 if (m_itemSize
.isEmpty()) {
1850 // The items are not aligned in a grid but either as columns or rows.
1851 startMovingAnim
= true;
1853 // When having a grid the moving-animation should only be started, if it is done within
1854 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1855 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1856 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1857 const int index
= widget
->index();
1858 const Cell cell
= m_visibleCells
.value(index
);
1859 if (cell
.column
>= 0 && cell
.row
>= 0) {
1860 if (scrollOrientation() == Qt::Vertical
) {
1861 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1863 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1868 if (startMovingAnim
) {
1869 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1873 m_animation
->stop(widget
);
1874 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1878 void KItemListView::emitOffsetChanges()
1880 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1881 if (m_oldScrollOffset
!= newScrollOffset
) {
1882 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1883 m_oldScrollOffset
= newScrollOffset
;
1886 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1887 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1888 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1889 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1892 const qreal newItemOffset
= m_layouter
->itemOffset();
1893 if (m_oldItemOffset
!= newItemOffset
) {
1894 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1895 m_oldItemOffset
= newItemOffset
;
1898 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1899 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1900 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1901 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1905 KItemListWidget
* KItemListView::createWidget(int index
)
1907 KItemListWidget
* widget
= widgetCreator()->create(this);
1908 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1910 m_visibleItems
.insert(index
, widget
);
1911 m_visibleCells
.insert(index
, Cell());
1912 updateWidgetProperties(widget
, index
);
1913 initializeItemListWidget(widget
);
1917 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1920 recycleGroupHeaderForWidget(widget
);
1923 const int index
= widget
->index();
1924 m_visibleItems
.remove(index
);
1925 m_visibleCells
.remove(index
);
1927 widgetCreator()->recycle(widget
);
1930 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1932 const int oldIndex
= widget
->index();
1933 m_visibleItems
.remove(oldIndex
);
1934 m_visibleCells
.remove(oldIndex
);
1936 m_visibleItems
.insert(index
, widget
);
1937 m_visibleCells
.insert(index
, Cell());
1939 widget
->setIndex(index
);
1942 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1944 const int oldIndex
= widget
->index();
1945 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1947 setWidgetIndex(widget
, index
);
1949 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1950 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1951 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1952 (!vertical
&& oldCell
.column
== newCell
.column
);
1954 m_visibleCells
.insert(index
, newCell
);
1958 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1961 case LayouterSize
: m_layouter
->setSize(size
); break;
1962 case ItemSize
: m_layouter
->setItemSize(size
); break;
1967 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1969 widget
->setVisibleRoles(m_visibleRoles
);
1970 updateWidgetColumnWidths(widget
);
1971 widget
->setStyleOption(m_styleOption
);
1973 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1974 widget
->setCurrent(index
== selectionManager
->currentItem());
1975 widget
->setSelected(selectionManager
->isSelected(index
));
1976 widget
->setHovered(false);
1977 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1978 widget
->setIndex(index
);
1979 widget
->setData(m_model
->data(index
));
1980 widget
->setSiblingsInformation(QBitArray());
1981 updateAlternateBackgroundForWidget(widget
);
1984 updateGroupHeaderForWidget(widget
);
1988 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1990 Q_ASSERT(m_grouped
);
1992 const int index
= widget
->index();
1993 if (!m_layouter
->isFirstGroupItem(index
)) {
1994 // The widget does not represent the first item of a group
1995 // and hence requires no header
1996 recycleGroupHeaderForWidget(widget
);
2000 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2001 if (groups
.isEmpty() || !groupHeaderCreator()) {
2005 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2007 groupHeader
= groupHeaderCreator()->create(this);
2008 groupHeader
->setParentItem(widget
);
2009 m_visibleGroups
.insert(widget
, groupHeader
);
2010 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2012 Q_ASSERT(groupHeader
->parentItem() == widget
);
2014 const int groupIndex
= groupIndexForItem(index
);
2015 Q_ASSERT(groupIndex
>= 0);
2016 groupHeader
->setData(groups
.at(groupIndex
).second
);
2017 groupHeader
->setRole(model()->sortRole());
2018 groupHeader
->setStyleOption(m_styleOption
);
2019 groupHeader
->setScrollOrientation(scrollOrientation());
2020 groupHeader
->setItemIndex(index
);
2022 groupHeader
->show();
2025 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2027 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2028 Q_ASSERT(groupHeader
);
2030 const int index
= widget
->index();
2031 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2032 const QRectF itemRect
= m_layouter
->itemRect(index
);
2034 // The group-header is a child of the itemlist widget. Translate the
2035 // group header position to the relative position.
2036 if (scrollOrientation() == Qt::Vertical
) {
2037 // In the vertical scroll orientation the group header should always span
2038 // the whole width no matter which temporary position the parent widget
2039 // has. In this case the x-position and width will be adjusted manually.
2040 const qreal x
= -widget
->x() - itemOffset();
2041 const qreal width
= maximumItemOffset();
2042 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2043 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2045 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2046 groupHeader
->resize(groupHeaderRect
.size());
2050 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2052 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2054 header
->setParentItem(0);
2055 groupHeaderCreator()->recycle(header
);
2056 m_visibleGroups
.remove(widget
);
2057 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2061 void KItemListView::updateVisibleGroupHeaders()
2063 Q_ASSERT(m_grouped
);
2064 m_layouter
->markAsDirty();
2066 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2067 while (it
.hasNext()) {
2069 updateGroupHeaderForWidget(it
.value());
2073 int KItemListView::groupIndexForItem(int index
) const
2075 Q_ASSERT(m_grouped
);
2077 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2078 if (groups
.isEmpty()) {
2083 int max
= groups
.count() - 1;
2086 mid
= (min
+ max
) / 2;
2087 if (index
> groups
[mid
].first
) {
2092 } while (groups
[mid
].first
!= index
&& min
<= max
);
2095 while (groups
[mid
].first
> index
&& mid
> 0) {
2103 void KItemListView::updateAlternateBackgrounds()
2105 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2106 while (it
.hasNext()) {
2108 updateAlternateBackgroundForWidget(it
.value());
2112 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2114 bool enabled
= useAlternateBackgrounds();
2116 const int index
= widget
->index();
2117 enabled
= (index
& 0x1) > 0;
2119 const int groupIndex
= groupIndexForItem(index
);
2120 if (groupIndex
>= 0) {
2121 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2122 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2123 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2124 enabled
= (relativeIndex
& 0x1) > 0;
2128 widget
->setAlternateBackground(enabled
);
2131 bool KItemListView::useAlternateBackgrounds() const
2133 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2136 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2138 QElapsedTimer timer
;
2141 QHash
<QByteArray
, qreal
> widths
;
2143 // Calculate the minimum width for each column that is required
2144 // to show the headline unclipped.
2145 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2146 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2147 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2148 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2149 const QString headerText
= m_model
->roleDescription(visibleRole
);
2150 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2151 widths
.insert(visibleRole
, headerWidth
);
2154 // Calculate the preferred column withs for each item and ignore values
2155 // smaller than the width for showing the headline unclipped.
2156 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2157 int calculatedItemCount
= 0;
2158 bool maxTimeExceeded
= false;
2159 foreach (const KItemRange
& itemRange
, itemRanges
) {
2160 const int startIndex
= itemRange
.index
;
2161 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2163 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2164 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2165 qreal maxWidth
= widths
.value(visibleRole
, 0);
2166 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2167 maxWidth
= qMax(width
, maxWidth
);
2168 widths
.insert(visibleRole
, maxWidth
);
2171 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2172 // When having several thousands of items calculating the sizes can get
2173 // very expensive. We accept a possibly too small role-size in favour
2174 // of having no blocking user interface.
2175 maxTimeExceeded
= true;
2178 ++calculatedItemCount
;
2180 if (maxTimeExceeded
) {
2188 void KItemListView::applyColumnWidthsFromHeader()
2190 // Apply the new size to the layouter
2191 const qreal requiredWidth
= columnWidthsSum();
2192 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2193 m_itemSize
.height());
2194 m_layouter
->setItemSize(dynamicItemSize
);
2196 // Update the role sizes for all visible widgets
2197 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2198 while (it
.hasNext()) {
2200 updateWidgetColumnWidths(it
.value());
2204 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2206 foreach (const QByteArray
& role
, m_visibleRoles
) {
2207 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2211 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2213 Q_ASSERT(m_itemSize
.isEmpty());
2214 const int itemCount
= m_model
->count();
2215 int rangesItemCount
= 0;
2216 foreach (const KItemRange
& range
, itemRanges
) {
2217 rangesItemCount
+= range
.count
;
2220 if (itemCount
== rangesItemCount
) {
2221 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2222 foreach (const QByteArray
& role
, m_visibleRoles
) {
2223 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2226 // Only a sub range of the roles need to be determined.
2227 // The chances are good that the widths of the sub ranges
2228 // already fit into the available widths and hence no
2229 // expensive update might be required.
2230 bool changed
= false;
2232 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2233 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2234 while (it
.hasNext()) {
2236 const QByteArray
& role
= it
.key();
2237 const qreal updatedWidth
= it
.value();
2238 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2239 if (updatedWidth
> currentWidth
) {
2240 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2246 // All the updated sizes are smaller than the current sizes and no change
2247 // of the stretched roles-widths is required
2252 if (m_headerWidget
->automaticColumnResizing()) {
2253 applyAutomaticColumnWidths();
2257 void KItemListView::updatePreferredColumnWidths()
2260 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2264 void KItemListView::applyAutomaticColumnWidths()
2266 Q_ASSERT(m_itemSize
.isEmpty());
2267 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2268 if (m_visibleRoles
.isEmpty()) {
2272 // Calculate the maximum size of an item by considering the
2273 // visible role sizes and apply them to the layouter. If the
2274 // size does not use the available view-size the size of the
2275 // first role will get stretched.
2277 foreach (const QByteArray
& role
, m_visibleRoles
) {
2278 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2279 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2282 const QByteArray firstRole
= m_visibleRoles
.first();
2283 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2284 QSizeF dynamicItemSize
= m_itemSize
;
2286 qreal requiredWidth
= columnWidthsSum();
2287 const qreal availableWidth
= size().width();
2288 if (requiredWidth
< availableWidth
) {
2289 // Stretch the first column to use the whole remaining width
2290 firstColumnWidth
+= availableWidth
- requiredWidth
;
2291 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2292 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2293 // Shrink the first column to be able to show as much other
2294 // columns as possible
2295 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2297 // TODO: A proper calculation of the minimum width depends on the implementation
2298 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2300 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2301 if (shrinkedFirstColumnWidth
< minWidth
) {
2302 shrinkedFirstColumnWidth
= minWidth
;
2305 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2306 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2309 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2311 m_layouter
->setItemSize(dynamicItemSize
);
2313 // Update the role sizes for all visible widgets
2314 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2315 while (it
.hasNext()) {
2317 updateWidgetColumnWidths(it
.value());
2321 qreal
KItemListView::columnWidthsSum() const
2323 qreal widthsSum
= 0;
2324 foreach (const QByteArray
& role
, m_visibleRoles
) {
2325 widthsSum
+= m_headerWidget
->columnWidth(role
);
2330 QRectF
KItemListView::headerBoundaries() const
2332 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2335 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2336 const QSizeF
& newItemSize
,
2337 const QSizeF
& newItemMargin
) const
2339 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2343 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2344 const qreal itemWidth
= m_layouter
->itemSize().width();
2345 if (itemWidth
> 0) {
2346 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2347 newItemSize
.width(),
2348 newItemMargin
.width());
2349 if (m_model
->count() > newColumnCount
) {
2350 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2352 m_layouter
->itemMargin().width());
2353 return oldColumnCount
!= newColumnCount
;
2357 const qreal itemHeight
= m_layouter
->itemSize().height();
2358 if (itemHeight
> 0) {
2359 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2360 newItemSize
.height(),
2361 newItemMargin
.height());
2362 if (m_model
->count() > newRowCount
) {
2363 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2365 m_layouter
->itemMargin().height());
2366 return oldRowCount
!= newRowCount
;
2374 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2376 if (m_itemSize
.isEmpty()) {
2377 // We have only columns or only rows, but no grid: An animation is usually
2378 // welcome when inserting or removing items.
2379 return !supportsItemExpanding();
2382 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2386 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2387 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2388 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2389 // Only animate if up to 2/3 of a row or column are inserted or removed
2390 return changedItemCount
<= maximum
* 2 / 3;
2394 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2396 const QSizeF oldSize
= m_layouter
->size();
2398 m_layouter
->setSize(size
);
2399 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2400 m_layouter
->setSize(oldSize
);
2402 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2403 : maxOffset
> size
.width();
2406 int KItemListView::showDropIndicator(const QPointF
& pos
)
2408 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2409 while (it
.hasNext()) {
2411 const KItemListWidget
* widget
= it
.value();
2413 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2414 const QRectF rect
= itemRect(widget
->index());
2415 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2416 if (m_model
->supportsDropping(widget
->index())) {
2417 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2418 const int gap
= qMax(4.0, 0.3 * rect
.height());
2419 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2424 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2425 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2427 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2428 if (m_dropIndicator
!= draggingInsertIndicator
) {
2429 m_dropIndicator
= draggingInsertIndicator
;
2433 int index
= widget
->index();
2441 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2442 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2445 void KItemListView::hideDropIndicator()
2447 if (!m_dropIndicator
.isNull()) {
2448 m_dropIndicator
= QRectF();
2453 void KItemListView::updateGroupHeaderHeight()
2455 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2456 qreal groupHeaderMargin
= 0;
2458 if (scrollOrientation() == Qt::Horizontal
) {
2459 // The vertical margin above and below the header should be
2460 // equal to the horizontal margin, not the vertical margin
2461 // from m_styleOption.
2462 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2463 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2464 } else if (m_itemSize
.isEmpty()){
2465 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2466 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2468 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2469 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2471 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2472 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2474 updateVisibleGroupHeaders();
2477 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2479 if (!supportsItemExpanding() || !m_model
) {
2483 if (firstIndex
< 0 || lastIndex
< 0) {
2484 firstIndex
= m_layouter
->firstVisibleIndex();
2485 lastIndex
= m_layouter
->lastVisibleIndex();
2487 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2488 lastIndex
>= m_layouter
->firstVisibleIndex());
2489 if (!isRangeVisible
) {
2494 int previousParents
= 0;
2495 QBitArray previousSiblings
;
2497 // The rootIndex describes the first index where the siblings get
2498 // calculated from. For the calculation the upper most parent item
2499 // is required. For performance reasons it is checked first whether
2500 // the visible items before or after the current range already
2501 // contain a siblings information which can be used as base.
2502 int rootIndex
= firstIndex
;
2504 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2506 // There is no visible widget before the range, check whether there
2507 // is one after the range:
2508 widget
= m_visibleItems
.value(lastIndex
+ 1);
2510 // The sibling information of the widget may only be used if
2511 // all items of the range have the same number of parents.
2512 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2513 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2514 if (m_model
->expandedParentsCount(i
) != parents
) {
2523 // Performance optimization: Use the sibling information of the visible
2524 // widget beside the given range.
2525 previousSiblings
= widget
->siblingsInformation();
2526 if (previousSiblings
.isEmpty()) {
2529 previousParents
= previousSiblings
.count() - 1;
2530 previousSiblings
.truncate(previousParents
);
2532 // Potentially slow path: Go back to the upper most parent of firstIndex
2533 // to be able to calculate the initial value for the siblings.
2534 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2539 Q_ASSERT(previousParents
>= 0);
2540 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2541 // Update the parent-siblings in case if the current item represents
2542 // a child or an upper parent.
2543 const int currentParents
= m_model
->expandedParentsCount(i
);
2544 Q_ASSERT(currentParents
>= 0);
2545 if (previousParents
< currentParents
) {
2546 previousParents
= currentParents
;
2547 previousSiblings
.resize(currentParents
);
2548 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2549 } else if (previousParents
> currentParents
) {
2550 previousParents
= currentParents
;
2551 previousSiblings
.truncate(currentParents
);
2554 if (i
>= firstIndex
) {
2555 // The index represents a visible item. Apply the parent-siblings
2556 // and update the sibling of the current item.
2557 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2562 QBitArray siblings
= previousSiblings
;
2563 siblings
.resize(siblings
.count() + 1);
2564 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2566 widget
->setSiblingsInformation(siblings
);
2571 bool KItemListView::hasSiblingSuccessor(int index
) const
2573 bool hasSuccessor
= false;
2574 const int parentsCount
= m_model
->expandedParentsCount(index
);
2575 int successorIndex
= index
+ 1;
2577 // Search the next sibling
2578 const int itemCount
= m_model
->count();
2579 while (successorIndex
< itemCount
) {
2580 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2581 if (currentParentsCount
== parentsCount
) {
2582 hasSuccessor
= true;
2584 } else if (currentParentsCount
< parentsCount
) {
2590 if (m_grouped
&& hasSuccessor
) {
2591 // If the sibling is part of another group, don't mark it as
2592 // successor as the group header is between the sibling connections.
2593 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2594 if (m_layouter
->isFirstGroupItem(i
)) {
2595 hasSuccessor
= false;
2601 return hasSuccessor
;
2604 void KItemListView::disconnectRoleEditingSignals(int index
)
2606 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2611 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2612 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2615 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2619 const int minSpeed
= 4;
2620 const int maxSpeed
= 128;
2621 const int speedLimiter
= 96;
2622 const int autoScrollBorder
= 64;
2624 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2625 // This assures that the autoscrolling speed grows gradually.
2626 const int incLimiter
= 1;
2628 if (pos
< autoScrollBorder
) {
2629 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2630 inc
= qMax(inc
, -maxSpeed
);
2631 inc
= qMax(inc
, oldInc
- incLimiter
);
2632 } else if (pos
> range
- autoScrollBorder
) {
2633 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2634 inc
= qMin(inc
, maxSpeed
);
2635 inc
= qMin(inc
, oldInc
+ incLimiter
);
2641 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2643 const qreal availableSize
= size
- itemMargin
;
2644 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2650 KItemListCreatorBase::~KItemListCreatorBase()
2652 qDeleteAll(m_recycleableWidgets
);
2653 qDeleteAll(m_createdWidgets
);
2656 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2658 m_createdWidgets
.insert(widget
);
2661 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2663 Q_ASSERT(m_createdWidgets
.contains(widget
));
2664 m_createdWidgets
.remove(widget
);
2666 if (m_recycleableWidgets
.count() < 100) {
2667 m_recycleableWidgets
.append(widget
);
2668 widget
->setVisible(false);
2674 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2676 if (m_recycleableWidgets
.isEmpty()) {
2680 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2681 m_createdWidgets
.insert(widget
);
2685 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2689 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2691 widget
->setParentItem(0);
2692 widget
->setOpacity(1.0);
2693 pushRecycleableWidget(widget
);
2696 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2700 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2702 header
->setOpacity(1.0);
2703 pushRecycleableWidget(header
);
2706 #include "kitemlistview.moc"