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 const QRectF currentRect
= itemRect(index
);
509 if (!viewGeometry
.contains(currentRect
)) {
510 qreal newOffset
= scrollOffset();
511 if (scrollOrientation() == Qt::Vertical
) {
512 if (currentRect
.top() < viewGeometry
.top()) {
513 newOffset
+= currentRect
.top() - viewGeometry
.top();
514 } else if (currentRect
.bottom() > viewGeometry
.bottom()) {
515 newOffset
+= currentRect
.bottom() - viewGeometry
.bottom();
518 if (currentRect
.left() < viewGeometry
.left()) {
519 newOffset
+= currentRect
.left() - viewGeometry
.left();
520 } else if (currentRect
.right() > viewGeometry
.right()) {
521 newOffset
+= currentRect
.right() - viewGeometry
.right();
525 if (newOffset
!= scrollOffset()) {
526 emit
scrollTo(newOffset
);
531 void KItemListView::beginTransaction()
533 ++m_activeTransactions
;
534 if (m_activeTransactions
== 1) {
535 onTransactionBegin();
539 void KItemListView::endTransaction()
541 --m_activeTransactions
;
542 if (m_activeTransactions
< 0) {
543 m_activeTransactions
= 0;
544 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
547 if (m_activeTransactions
== 0) {
549 doLayout(m_endTransactionAnimationHint
);
550 m_endTransactionAnimationHint
= Animation
;
554 bool KItemListView::isTransactionActive() const
556 return m_activeTransactions
> 0;
559 void KItemListView::setHeaderVisible(bool visible
)
561 if (visible
&& !m_headerWidget
->isVisible()) {
562 QStyleOptionHeader option
;
563 const QSize headerSize
= style()->sizeFromContents(QStyle::CT_HeaderSection
,
566 m_headerWidget
->setPos(0, 0);
567 m_headerWidget
->resize(size().width(), headerSize
.height());
568 m_headerWidget
->setModel(m_model
);
569 m_headerWidget
->setColumns(m_visibleRoles
);
570 m_headerWidget
->setZValue(1);
572 connect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
573 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
574 connect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
575 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
576 connect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
577 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
578 connect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
579 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
581 m_layouter
->setHeaderHeight(headerSize
.height());
582 m_headerWidget
->setVisible(true);
583 } else if (!visible
&& m_headerWidget
->isVisible()) {
584 disconnect(m_headerWidget
, SIGNAL(columnWidthChanged(QByteArray
,qreal
,qreal
)),
585 this, SLOT(slotHeaderColumnWidthChanged(QByteArray
,qreal
,qreal
)));
586 disconnect(m_headerWidget
, SIGNAL(columnMoved(QByteArray
,int,int)),
587 this, SLOT(slotHeaderColumnMoved(QByteArray
,int,int)));
588 disconnect(m_headerWidget
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
589 this, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
590 disconnect(m_headerWidget
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
591 this, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)));
593 m_layouter
->setHeaderHeight(0);
594 m_headerWidget
->setVisible(false);
598 bool KItemListView::isHeaderVisible() const
600 return m_headerWidget
->isVisible();
603 KItemListHeader
* KItemListView::header() const
608 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
612 if (indexes
.count() == 1) {
613 KItemListWidget
* item
= m_visibleItems
.value(indexes
.toList().first());
614 QGraphicsView
* graphicsView
= scene()->views()[0];
615 if (item
&& graphicsView
) {
616 pixmap
= item
->createDragPixmap(0, graphicsView
);
619 // TODO: Not implemented yet. Probably extend the interface
620 // from KItemListWidget::createDragPixmap() to return a pixmap
621 // that can be used for multiple indexes.
627 void KItemListView::editRole(int index
, const QByteArray
& role
)
629 KItemListWidget
* widget
= m_visibleItems
.value(index
);
630 if (!widget
|| m_editingRole
) {
634 m_editingRole
= true;
635 widget
->setEditedRole(role
);
637 connect(widget
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
638 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
639 connect(widget
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
640 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
643 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
645 QGraphicsWidget::paint(painter
, option
, widget
);
647 if (m_rubberBand
->isActive()) {
648 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
649 m_rubberBand
->endPosition()).normalized();
651 const QPointF topLeft
= rubberBandRect
.topLeft();
652 if (scrollOrientation() == Qt::Vertical
) {
653 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - scrollOffset());
655 rubberBandRect
.moveTo(topLeft
.x() - scrollOffset(), topLeft
.y());
658 QStyleOptionRubberBand opt
;
659 opt
.initFrom(widget
);
660 opt
.shape
= QRubberBand::Rectangle
;
662 opt
.rect
= rubberBandRect
.toRect();
663 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
666 if (!m_dropIndicator
.isEmpty()) {
667 const QRectF r
= m_dropIndicator
.toRect();
669 QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
670 painter
->setPen(color
);
672 // TODO: The following implementation works only for a vertical scroll-orientation
673 // and assumes a height of the m_draggingInsertIndicator of 1.
674 Q_ASSERT(r
.height() == 1);
675 painter
->drawLine(r
.left() + 1, r
.top(), r
.right() - 1, r
.top());
678 painter
->setPen(color
);
679 painter
->drawRect(r
.left(), r
.top() - 1, r
.width() - 1, 2);
683 QVariant
KItemListView::itemChange(GraphicsItemChange change
, const QVariant
&value
)
685 if (change
== QGraphicsItem::ItemSceneHasChanged
&& scene()) {
686 if (!scene()->views().isEmpty()) {
687 m_styleOption
.palette
= scene()->views().at(0)->palette();
690 return QGraphicsItem::itemChange(change
, value
);
693 void KItemListView::setItemSize(const QSizeF
& size
)
695 const QSizeF previousSize
= m_itemSize
;
696 if (size
== previousSize
) {
700 // Skip animations when the number of rows or columns
701 // are changed in the grid layout. Although the animation
702 // engine can handle this usecase, it looks obtrusive.
703 const bool animate
= !changesItemGridLayout(m_layouter
->size(),
705 m_layouter
->itemMargin());
707 const bool alternateBackgroundsChanged
= (m_visibleRoles
.count() > 1) &&
708 (( m_itemSize
.isEmpty() && !size
.isEmpty()) ||
709 (!m_itemSize
.isEmpty() && size
.isEmpty()));
713 if (alternateBackgroundsChanged
) {
714 // For an empty item size alternate backgrounds are drawn if more than
715 // one role is shown. Assure that the backgrounds for visible items are
716 // updated when changing the size in this context.
717 updateAlternateBackgrounds();
720 if (size
.isEmpty()) {
721 if (m_headerWidget
->automaticColumnResizing()) {
722 updatePreferredColumnWidths();
724 // Only apply the changed height and respect the header widths
726 const qreal currentWidth
= m_layouter
->itemSize().width();
727 const QSizeF
newSize(currentWidth
, size
.height());
728 m_layouter
->setItemSize(newSize
);
731 m_layouter
->setItemSize(size
);
734 m_sizeHintResolver
->clearCache();
735 doLayout(animate
? Animation
: NoAnimation
);
736 onItemSizeChanged(size
, previousSize
);
739 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
741 const KItemListStyleOption previousOption
= m_styleOption
;
742 m_styleOption
= option
;
745 const QSizeF
margin(option
.horizontalMargin
, option
.verticalMargin
);
746 if (margin
!= m_layouter
->itemMargin()) {
747 // Skip animations when the number of rows or columns
748 // are changed in the grid layout. Although the animation
749 // engine can handle this usecase, it looks obtrusive.
750 animate
= !changesItemGridLayout(m_layouter
->size(),
751 m_layouter
->itemSize(),
753 m_layouter
->setItemMargin(margin
);
757 updateGroupHeaderHeight();
760 if (animate
&& previousOption
.maxTextSize
!= option
.maxTextSize
) {
761 // Animating a change of the maximum text size just results in expensive
762 // temporary eliding and clipping operations and does not look good visually.
766 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
767 while (it
.hasNext()) {
769 it
.value()->setStyleOption(option
);
772 m_sizeHintResolver
->clearCache();
773 m_layouter
->markAsDirty();
774 doLayout(animate
? Animation
: NoAnimation
);
776 if (m_itemSize
.isEmpty()) {
777 updatePreferredColumnWidths();
780 onStyleOptionChanged(option
, previousOption
);
783 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
785 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
786 if (orientation
== previousOrientation
) {
790 m_layouter
->setScrollOrientation(orientation
);
791 m_animation
->setScrollOrientation(orientation
);
792 m_sizeHintResolver
->clearCache();
795 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
796 while (it
.hasNext()) {
798 it
.value()->setScrollOrientation(orientation
);
800 updateGroupHeaderHeight();
804 doLayout(NoAnimation
);
806 onScrollOrientationChanged(orientation
, previousOrientation
);
807 emit
scrollOrientationChanged(orientation
, previousOrientation
);
810 Qt::Orientation
KItemListView::scrollOrientation() const
812 return m_layouter
->scrollOrientation();
815 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
820 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
825 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
830 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
832 Q_UNUSED(changedRoles
);
836 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
842 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
848 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
854 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
860 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
866 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
872 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
878 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
880 Q_UNUSED(supportsExpanding
);
883 void KItemListView::onTransactionBegin()
887 void KItemListView::onTransactionEnd()
891 bool KItemListView::event(QEvent
* event
)
893 // Forward all events to the controller and handle them there
894 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
898 return QGraphicsWidget::event(event
);
901 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
903 m_mousePos
= transform().map(event
->pos());
907 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
909 QGraphicsWidget::mouseMoveEvent(event
);
911 m_mousePos
= transform().map(event
->pos());
912 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
913 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
917 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
919 event
->setAccepted(true);
923 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
925 QGraphicsWidget::dragMoveEvent(event
);
927 m_mousePos
= transform().map(event
->pos());
928 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
929 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
933 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
935 QGraphicsWidget::dragLeaveEvent(event
);
936 setAutoScroll(false);
939 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
941 QGraphicsWidget::dropEvent(event
);
942 setAutoScroll(false);
945 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
947 return m_visibleItems
.values();
950 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
952 if (m_itemSize
.isEmpty()) {
953 updatePreferredColumnWidths(itemRanges
);
956 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
957 if (hasMultipleRanges
) {
961 m_layouter
->markAsDirty();
963 m_sizeHintResolver
->itemsInserted(itemRanges
);
965 int previouslyInsertedCount
= 0;
966 foreach (const KItemRange
& range
, itemRanges
) {
967 // range.index is related to the model before anything has been inserted.
968 // As in each loop the current item-range gets inserted the index must
969 // be increased by the already previously inserted items.
970 const int index
= range
.index
+ previouslyInsertedCount
;
971 const int count
= range
.count
;
972 if (index
< 0 || count
<= 0) {
973 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
976 previouslyInsertedCount
+= count
;
978 // Determine which visible items must be moved
979 QList
<int> itemsToMove
;
980 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
981 while (it
.hasNext()) {
983 const int visibleItemIndex
= it
.key();
984 if (visibleItemIndex
>= index
) {
985 itemsToMove
.append(visibleItemIndex
);
989 // Update the indexes of all KItemListWidget instances that are located
990 // after the inserted items. It is important to adjust the indexes in the order
991 // from the highest index to the lowest index to prevent overlaps when setting the new index.
993 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
994 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
996 const int newIndex
= widget
->index() + count
;
997 if (hasMultipleRanges
) {
998 setWidgetIndex(widget
, newIndex
);
1000 // Try to animate the moving of the item
1001 moveWidgetToIndex(widget
, newIndex
);
1005 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1006 // Check whether a scrollbar is required to show the inserted items. In this case
1007 // the size of the layouter will be decreased before calling doLayout(): This prevents
1008 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1009 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1010 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1011 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1012 if (decreaseLayouterSize
) {
1013 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1014 QSizeF layouterSize
= m_layouter
->size();
1015 if (verticalScrollOrientation
) {
1016 layouterSize
.rwidth() -= scrollBarExtent
;
1018 layouterSize
.rheight() -= scrollBarExtent
;
1020 m_layouter
->setSize(layouterSize
);
1024 if (!hasMultipleRanges
) {
1025 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1026 updateSiblingsInformation();
1031 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1034 if (hasMultipleRanges
) {
1035 m_endTransactionAnimationHint
= NoAnimation
;
1038 updateSiblingsInformation();
1041 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1042 // In case if items of the same group have been inserted before an item that
1043 // currently represents the first item of the group, the group header of
1044 // this item must be removed.
1045 updateVisibleGroupHeaders();
1048 if (useAlternateBackgrounds()) {
1049 updateAlternateBackgrounds();
1053 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1055 if (m_itemSize
.isEmpty()) {
1056 // Don't pass the item-range: The preferred column-widths of
1057 // all items must be adjusted when removing items.
1058 updatePreferredColumnWidths();
1061 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1062 if (hasMultipleRanges
) {
1066 m_layouter
->markAsDirty();
1068 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1070 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1071 const KItemRange
& range
= itemRanges
[i
];
1072 const int index
= range
.index
;
1073 const int count
= range
.count
;
1074 if (index
< 0 || count
<= 0) {
1075 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1079 const int firstRemovedIndex
= index
;
1080 const int lastRemovedIndex
= index
+ count
- 1;
1082 // Remeber which items have to be moved because they are behind the removed range.
1083 QVector
<int> itemsToMove
;
1085 // Remove all KItemListWidget instances that got deleted
1086 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1087 const int i
= widget
->index();
1088 if (i
< firstRemovedIndex
) {
1090 } else if (i
> lastRemovedIndex
) {
1091 itemsToMove
.append(i
);
1095 m_animation
->stop(widget
);
1096 // Stopping the animation might lead to recycling the widget if
1097 // it is invisible (see slotAnimationFinished()).
1098 // Check again whether it is still visible:
1099 if (!m_visibleItems
.contains(i
)) {
1103 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1104 // Remove the widget without animation
1105 recycleWidget(widget
);
1107 // Animate the removing of the items. Special case: When removing an item there
1108 // is no valid model index available anymore. For the
1109 // remove-animation the item gets removed from m_visibleItems but the widget
1110 // will stay alive until the animation has been finished and will
1111 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1112 m_visibleItems
.remove(i
);
1113 widget
->setIndex(-1);
1114 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1118 // Update the indexes of all KItemListWidget instances that are located
1119 // after the deleted items. It is important to update them in ascending
1120 // order to prevent overlaps when setting the new index.
1121 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1122 foreach (int i
, itemsToMove
) {
1123 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1125 const int newIndex
= i
- count
;
1126 if (hasMultipleRanges
) {
1127 setWidgetIndex(widget
, newIndex
);
1129 // Try to animate the moving of the item
1130 moveWidgetToIndex(widget
, newIndex
);
1134 if (!hasMultipleRanges
) {
1135 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1136 // assumes an updated geometry. If items are removed during an active transaction,
1137 // the transaction will be temporary deactivated so that doLayout() triggers a
1138 // geometry update if necessary.
1139 const int activeTransactions
= m_activeTransactions
;
1140 m_activeTransactions
= 0;
1141 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1142 m_activeTransactions
= activeTransactions
;
1143 updateSiblingsInformation();
1148 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1151 if (hasMultipleRanges
) {
1152 m_endTransactionAnimationHint
= NoAnimation
;
1154 updateSiblingsInformation();
1157 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1158 // In case if the first item of a group has been removed, the group header
1159 // must be applied to the next visible item.
1160 updateVisibleGroupHeaders();
1163 if (useAlternateBackgrounds()) {
1164 updateAlternateBackgrounds();
1168 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1170 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1171 m_layouter
->markAsDirty();
1174 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1177 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1178 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1180 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1181 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1183 updateWidgetProperties(widget
, index
);
1184 initializeItemListWidget(widget
);
1188 doLayout(NoAnimation
);
1189 updateSiblingsInformation();
1192 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1193 const QSet
<QByteArray
>& roles
)
1195 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1196 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1197 updatePreferredColumnWidths(itemRanges
);
1200 foreach (const KItemRange
& itemRange
, itemRanges
) {
1201 const int index
= itemRange
.index
;
1202 const int count
= itemRange
.count
;
1204 if (updateSizeHints
) {
1205 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1206 m_layouter
->markAsDirty();
1208 if (!m_layoutTimer
->isActive()) {
1209 m_layoutTimer
->start();
1213 // Apply the changed roles to the visible item-widgets
1214 const int lastIndex
= index
+ count
- 1;
1215 for (int i
= index
; i
<= lastIndex
; ++i
) {
1216 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1218 widget
->setData(m_model
->data(i
), roles
);
1222 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1223 // The sort-role has been changed which might result
1224 // in modified group headers
1225 updateVisibleGroupHeaders();
1226 doLayout(NoAnimation
);
1229 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1232 void KItemListView::slotGroupedSortingChanged(bool current
)
1234 m_grouped
= current
;
1235 m_layouter
->markAsDirty();
1238 updateGroupHeaderHeight();
1240 // Clear all visible headers
1241 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
1242 while (it
.hasNext()) {
1244 recycleGroupHeaderForWidget(it
.key());
1246 Q_ASSERT(m_visibleGroups
.isEmpty());
1249 if (useAlternateBackgrounds()) {
1250 // Changing the group mode requires to update the alternate backgrounds
1251 // as with the enabled group mode the altering is done on base of the first
1253 updateAlternateBackgrounds();
1255 updateSiblingsInformation();
1256 doLayout(NoAnimation
);
1259 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1264 updateVisibleGroupHeaders();
1265 doLayout(NoAnimation
);
1269 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1274 updateVisibleGroupHeaders();
1275 doLayout(NoAnimation
);
1279 void KItemListView::slotCurrentChanged(int current
, int previous
)
1283 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1284 if (previousWidget
) {
1285 previousWidget
->setCurrent(false);
1288 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1289 if (currentWidget
) {
1290 currentWidget
->setCurrent(true);
1292 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1295 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
1299 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1300 while (it
.hasNext()) {
1302 const int index
= it
.key();
1303 KItemListWidget
* widget
= it
.value();
1304 widget
->setSelected(current
.contains(index
));
1308 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1309 KItemListViewAnimation::AnimationType type
)
1311 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1312 Q_ASSERT(itemListWidget
);
1315 case KItemListViewAnimation::DeleteAnimation
: {
1316 // As we recycle the widget in this case it is important to assure that no
1317 // other animation has been started. This is a convention in KItemListView and
1318 // not a requirement defined by KItemListViewAnimation.
1319 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1321 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1322 // by m_visibleWidgets and must be deleted manually after the animation has
1324 recycleGroupHeaderForWidget(itemListWidget
);
1325 widgetCreator()->recycle(itemListWidget
);
1329 case KItemListViewAnimation::CreateAnimation
:
1330 case KItemListViewAnimation::MovingAnimation
:
1331 case KItemListViewAnimation::ResizeAnimation
: {
1332 const int index
= itemListWidget
->index();
1333 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1334 (index
> m_layouter
->lastVisibleIndex());
1335 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1336 recycleWidget(itemListWidget
);
1345 void KItemListView::slotLayoutTimerFinished()
1347 m_layouter
->setSize(geometry().size());
1348 doLayout(Animation
);
1351 void KItemListView::slotRubberBandPosChanged()
1356 void KItemListView::slotRubberBandActivationChanged(bool active
)
1359 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1360 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1361 m_skipAutoScrollForRubberBand
= true;
1363 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1364 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1365 m_skipAutoScrollForRubberBand
= false;
1371 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1373 qreal previousWidth
)
1376 Q_UNUSED(currentWidth
);
1377 Q_UNUSED(previousWidth
);
1379 m_headerWidget
->setAutomaticColumnResizing(false);
1380 applyColumnWidthsFromHeader();
1381 doLayout(NoAnimation
);
1384 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1388 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1390 const QList
<QByteArray
> previous
= m_visibleRoles
;
1392 QList
<QByteArray
> current
= m_visibleRoles
;
1393 current
.removeAt(previousIndex
);
1394 current
.insert(currentIndex
, role
);
1396 setVisibleRoles(current
);
1398 emit
visibleRolesChanged(current
, previous
);
1401 void KItemListView::triggerAutoScrolling()
1403 if (!m_autoScrollTimer
) {
1408 int visibleSize
= 0;
1409 if (scrollOrientation() == Qt::Vertical
) {
1410 pos
= m_mousePos
.y();
1411 visibleSize
= size().height();
1413 pos
= m_mousePos
.x();
1414 visibleSize
= size().width();
1417 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1418 m_autoScrollIncrement
= 0;
1421 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1422 if (m_autoScrollIncrement
== 0) {
1423 // The mouse position is not above an autoscroll margin (the autoscroll timer
1424 // will be restarted in mouseMoveEvent())
1425 m_autoScrollTimer
->stop();
1429 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1430 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1431 // if the direction of the rubberband is similar to the autoscroll direction. This
1432 // prevents that starting to create a rubberband within the autoscroll margins starts
1433 // an autoscrolling.
1435 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1436 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1437 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1438 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1439 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1440 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1441 // been moved up although the autoscroll direction might be down)
1442 m_autoScrollTimer
->stop();
1447 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1448 // the autoscrolling may not get skipped anymore until a new rubberband is created
1449 m_skipAutoScrollForRubberBand
= false;
1451 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1452 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1453 setScrollOffset(newScrollOffset
);
1455 // Trigger the autoscroll timer which will periodically call
1456 // triggerAutoScrolling()
1457 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1460 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1462 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1464 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1465 Q_ASSERT(groupHeader
);
1466 updateGroupHeaderLayout(widget
);
1469 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1471 disconnectRoleEditingSignals(index
);
1473 emit
roleEditingCanceled(index
, role
, value
);
1474 m_editingRole
= false;
1477 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1479 disconnectRoleEditingSignals(index
);
1481 emit
roleEditingFinished(index
, role
, value
);
1482 m_editingRole
= false;
1485 void KItemListView::setController(KItemListController
* controller
)
1487 if (m_controller
!= controller
) {
1488 KItemListController
* previous
= m_controller
;
1490 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1491 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1492 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1495 m_controller
= controller
;
1498 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1499 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1500 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
1503 onControllerChanged(controller
, previous
);
1507 void KItemListView::setModel(KItemModelBase
* model
)
1509 if (m_model
== model
) {
1513 KItemModelBase
* previous
= m_model
;
1516 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1517 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1518 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1519 this, SLOT(slotItemsInserted(KItemRangeList
)));
1520 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1521 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1522 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1523 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1524 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1525 this, SLOT(slotGroupedSortingChanged(bool)));
1526 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1527 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1528 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1529 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1531 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1535 m_layouter
->setModel(model
);
1536 m_grouped
= model
->groupedSorting();
1539 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1540 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1541 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1542 this, SLOT(slotItemsInserted(KItemRangeList
)));
1543 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1544 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1545 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1546 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1547 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1548 this, SLOT(slotGroupedSortingChanged(bool)));
1549 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1550 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1551 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1552 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1554 const int itemCount
= m_model
->count();
1555 if (itemCount
> 0) {
1556 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1560 onModelChanged(model
, previous
);
1563 KItemListRubberBand
* KItemListView::rubberBand() const
1565 return m_rubberBand
;
1568 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1570 if (m_layoutTimer
->isActive()) {
1571 m_layoutTimer
->stop();
1574 if (m_activeTransactions
> 0) {
1575 if (hint
== NoAnimation
) {
1576 // As soon as at least one property change should be done without animation,
1577 // the whole transaction will be marked as not animated.
1578 m_endTransactionAnimationHint
= NoAnimation
;
1583 if (!m_model
|| m_model
->count() < 0) {
1587 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1588 if (firstVisibleIndex
< 0) {
1589 emitOffsetChanges();
1593 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1594 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1595 // is still shown if the maximum offset got decreased.
1596 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1597 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1598 if (scrollOffset() > maxOffsetToShowFullRange
) {
1599 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1600 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1603 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1605 int firstSibblingIndex
= -1;
1606 int lastSibblingIndex
= -1;
1607 const bool supportsExpanding
= supportsItemExpanding();
1609 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1611 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1612 // instances from invisible items are reused. If no reusable items are
1613 // found then new KItemListWidget instances get created.
1614 const bool animate
= (hint
== Animation
);
1615 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1616 bool applyNewPos
= true;
1617 bool wasHidden
= false;
1619 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1620 const QPointF newPos
= itemBounds
.topLeft();
1621 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1624 if (!reusableItems
.isEmpty()) {
1625 // Reuse a KItemListWidget instance from an invisible item
1626 const int oldIndex
= reusableItems
.takeLast();
1627 widget
= m_visibleItems
.value(oldIndex
);
1628 setWidgetIndex(widget
, i
);
1629 updateWidgetProperties(widget
, i
);
1630 initializeItemListWidget(widget
);
1632 // No reusable KItemListWidget instance is available, create a new one
1633 widget
= createWidget(i
);
1635 widget
->resize(itemBounds
.size());
1637 if (animate
&& changedCount
< 0) {
1638 // Items have been deleted.
1639 if (i
>= changedIndex
) {
1640 // The item is located behind the removed range. Move the
1641 // created item to the imaginary old position outside the
1642 // view. It will get animated to the new position later.
1643 const int previousIndex
= i
- changedCount
;
1644 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1645 if (itemRect
.isEmpty()) {
1646 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1647 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1648 widget
->setPos(invisibleOldPos
);
1650 widget
->setPos(itemRect
.topLeft());
1652 applyNewPos
= false;
1656 if (supportsExpanding
&& changedCount
== 0) {
1657 if (firstSibblingIndex
< 0) {
1658 firstSibblingIndex
= i
;
1660 lastSibblingIndex
= i
;
1665 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1666 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1667 applyNewPos
= false;
1670 const bool itemsRemoved
= (changedCount
< 0);
1671 const bool itemsInserted
= (changedCount
> 0);
1672 if (itemsRemoved
&& (i
>= changedIndex
)) {
1673 // The item is located after the removed items. Animate the moving of the position.
1674 applyNewPos
= !moveWidget(widget
, newPos
);
1675 } else if (itemsInserted
&& i
>= changedIndex
) {
1676 // The item is located after the first inserted item
1677 if (i
<= changedIndex
+ changedCount
- 1) {
1678 // The item is an inserted item. Animate the appearing of the item.
1679 // For performance reasons no animation is done when changedCount is equal
1680 // to all available items.
1681 if (changedCount
< m_model
->count()) {
1682 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1684 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1685 // The item was already there before, so animate the moving of the position.
1686 // No moving animation is done if the item is animated by a create animation: This
1687 // prevents a "move animation mess" when inserting several ranges in parallel.
1688 applyNewPos
= !moveWidget(widget
, newPos
);
1690 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1691 // The size of the view might have been changed. Animate the moving of the position.
1692 applyNewPos
= !moveWidget(widget
, newPos
);
1695 m_animation
->stop(widget
);
1699 widget
->setPos(newPos
);
1702 Q_ASSERT(widget
->index() == i
);
1703 widget
->setVisible(true);
1705 if (widget
->size() != itemBounds
.size()) {
1706 // Resize the widget for the item to the changed size.
1708 // If a dynamic item size is used then no animation is done in the direction
1709 // of the dynamic size.
1710 if (m_itemSize
.width() <= 0) {
1711 // The width is dynamic, apply the new width without animation.
1712 widget
->resize(itemBounds
.width(), widget
->size().height());
1713 } else if (m_itemSize
.height() <= 0) {
1714 // The height is dynamic, apply the new height without animation.
1715 widget
->resize(widget
->size().width(), itemBounds
.height());
1717 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1719 widget
->resize(itemBounds
.size());
1723 // Updating the cell-information must be done as last step: The decision whether the
1724 // moving-animation should be started at all is based on the previous cell-information.
1725 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1726 m_visibleCells
.insert(i
, cell
);
1729 // Delete invisible KItemListWidget instances that have not been reused
1730 foreach (int index
, reusableItems
) {
1731 recycleWidget(m_visibleItems
.value(index
));
1734 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1735 Q_ASSERT(lastSibblingIndex
>= 0);
1736 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1740 // Update the layout of all visible group headers
1741 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1742 while (it
.hasNext()) {
1744 updateGroupHeaderLayout(it
.key());
1748 emitOffsetChanges();
1751 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1752 int lastVisibleIndex
,
1753 LayoutAnimationHint hint
)
1755 // Determine all items that are completely invisible and might be
1756 // reused for items that just got (at least partly) visible. If the
1757 // animation hint is set to 'Animation' items that do e.g. an animated
1758 // moving of their position are not marked as invisible: This assures
1759 // that a scrolling inside the view can be done without breaking an animation.
1763 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1764 while (it
.hasNext()) {
1767 KItemListWidget
* widget
= it
.value();
1768 const int index
= widget
->index();
1769 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1772 if (m_animation
->isStarted(widget
)) {
1773 if (hint
== NoAnimation
) {
1774 // Stopping the animation will call KItemListView::slotAnimationFinished()
1775 // and the widget will be recycled if necessary there.
1776 m_animation
->stop(widget
);
1779 widget
->setVisible(false);
1780 items
.append(index
);
1783 recycleGroupHeaderForWidget(widget
);
1792 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1794 if (widget
->pos() == newPos
) {
1798 bool startMovingAnim
= false;
1800 if (m_itemSize
.isEmpty()) {
1801 // The items are not aligned in a grid but either as columns or rows.
1802 startMovingAnim
= true;
1804 // When having a grid the moving-animation should only be started, if it is done within
1805 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1806 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1807 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1808 const int index
= widget
->index();
1809 const Cell cell
= m_visibleCells
.value(index
);
1810 if (cell
.column
>= 0 && cell
.row
>= 0) {
1811 if (scrollOrientation() == Qt::Vertical
) {
1812 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1814 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1819 if (startMovingAnim
) {
1820 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1824 m_animation
->stop(widget
);
1825 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1829 void KItemListView::emitOffsetChanges()
1831 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1832 if (m_oldScrollOffset
!= newScrollOffset
) {
1833 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1834 m_oldScrollOffset
= newScrollOffset
;
1837 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1838 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1839 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1840 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1843 const qreal newItemOffset
= m_layouter
->itemOffset();
1844 if (m_oldItemOffset
!= newItemOffset
) {
1845 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1846 m_oldItemOffset
= newItemOffset
;
1849 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1850 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1851 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1852 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1856 KItemListWidget
* KItemListView::createWidget(int index
)
1858 KItemListWidget
* widget
= widgetCreator()->create(this);
1859 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1861 m_visibleItems
.insert(index
, widget
);
1862 m_visibleCells
.insert(index
, Cell());
1863 updateWidgetProperties(widget
, index
);
1864 initializeItemListWidget(widget
);
1868 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1871 recycleGroupHeaderForWidget(widget
);
1874 const int index
= widget
->index();
1875 m_visibleItems
.remove(index
);
1876 m_visibleCells
.remove(index
);
1878 widgetCreator()->recycle(widget
);
1881 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1883 const int oldIndex
= widget
->index();
1884 m_visibleItems
.remove(oldIndex
);
1885 m_visibleCells
.remove(oldIndex
);
1887 m_visibleItems
.insert(index
, widget
);
1888 m_visibleCells
.insert(index
, Cell());
1890 widget
->setIndex(index
);
1893 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1895 const int oldIndex
= widget
->index();
1896 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1898 setWidgetIndex(widget
, index
);
1900 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1901 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1902 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1903 (!vertical
&& oldCell
.column
== newCell
.column
);
1905 m_visibleCells
.insert(index
, newCell
);
1909 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1912 case LayouterSize
: m_layouter
->setSize(size
); break;
1913 case ItemSize
: m_layouter
->setItemSize(size
); break;
1918 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1920 widget
->setVisibleRoles(m_visibleRoles
);
1921 updateWidgetColumnWidths(widget
);
1922 widget
->setStyleOption(m_styleOption
);
1924 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1925 widget
->setCurrent(index
== selectionManager
->currentItem());
1926 widget
->setSelected(selectionManager
->isSelected(index
));
1927 widget
->setHovered(false);
1928 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1929 widget
->setIndex(index
);
1930 widget
->setData(m_model
->data(index
));
1931 widget
->setSiblingsInformation(QBitArray());
1932 updateAlternateBackgroundForWidget(widget
);
1935 updateGroupHeaderForWidget(widget
);
1939 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1941 Q_ASSERT(m_grouped
);
1943 const int index
= widget
->index();
1944 if (!m_layouter
->isFirstGroupItem(index
)) {
1945 // The widget does not represent the first item of a group
1946 // and hence requires no header
1947 recycleGroupHeaderForWidget(widget
);
1951 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
1952 if (groups
.isEmpty() || !groupHeaderCreator()) {
1956 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1958 groupHeader
= groupHeaderCreator()->create(this);
1959 groupHeader
->setParentItem(widget
);
1960 m_visibleGroups
.insert(widget
, groupHeader
);
1961 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1963 Q_ASSERT(groupHeader
->parentItem() == widget
);
1965 const int groupIndex
= groupIndexForItem(index
);
1966 Q_ASSERT(groupIndex
>= 0);
1967 groupHeader
->setData(groups
.at(groupIndex
).second
);
1968 groupHeader
->setRole(model()->sortRole());
1969 groupHeader
->setStyleOption(m_styleOption
);
1970 groupHeader
->setScrollOrientation(scrollOrientation());
1971 groupHeader
->setItemIndex(index
);
1973 groupHeader
->show();
1976 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
1978 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1979 Q_ASSERT(groupHeader
);
1981 const int index
= widget
->index();
1982 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
1983 const QRectF itemRect
= m_layouter
->itemRect(index
);
1985 // The group-header is a child of the itemlist widget. Translate the
1986 // group header position to the relative position.
1987 if (scrollOrientation() == Qt::Vertical
) {
1988 // In the vertical scroll orientation the group header should always span
1989 // the whole width no matter which temporary position the parent widget
1990 // has. In this case the x-position and width will be adjusted manually.
1991 const qreal x
= -widget
->x() - itemOffset();
1992 const qreal width
= maximumItemOffset();
1993 groupHeader
->setPos(x
, -groupHeaderRect
.height());
1994 groupHeader
->resize(width
, groupHeaderRect
.size().height());
1996 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
1997 groupHeader
->resize(groupHeaderRect
.size());
2001 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2003 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2005 header
->setParentItem(0);
2006 groupHeaderCreator()->recycle(header
);
2007 m_visibleGroups
.remove(widget
);
2008 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2012 void KItemListView::updateVisibleGroupHeaders()
2014 Q_ASSERT(m_grouped
);
2015 m_layouter
->markAsDirty();
2017 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2018 while (it
.hasNext()) {
2020 updateGroupHeaderForWidget(it
.value());
2024 int KItemListView::groupIndexForItem(int index
) const
2026 Q_ASSERT(m_grouped
);
2028 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2029 if (groups
.isEmpty()) {
2034 int max
= groups
.count() - 1;
2037 mid
= (min
+ max
) / 2;
2038 if (index
> groups
[mid
].first
) {
2043 } while (groups
[mid
].first
!= index
&& min
<= max
);
2046 while (groups
[mid
].first
> index
&& mid
> 0) {
2054 void KItemListView::updateAlternateBackgrounds()
2056 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2057 while (it
.hasNext()) {
2059 updateAlternateBackgroundForWidget(it
.value());
2063 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2065 bool enabled
= useAlternateBackgrounds();
2067 const int index
= widget
->index();
2068 enabled
= (index
& 0x1) > 0;
2070 const int groupIndex
= groupIndexForItem(index
);
2071 if (groupIndex
>= 0) {
2072 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2073 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2074 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2075 enabled
= (relativeIndex
& 0x1) > 0;
2079 widget
->setAlternateBackground(enabled
);
2082 bool KItemListView::useAlternateBackgrounds() const
2084 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2087 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2089 QElapsedTimer timer
;
2092 QHash
<QByteArray
, qreal
> widths
;
2094 // Calculate the minimum width for each column that is required
2095 // to show the headline unclipped.
2096 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2097 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2098 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2099 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2100 const QString headerText
= m_model
->roleDescription(visibleRole
);
2101 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2102 widths
.insert(visibleRole
, headerWidth
);
2105 // Calculate the preferred column withs for each item and ignore values
2106 // smaller than the width for showing the headline unclipped.
2107 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2108 int calculatedItemCount
= 0;
2109 bool maxTimeExceeded
= false;
2110 foreach (const KItemRange
& itemRange
, itemRanges
) {
2111 const int startIndex
= itemRange
.index
;
2112 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2114 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2115 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2116 qreal maxWidth
= widths
.value(visibleRole
, 0);
2117 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2118 maxWidth
= qMax(width
, maxWidth
);
2119 widths
.insert(visibleRole
, maxWidth
);
2122 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2123 // When having several thousands of items calculating the sizes can get
2124 // very expensive. We accept a possibly too small role-size in favour
2125 // of having no blocking user interface.
2126 maxTimeExceeded
= true;
2129 ++calculatedItemCount
;
2131 if (maxTimeExceeded
) {
2139 void KItemListView::applyColumnWidthsFromHeader()
2141 // Apply the new size to the layouter
2142 const qreal requiredWidth
= columnWidthsSum();
2143 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2144 m_itemSize
.height());
2145 m_layouter
->setItemSize(dynamicItemSize
);
2147 // Update the role sizes for all visible widgets
2148 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2149 while (it
.hasNext()) {
2151 updateWidgetColumnWidths(it
.value());
2155 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2157 foreach (const QByteArray
& role
, m_visibleRoles
) {
2158 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2162 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2164 Q_ASSERT(m_itemSize
.isEmpty());
2165 const int itemCount
= m_model
->count();
2166 int rangesItemCount
= 0;
2167 foreach (const KItemRange
& range
, itemRanges
) {
2168 rangesItemCount
+= range
.count
;
2171 if (itemCount
== rangesItemCount
) {
2172 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2173 foreach (const QByteArray
& role
, m_visibleRoles
) {
2174 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2177 // Only a sub range of the roles need to be determined.
2178 // The chances are good that the widths of the sub ranges
2179 // already fit into the available widths and hence no
2180 // expensive update might be required.
2181 bool changed
= false;
2183 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2184 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2185 while (it
.hasNext()) {
2187 const QByteArray
& role
= it
.key();
2188 const qreal updatedWidth
= it
.value();
2189 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2190 if (updatedWidth
> currentWidth
) {
2191 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2197 // All the updated sizes are smaller than the current sizes and no change
2198 // of the stretched roles-widths is required
2203 if (m_headerWidget
->automaticColumnResizing()) {
2204 applyAutomaticColumnWidths();
2208 void KItemListView::updatePreferredColumnWidths()
2211 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2215 void KItemListView::applyAutomaticColumnWidths()
2217 Q_ASSERT(m_itemSize
.isEmpty());
2218 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2219 if (m_visibleRoles
.isEmpty()) {
2223 // Calculate the maximum size of an item by considering the
2224 // visible role sizes and apply them to the layouter. If the
2225 // size does not use the available view-size the size of the
2226 // first role will get stretched.
2228 foreach (const QByteArray
& role
, m_visibleRoles
) {
2229 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2230 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2233 const QByteArray firstRole
= m_visibleRoles
.first();
2234 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2235 QSizeF dynamicItemSize
= m_itemSize
;
2237 qreal requiredWidth
= columnWidthsSum();
2238 const qreal availableWidth
= size().width();
2239 if (requiredWidth
< availableWidth
) {
2240 // Stretch the first column to use the whole remaining width
2241 firstColumnWidth
+= availableWidth
- requiredWidth
;
2242 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2243 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2244 // Shrink the first column to be able to show as much other
2245 // columns as possible
2246 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2248 // TODO: A proper calculation of the minimum width depends on the implementation
2249 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2251 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2252 if (shrinkedFirstColumnWidth
< minWidth
) {
2253 shrinkedFirstColumnWidth
= minWidth
;
2256 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2257 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2260 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2262 m_layouter
->setItemSize(dynamicItemSize
);
2264 // Update the role sizes for all visible widgets
2265 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2266 while (it
.hasNext()) {
2268 updateWidgetColumnWidths(it
.value());
2272 qreal
KItemListView::columnWidthsSum() const
2274 qreal widthsSum
= 0;
2275 foreach (const QByteArray
& role
, m_visibleRoles
) {
2276 widthsSum
+= m_headerWidget
->columnWidth(role
);
2281 QRectF
KItemListView::headerBoundaries() const
2283 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2286 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2287 const QSizeF
& newItemSize
,
2288 const QSizeF
& newItemMargin
) const
2290 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2294 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2295 const qreal itemWidth
= m_layouter
->itemSize().width();
2296 if (itemWidth
> 0) {
2297 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2298 newItemSize
.width(),
2299 newItemMargin
.width());
2300 if (m_model
->count() > newColumnCount
) {
2301 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2303 m_layouter
->itemMargin().width());
2304 return oldColumnCount
!= newColumnCount
;
2308 const qreal itemHeight
= m_layouter
->itemSize().height();
2309 if (itemHeight
> 0) {
2310 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2311 newItemSize
.height(),
2312 newItemMargin
.height());
2313 if (m_model
->count() > newRowCount
) {
2314 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2316 m_layouter
->itemMargin().height());
2317 return oldRowCount
!= newRowCount
;
2325 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2327 if (m_itemSize
.isEmpty()) {
2328 // We have only columns or only rows, but no grid: An animation is usually
2329 // welcome when inserting or removing items.
2330 return !supportsItemExpanding();
2333 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2337 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2338 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2339 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2340 // Only animate if up to 2/3 of a row or column are inserted or removed
2341 return changedItemCount
<= maximum
* 2 / 3;
2345 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2347 const QSizeF oldSize
= m_layouter
->size();
2349 m_layouter
->setSize(size
);
2350 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2351 m_layouter
->setSize(oldSize
);
2353 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2354 : maxOffset
> size
.width();
2357 int KItemListView::showDropIndicator(const QPointF
& pos
)
2359 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2360 while (it
.hasNext()) {
2362 const KItemListWidget
* widget
= it
.value();
2364 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2365 const QRectF rect
= itemRect(widget
->index());
2366 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2367 if (m_model
->supportsDropping(widget
->index())) {
2368 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2369 const int gap
= qMax(4.0, 0.3 * rect
.height());
2370 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2375 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2376 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2378 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2379 if (m_dropIndicator
!= draggingInsertIndicator
) {
2380 m_dropIndicator
= draggingInsertIndicator
;
2384 int index
= widget
->index();
2392 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2393 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2396 void KItemListView::hideDropIndicator()
2398 if (!m_dropIndicator
.isNull()) {
2399 m_dropIndicator
= QRectF();
2404 void KItemListView::updateGroupHeaderHeight()
2406 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2407 qreal groupHeaderMargin
= 0;
2409 if (scrollOrientation() == Qt::Horizontal
) {
2410 // The vertical margin above and below the header should be
2411 // equal to the horizontal margin, not the vertical margin
2412 // from m_styleOption.
2413 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2414 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2415 } else if (m_itemSize
.isEmpty()){
2416 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2417 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2419 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2420 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2422 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2423 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2425 updateVisibleGroupHeaders();
2428 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2430 if (!supportsItemExpanding() || !m_model
) {
2434 if (firstIndex
< 0 || lastIndex
< 0) {
2435 firstIndex
= m_layouter
->firstVisibleIndex();
2436 lastIndex
= m_layouter
->lastVisibleIndex();
2438 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2439 lastIndex
>= m_layouter
->firstVisibleIndex());
2440 if (!isRangeVisible
) {
2445 int previousParents
= 0;
2446 QBitArray previousSiblings
;
2448 // The rootIndex describes the first index where the siblings get
2449 // calculated from. For the calculation the upper most parent item
2450 // is required. For performance reasons it is checked first whether
2451 // the visible items before or after the current range already
2452 // contain a siblings information which can be used as base.
2453 int rootIndex
= firstIndex
;
2455 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2457 // There is no visible widget before the range, check whether there
2458 // is one after the range:
2459 widget
= m_visibleItems
.value(lastIndex
+ 1);
2461 // The sibling information of the widget may only be used if
2462 // all items of the range have the same number of parents.
2463 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2464 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2465 if (m_model
->expandedParentsCount(i
) != parents
) {
2474 // Performance optimization: Use the sibling information of the visible
2475 // widget beside the given range.
2476 previousSiblings
= widget
->siblingsInformation();
2477 if (previousSiblings
.isEmpty()) {
2480 previousParents
= previousSiblings
.count() - 1;
2481 previousSiblings
.truncate(previousParents
);
2483 // Potentially slow path: Go back to the upper most parent of firstIndex
2484 // to be able to calculate the initial value for the siblings.
2485 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2490 Q_ASSERT(previousParents
>= 0);
2491 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2492 // Update the parent-siblings in case if the current item represents
2493 // a child or an upper parent.
2494 const int currentParents
= m_model
->expandedParentsCount(i
);
2495 Q_ASSERT(currentParents
>= 0);
2496 if (previousParents
< currentParents
) {
2497 previousParents
= currentParents
;
2498 previousSiblings
.resize(currentParents
);
2499 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2500 } else if (previousParents
> currentParents
) {
2501 previousParents
= currentParents
;
2502 previousSiblings
.truncate(currentParents
);
2505 if (i
>= firstIndex
) {
2506 // The index represents a visible item. Apply the parent-siblings
2507 // and update the sibling of the current item.
2508 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2513 QBitArray siblings
= previousSiblings
;
2514 siblings
.resize(siblings
.count() + 1);
2515 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2517 widget
->setSiblingsInformation(siblings
);
2522 bool KItemListView::hasSiblingSuccessor(int index
) const
2524 bool hasSuccessor
= false;
2525 const int parentsCount
= m_model
->expandedParentsCount(index
);
2526 int successorIndex
= index
+ 1;
2528 // Search the next sibling
2529 const int itemCount
= m_model
->count();
2530 while (successorIndex
< itemCount
) {
2531 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2532 if (currentParentsCount
== parentsCount
) {
2533 hasSuccessor
= true;
2535 } else if (currentParentsCount
< parentsCount
) {
2541 if (m_grouped
&& hasSuccessor
) {
2542 // If the sibling is part of another group, don't mark it as
2543 // successor as the group header is between the sibling connections.
2544 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2545 if (m_layouter
->isFirstGroupItem(i
)) {
2546 hasSuccessor
= false;
2552 return hasSuccessor
;
2555 void KItemListView::disconnectRoleEditingSignals(int index
)
2557 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2562 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2563 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2566 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2570 const int minSpeed
= 4;
2571 const int maxSpeed
= 128;
2572 const int speedLimiter
= 96;
2573 const int autoScrollBorder
= 64;
2575 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2576 // This assures that the autoscrolling speed grows gradually.
2577 const int incLimiter
= 1;
2579 if (pos
< autoScrollBorder
) {
2580 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2581 inc
= qMax(inc
, -maxSpeed
);
2582 inc
= qMax(inc
, oldInc
- incLimiter
);
2583 } else if (pos
> range
- autoScrollBorder
) {
2584 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2585 inc
= qMin(inc
, maxSpeed
);
2586 inc
= qMin(inc
, oldInc
+ incLimiter
);
2592 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2594 const qreal availableSize
= size
- itemMargin
;
2595 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2601 KItemListCreatorBase::~KItemListCreatorBase()
2603 qDeleteAll(m_recycleableWidgets
);
2604 qDeleteAll(m_createdWidgets
);
2607 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2609 m_createdWidgets
.insert(widget
);
2612 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2614 Q_ASSERT(m_createdWidgets
.contains(widget
));
2615 m_createdWidgets
.remove(widget
);
2617 if (m_recycleableWidgets
.count() < 100) {
2618 m_recycleableWidgets
.append(widget
);
2619 widget
->setVisible(false);
2625 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2627 if (m_recycleableWidgets
.isEmpty()) {
2631 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2632 m_createdWidgets
.insert(widget
);
2636 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2640 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2642 widget
->setParentItem(0);
2643 widget
->setOpacity(1.0);
2644 pushRecycleableWidget(widget
);
2647 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2651 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2653 header
->setOpacity(1.0);
2654 pushRecycleableWidget(header
);
2657 #include "kitemlistview.moc"