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
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
) const
464 widgetCreator()->calculateItemSizeHints(logicalHeightHints
, logicalWidthHint
, 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();
764 (previousOption
.maxTextLines
!= option
.maxTextLines
|| previousOption
.maxTextWidth
!= option
.maxTextWidth
)) {
765 // Animating a change of the maximum text size just results in expensive
766 // temporary eliding and clipping operations and does not look good visually.
770 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
771 while (it
.hasNext()) {
773 it
.value()->setStyleOption(option
);
776 m_sizeHintResolver
->clearCache();
777 m_layouter
->markAsDirty();
778 doLayout(animate
? Animation
: NoAnimation
);
780 if (m_itemSize
.isEmpty()) {
781 updatePreferredColumnWidths();
784 onStyleOptionChanged(option
, previousOption
);
787 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
789 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
790 if (orientation
== previousOrientation
) {
794 m_layouter
->setScrollOrientation(orientation
);
795 m_animation
->setScrollOrientation(orientation
);
796 m_sizeHintResolver
->clearCache();
799 QMutableHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it (m_visibleGroups
);
800 while (it
.hasNext()) {
802 it
.value()->setScrollOrientation(orientation
);
804 updateGroupHeaderHeight();
808 doLayout(NoAnimation
);
810 onScrollOrientationChanged(orientation
, previousOrientation
);
811 emit
scrollOrientationChanged(orientation
, previousOrientation
);
814 Qt::Orientation
KItemListView::scrollOrientation() const
816 return m_layouter
->scrollOrientation();
819 KItemListWidgetCreatorBase
* KItemListView::defaultWidgetCreator() const
824 KItemListGroupHeaderCreatorBase
* KItemListView::defaultGroupHeaderCreator() const
829 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
834 bool KItemListView::itemSizeHintUpdateRequired(const QSet
<QByteArray
>& changedRoles
) const
836 Q_UNUSED(changedRoles
);
840 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
846 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
852 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
858 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
864 void KItemListView::onScrollOffsetChanged(qreal current
, qreal previous
)
870 void KItemListView::onVisibleRolesChanged(const QList
<QByteArray
>& current
, const QList
<QByteArray
>& previous
)
876 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
882 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding
)
884 Q_UNUSED(supportsExpanding
);
887 void KItemListView::onTransactionBegin()
891 void KItemListView::onTransactionEnd()
895 bool KItemListView::event(QEvent
* event
)
897 switch (event
->type()) {
898 case QEvent::PaletteChange
:
902 case QEvent::FontChange
:
907 // Forward all other events to the controller and handle them there
908 if (!m_editingRole
&& m_controller
&& m_controller
->processEvent(event
, transform())) {
914 return QGraphicsWidget::event(event
);
917 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
919 m_mousePos
= transform().map(event
->pos());
923 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
925 QGraphicsWidget::mouseMoveEvent(event
);
927 m_mousePos
= transform().map(event
->pos());
928 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
929 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
933 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
935 event
->setAccepted(true);
939 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
941 QGraphicsWidget::dragMoveEvent(event
);
943 m_mousePos
= transform().map(event
->pos());
944 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
945 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
949 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
951 QGraphicsWidget::dragLeaveEvent(event
);
952 setAutoScroll(false);
955 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
957 QGraphicsWidget::dropEvent(event
);
958 setAutoScroll(false);
961 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
963 return m_visibleItems
.values();
966 void KItemListView::updateFont()
968 if (scene() && !scene()->views().isEmpty()) {
969 KItemListStyleOption option
= styleOption();
970 option
.font
= scene()->views().first()->font();
971 option
.fontMetrics
= QFontMetrics(option
.font
);
973 setStyleOption(option
);
977 void KItemListView::updatePalette()
979 if (scene() && !scene()->views().isEmpty()) {
980 KItemListStyleOption option
= styleOption();
981 option
.palette
= scene()->views().first()->palette();
983 setStyleOption(option
);
987 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
989 if (m_itemSize
.isEmpty()) {
990 updatePreferredColumnWidths(itemRanges
);
993 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
994 if (hasMultipleRanges
) {
998 m_layouter
->markAsDirty();
1000 m_sizeHintResolver
->itemsInserted(itemRanges
);
1002 int previouslyInsertedCount
= 0;
1003 foreach (const KItemRange
& range
, itemRanges
) {
1004 // range.index is related to the model before anything has been inserted.
1005 // As in each loop the current item-range gets inserted the index must
1006 // be increased by the already previously inserted items.
1007 const int index
= range
.index
+ previouslyInsertedCount
;
1008 const int count
= range
.count
;
1009 if (index
< 0 || count
<= 0) {
1010 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1013 previouslyInsertedCount
+= count
;
1015 // Determine which visible items must be moved
1016 QList
<int> itemsToMove
;
1017 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1018 while (it
.hasNext()) {
1020 const int visibleItemIndex
= it
.key();
1021 if (visibleItemIndex
>= index
) {
1022 itemsToMove
.append(visibleItemIndex
);
1026 // Update the indexes of all KItemListWidget instances that are located
1027 // after the inserted items. It is important to adjust the indexes in the order
1028 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1030 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
1031 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
1033 const int newIndex
= widget
->index() + count
;
1034 if (hasMultipleRanges
) {
1035 setWidgetIndex(widget
, newIndex
);
1037 // Try to animate the moving of the item
1038 moveWidgetToIndex(widget
, newIndex
);
1042 if (m_model
->count() == count
&& m_activeTransactions
== 0) {
1043 // Check whether a scrollbar is required to show the inserted items. In this case
1044 // the size of the layouter will be decreased before calling doLayout(): This prevents
1045 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1046 const bool verticalScrollOrientation
= (scrollOrientation() == Qt::Vertical
);
1047 const bool decreaseLayouterSize
= ( verticalScrollOrientation
&& maximumScrollOffset() > size().height()) ||
1048 (!verticalScrollOrientation
&& maximumScrollOffset() > size().width());
1049 if (decreaseLayouterSize
) {
1050 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
1052 int scrollbarSpacing
= 0;
1053 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents
)) {
1054 scrollbarSpacing
= style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing
);
1057 QSizeF layouterSize
= m_layouter
->size();
1058 if (verticalScrollOrientation
) {
1059 layouterSize
.rwidth() -= scrollBarExtent
+ scrollbarSpacing
;
1061 layouterSize
.rheight() -= scrollBarExtent
+ scrollbarSpacing
;
1063 m_layouter
->setSize(layouterSize
);
1067 if (!hasMultipleRanges
) {
1068 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, count
);
1069 updateSiblingsInformation();
1074 m_controller
->selectionManager()->itemsInserted(itemRanges
);
1077 if (hasMultipleRanges
) {
1078 m_endTransactionAnimationHint
= NoAnimation
;
1081 updateSiblingsInformation();
1084 if (m_grouped
&& (hasMultipleRanges
|| itemRanges
.first().count
< m_model
->count())) {
1085 // In case if items of the same group have been inserted before an item that
1086 // currently represents the first item of the group, the group header of
1087 // this item must be removed.
1088 updateVisibleGroupHeaders();
1091 if (useAlternateBackgrounds()) {
1092 updateAlternateBackgrounds();
1096 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
1098 if (m_itemSize
.isEmpty()) {
1099 // Don't pass the item-range: The preferred column-widths of
1100 // all items must be adjusted when removing items.
1101 updatePreferredColumnWidths();
1104 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
1105 if (hasMultipleRanges
) {
1109 m_layouter
->markAsDirty();
1111 m_sizeHintResolver
->itemsRemoved(itemRanges
);
1113 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
1114 const KItemRange
& range
= itemRanges
[i
];
1115 const int index
= range
.index
;
1116 const int count
= range
.count
;
1117 if (index
< 0 || count
<= 0) {
1118 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
1122 const int firstRemovedIndex
= index
;
1123 const int lastRemovedIndex
= index
+ count
- 1;
1125 // Remeber which items have to be moved because they are behind the removed range.
1126 QVector
<int> itemsToMove
;
1128 // Remove all KItemListWidget instances that got deleted
1129 foreach (KItemListWidget
* widget
, m_visibleItems
) {
1130 const int i
= widget
->index();
1131 if (i
< firstRemovedIndex
) {
1133 } else if (i
> lastRemovedIndex
) {
1134 itemsToMove
.append(i
);
1138 m_animation
->stop(widget
);
1139 // Stopping the animation might lead to recycling the widget if
1140 // it is invisible (see slotAnimationFinished()).
1141 // Check again whether it is still visible:
1142 if (!m_visibleItems
.contains(i
)) {
1146 if (m_model
->count() == 0 || hasMultipleRanges
|| !animateChangedItemCount(count
)) {
1147 // Remove the widget without animation
1148 recycleWidget(widget
);
1150 // Animate the removing of the items. Special case: When removing an item there
1151 // is no valid model index available anymore. For the
1152 // remove-animation the item gets removed from m_visibleItems but the widget
1153 // will stay alive until the animation has been finished and will
1154 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1155 m_visibleItems
.remove(i
);
1156 widget
->setIndex(-1);
1157 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
1161 // Update the indexes of all KItemListWidget instances that are located
1162 // after the deleted items. It is important to update them in ascending
1163 // order to prevent overlaps when setting the new index.
1164 std::sort(itemsToMove
.begin(), itemsToMove
.end());
1165 foreach (int i
, itemsToMove
) {
1166 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1168 const int newIndex
= i
- count
;
1169 if (hasMultipleRanges
) {
1170 setWidgetIndex(widget
, newIndex
);
1172 // Try to animate the moving of the item
1173 moveWidgetToIndex(widget
, newIndex
);
1177 if (!hasMultipleRanges
) {
1178 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1179 // assumes an updated geometry. If items are removed during an active transaction,
1180 // the transaction will be temporary deactivated so that doLayout() triggers a
1181 // geometry update if necessary.
1182 const int activeTransactions
= m_activeTransactions
;
1183 m_activeTransactions
= 0;
1184 doLayout(animateChangedItemCount(count
) ? Animation
: NoAnimation
, index
, -count
);
1185 m_activeTransactions
= activeTransactions
;
1186 updateSiblingsInformation();
1191 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
1194 if (hasMultipleRanges
) {
1195 m_endTransactionAnimationHint
= NoAnimation
;
1197 updateSiblingsInformation();
1200 if (m_grouped
&& (hasMultipleRanges
|| m_model
->count() > 0)) {
1201 // In case if the first item of a group has been removed, the group header
1202 // must be applied to the next visible item.
1203 updateVisibleGroupHeaders();
1206 if (useAlternateBackgrounds()) {
1207 updateAlternateBackgrounds();
1211 void KItemListView::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int>& movedToIndexes
)
1213 m_sizeHintResolver
->itemsMoved(itemRange
, movedToIndexes
);
1214 m_layouter
->markAsDirty();
1217 m_controller
->selectionManager()->itemsMoved(itemRange
, movedToIndexes
);
1220 const int firstVisibleMovedIndex
= qMax(firstVisibleIndex(), itemRange
.index
);
1221 const int lastVisibleMovedIndex
= qMin(lastVisibleIndex(), itemRange
.index
+ itemRange
.count
- 1);
1223 for (int index
= firstVisibleMovedIndex
; index
<= lastVisibleMovedIndex
; ++index
) {
1224 KItemListWidget
* widget
= m_visibleItems
.value(index
);
1226 updateWidgetProperties(widget
, index
);
1227 initializeItemListWidget(widget
);
1231 doLayout(NoAnimation
);
1232 updateSiblingsInformation();
1235 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
1236 const QSet
<QByteArray
>& roles
)
1238 const bool updateSizeHints
= itemSizeHintUpdateRequired(roles
);
1239 if (updateSizeHints
&& m_itemSize
.isEmpty()) {
1240 updatePreferredColumnWidths(itemRanges
);
1243 foreach (const KItemRange
& itemRange
, itemRanges
) {
1244 const int index
= itemRange
.index
;
1245 const int count
= itemRange
.count
;
1247 if (updateSizeHints
) {
1248 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
1249 m_layouter
->markAsDirty();
1251 if (!m_layoutTimer
->isActive()) {
1252 m_layoutTimer
->start();
1256 // Apply the changed roles to the visible item-widgets
1257 const int lastIndex
= index
+ count
- 1;
1258 for (int i
= index
; i
<= lastIndex
; ++i
) {
1259 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1261 widget
->setData(m_model
->data(i
), roles
);
1265 if (m_grouped
&& roles
.contains(m_model
->sortRole())) {
1266 // The sort-role has been changed which might result
1267 // in modified group headers
1268 updateVisibleGroupHeaders();
1269 doLayout(NoAnimation
);
1272 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged
);
1275 void KItemListView::slotGroupsChanged()
1277 updateVisibleGroupHeaders();
1278 doLayout(NoAnimation
);
1279 updateSiblingsInformation();
1282 void KItemListView::slotGroupedSortingChanged(bool current
)
1284 m_grouped
= current
;
1285 m_layouter
->markAsDirty();
1288 updateGroupHeaderHeight();
1290 // Clear all visible headers. Note that the QHashIterator takes a copy of
1291 // m_visibleGroups. Therefore, it remains valid even if items are removed
1292 // from m_visibleGroups in recycleGroupHeaderForWidget().
1293 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1294 while (it
.hasNext()) {
1296 recycleGroupHeaderForWidget(it
.key());
1298 Q_ASSERT(m_visibleGroups
.isEmpty());
1301 if (useAlternateBackgrounds()) {
1302 // Changing the group mode requires to update the alternate backgrounds
1303 // as with the enabled group mode the altering is done on base of the first
1305 updateAlternateBackgrounds();
1307 updateSiblingsInformation();
1308 doLayout(NoAnimation
);
1311 void KItemListView::slotSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
1316 updateVisibleGroupHeaders();
1317 doLayout(NoAnimation
);
1321 void KItemListView::slotSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
1326 updateVisibleGroupHeaders();
1327 doLayout(NoAnimation
);
1331 void KItemListView::slotCurrentChanged(int current
, int previous
)
1335 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
1336 if (previousWidget
) {
1337 previousWidget
->setCurrent(false);
1340 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
1341 if (currentWidget
) {
1342 currentWidget
->setCurrent(true);
1344 QAccessible::updateAccessibility(this, current
+1, QAccessible::Focus
);
1347 void KItemListView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1351 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1352 while (it
.hasNext()) {
1354 const int index
= it
.key();
1355 KItemListWidget
* widget
= it
.value();
1356 widget
->setSelected(current
.contains(index
));
1360 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
1361 KItemListViewAnimation::AnimationType type
)
1363 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
1364 Q_ASSERT(itemListWidget
);
1367 case KItemListViewAnimation::DeleteAnimation
: {
1368 // As we recycle the widget in this case it is important to assure that no
1369 // other animation has been started. This is a convention in KItemListView and
1370 // not a requirement defined by KItemListViewAnimation.
1371 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
1373 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1374 // by m_visibleWidgets and must be deleted manually after the animation has
1376 recycleGroupHeaderForWidget(itemListWidget
);
1377 widgetCreator()->recycle(itemListWidget
);
1381 case KItemListViewAnimation::CreateAnimation
:
1382 case KItemListViewAnimation::MovingAnimation
:
1383 case KItemListViewAnimation::ResizeAnimation
: {
1384 const int index
= itemListWidget
->index();
1385 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
1386 (index
> m_layouter
->lastVisibleIndex());
1387 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
1388 recycleWidget(itemListWidget
);
1397 void KItemListView::slotLayoutTimerFinished()
1399 m_layouter
->setSize(geometry().size());
1400 doLayout(Animation
);
1403 void KItemListView::slotRubberBandPosChanged()
1408 void KItemListView::slotRubberBandActivationChanged(bool active
)
1411 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1412 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1413 m_skipAutoScrollForRubberBand
= true;
1415 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1416 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
1417 m_skipAutoScrollForRubberBand
= false;
1423 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray
& role
,
1425 qreal previousWidth
)
1428 Q_UNUSED(currentWidth
);
1429 Q_UNUSED(previousWidth
);
1431 m_headerWidget
->setAutomaticColumnResizing(false);
1432 applyColumnWidthsFromHeader();
1433 doLayout(NoAnimation
);
1436 void KItemListView::slotHeaderColumnMoved(const QByteArray
& role
,
1440 Q_ASSERT(m_visibleRoles
[previousIndex
] == role
);
1442 const QList
<QByteArray
> previous
= m_visibleRoles
;
1444 QList
<QByteArray
> current
= m_visibleRoles
;
1445 current
.removeAt(previousIndex
);
1446 current
.insert(currentIndex
, role
);
1448 setVisibleRoles(current
);
1450 emit
visibleRolesChanged(current
, previous
);
1453 void KItemListView::triggerAutoScrolling()
1455 if (!m_autoScrollTimer
) {
1460 int visibleSize
= 0;
1461 if (scrollOrientation() == Qt::Vertical
) {
1462 pos
= m_mousePos
.y();
1463 visibleSize
= size().height();
1465 pos
= m_mousePos
.x();
1466 visibleSize
= size().width();
1469 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
1470 m_autoScrollIncrement
= 0;
1473 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
1474 if (m_autoScrollIncrement
== 0) {
1475 // The mouse position is not above an autoscroll margin (the autoscroll timer
1476 // will be restarted in mouseMoveEvent())
1477 m_autoScrollTimer
->stop();
1481 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
1482 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1483 // if the direction of the rubberband is similar to the autoscroll direction. This
1484 // prevents that starting to create a rubberband within the autoscroll margins starts
1485 // an autoscrolling.
1487 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
1488 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
1489 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
1490 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
1491 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
1492 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1493 // been moved up although the autoscroll direction might be down)
1494 m_autoScrollTimer
->stop();
1499 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1500 // the autoscrolling may not get skipped anymore until a new rubberband is created
1501 m_skipAutoScrollForRubberBand
= false;
1503 const qreal maxVisibleOffset
= qMax(qreal(0), maximumScrollOffset() - visibleSize
);
1504 const qreal newScrollOffset
= qMin(scrollOffset() + m_autoScrollIncrement
, maxVisibleOffset
);
1505 setScrollOffset(newScrollOffset
);
1507 // Trigger the autoscroll timer which will periodically call
1508 // triggerAutoScrolling()
1509 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
1512 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1514 KItemListWidget
* widget
= qobject_cast
<KItemListWidget
*>(sender());
1516 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
1517 Q_ASSERT(groupHeader
);
1518 updateGroupHeaderLayout(widget
);
1521 void KItemListView::slotRoleEditingCanceled(int index
, const QByteArray
& role
, const QVariant
& value
)
1523 disconnectRoleEditingSignals(index
);
1525 emit
roleEditingCanceled(index
, role
, value
);
1526 m_editingRole
= false;
1529 void KItemListView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1531 disconnectRoleEditingSignals(index
);
1533 emit
roleEditingFinished(index
, role
, value
);
1534 m_editingRole
= false;
1537 void KItemListView::setController(KItemListController
* controller
)
1539 if (m_controller
!= controller
) {
1540 KItemListController
* previous
= m_controller
;
1542 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
1543 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1544 disconnect(selectionManager
, SIGNAL(selectionChanged(KItemSet
,KItemSet
)), this, SLOT(slotSelectionChanged(KItemSet
,KItemSet
)));
1547 m_controller
= controller
;
1550 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
1551 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1552 connect(selectionManager
, SIGNAL(selectionChanged(KItemSet
,KItemSet
)), this, SLOT(slotSelectionChanged(KItemSet
,KItemSet
)));
1555 onControllerChanged(controller
, previous
);
1559 void KItemListView::setModel(KItemModelBase
* model
)
1561 if (m_model
== model
) {
1565 KItemModelBase
* previous
= m_model
;
1568 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1569 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1570 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1571 this, SLOT(slotItemsInserted(KItemRangeList
)));
1572 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1573 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1574 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1575 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1576 disconnect(m_model
, SIGNAL(groupsChanged()),
1577 this, SLOT(slotGroupsChanged()));
1578 disconnect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1579 this, SLOT(slotGroupedSortingChanged(bool)));
1580 disconnect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1581 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1582 disconnect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1583 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1585 m_sizeHintResolver
->itemsRemoved(KItemRangeList() << KItemRange(0, m_model
->count()));
1589 m_layouter
->setModel(model
);
1590 m_grouped
= model
->groupedSorting();
1593 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1594 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1595 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
1596 this, SLOT(slotItemsInserted(KItemRangeList
)));
1597 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
1598 this, SLOT(slotItemsRemoved(KItemRangeList
)));
1599 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
1600 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
1601 connect(m_model
, SIGNAL(groupsChanged()),
1602 this, SLOT(slotGroupsChanged()));
1603 connect(m_model
, SIGNAL(groupedSortingChanged(bool)),
1604 this, SLOT(slotGroupedSortingChanged(bool)));
1605 connect(m_model
, SIGNAL(sortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)),
1606 this, SLOT(slotSortOrderChanged(Qt::SortOrder
,Qt::SortOrder
)));
1607 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
1608 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
1610 const int itemCount
= m_model
->count();
1611 if (itemCount
> 0) {
1612 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
1616 onModelChanged(model
, previous
);
1619 KItemListRubberBand
* KItemListView::rubberBand() const
1621 return m_rubberBand
;
1624 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
1626 if (m_layoutTimer
->isActive()) {
1627 m_layoutTimer
->stop();
1630 if (m_activeTransactions
> 0) {
1631 if (hint
== NoAnimation
) {
1632 // As soon as at least one property change should be done without animation,
1633 // the whole transaction will be marked as not animated.
1634 m_endTransactionAnimationHint
= NoAnimation
;
1639 if (!m_model
|| m_model
->count() < 0) {
1643 int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1644 if (firstVisibleIndex
< 0) {
1645 emitOffsetChanges();
1649 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1650 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1651 // is still shown if the maximum offset got decreased.
1652 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
1653 const qreal maxOffsetToShowFullRange
= maximumScrollOffset() - visibleOffsetRange
;
1654 if (scrollOffset() > maxOffsetToShowFullRange
) {
1655 m_layouter
->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
1656 firstVisibleIndex
= m_layouter
->firstVisibleIndex();
1659 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
1661 int firstSibblingIndex
= -1;
1662 int lastSibblingIndex
= -1;
1663 const bool supportsExpanding
= supportsItemExpanding();
1665 QList
<int> reusableItems
= recycleInvisibleItems(firstVisibleIndex
, lastVisibleIndex
, hint
);
1667 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1668 // instances from invisible items are reused. If no reusable items are
1669 // found then new KItemListWidget instances get created.
1670 const bool animate
= (hint
== Animation
);
1671 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1672 bool applyNewPos
= true;
1673 bool wasHidden
= false;
1675 const QRectF itemBounds
= m_layouter
->itemRect(i
);
1676 const QPointF newPos
= itemBounds
.topLeft();
1677 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1680 if (!reusableItems
.isEmpty()) {
1681 // Reuse a KItemListWidget instance from an invisible item
1682 const int oldIndex
= reusableItems
.takeLast();
1683 widget
= m_visibleItems
.value(oldIndex
);
1684 setWidgetIndex(widget
, i
);
1685 updateWidgetProperties(widget
, i
);
1686 initializeItemListWidget(widget
);
1688 // No reusable KItemListWidget instance is available, create a new one
1689 widget
= createWidget(i
);
1691 widget
->resize(itemBounds
.size());
1693 if (animate
&& changedCount
< 0) {
1694 // Items have been deleted.
1695 if (i
>= changedIndex
) {
1696 // The item is located behind the removed range. Move the
1697 // created item to the imaginary old position outside the
1698 // view. It will get animated to the new position later.
1699 const int previousIndex
= i
- changedCount
;
1700 const QRectF itemRect
= m_layouter
->itemRect(previousIndex
);
1701 if (itemRect
.isEmpty()) {
1702 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1703 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1704 widget
->setPos(invisibleOldPos
);
1706 widget
->setPos(itemRect
.topLeft());
1708 applyNewPos
= false;
1712 if (supportsExpanding
&& changedCount
== 0) {
1713 if (firstSibblingIndex
< 0) {
1714 firstSibblingIndex
= i
;
1716 lastSibblingIndex
= i
;
1721 if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1722 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1723 applyNewPos
= false;
1726 const bool itemsRemoved
= (changedCount
< 0);
1727 const bool itemsInserted
= (changedCount
> 0);
1728 if (itemsRemoved
&& (i
>= changedIndex
)) {
1729 // The item is located after the removed items. Animate the moving of the position.
1730 applyNewPos
= !moveWidget(widget
, newPos
);
1731 } else if (itemsInserted
&& i
>= changedIndex
) {
1732 // The item is located after the first inserted item
1733 if (i
<= changedIndex
+ changedCount
- 1) {
1734 // The item is an inserted item. Animate the appearing of the item.
1735 // For performance reasons no animation is done when changedCount is equal
1736 // to all available items.
1737 if (changedCount
< m_model
->count()) {
1738 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1740 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1741 // The item was already there before, so animate the moving of the position.
1742 // No moving animation is done if the item is animated by a create animation: This
1743 // prevents a "move animation mess" when inserting several ranges in parallel.
1744 applyNewPos
= !moveWidget(widget
, newPos
);
1746 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1747 // The size of the view might have been changed. Animate the moving of the position.
1748 applyNewPos
= !moveWidget(widget
, newPos
);
1751 m_animation
->stop(widget
);
1755 widget
->setPos(newPos
);
1758 Q_ASSERT(widget
->index() == i
);
1759 widget
->setVisible(true);
1761 if (widget
->size() != itemBounds
.size()) {
1762 // Resize the widget for the item to the changed size.
1764 // If a dynamic item size is used then no animation is done in the direction
1765 // of the dynamic size.
1766 if (m_itemSize
.width() <= 0) {
1767 // The width is dynamic, apply the new width without animation.
1768 widget
->resize(itemBounds
.width(), widget
->size().height());
1769 } else if (m_itemSize
.height() <= 0) {
1770 // The height is dynamic, apply the new height without animation.
1771 widget
->resize(widget
->size().width(), itemBounds
.height());
1773 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1775 widget
->resize(itemBounds
.size());
1779 // Updating the cell-information must be done as last step: The decision whether the
1780 // moving-animation should be started at all is based on the previous cell-information.
1781 const Cell
cell(m_layouter
->itemColumn(i
), m_layouter
->itemRow(i
));
1782 m_visibleCells
.insert(i
, cell
);
1785 // Delete invisible KItemListWidget instances that have not been reused
1786 foreach (int index
, reusableItems
) {
1787 recycleWidget(m_visibleItems
.value(index
));
1790 if (supportsExpanding
&& firstSibblingIndex
>= 0) {
1791 Q_ASSERT(lastSibblingIndex
>= 0);
1792 updateSiblingsInformation(firstSibblingIndex
, lastSibblingIndex
);
1796 // Update the layout of all visible group headers
1797 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_visibleGroups
);
1798 while (it
.hasNext()) {
1800 updateGroupHeaderLayout(it
.key());
1804 emitOffsetChanges();
1807 QList
<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex
,
1808 int lastVisibleIndex
,
1809 LayoutAnimationHint hint
)
1811 // Determine all items that are completely invisible and might be
1812 // reused for items that just got (at least partly) visible. If the
1813 // animation hint is set to 'Animation' items that do e.g. an animated
1814 // moving of their position are not marked as invisible: This assures
1815 // that a scrolling inside the view can be done without breaking an animation.
1819 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
1820 while (it
.hasNext()) {
1823 KItemListWidget
* widget
= it
.value();
1824 const int index
= widget
->index();
1825 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
1828 if (m_animation
->isStarted(widget
)) {
1829 if (hint
== NoAnimation
) {
1830 // Stopping the animation will call KItemListView::slotAnimationFinished()
1831 // and the widget will be recycled if necessary there.
1832 m_animation
->stop(widget
);
1835 widget
->setVisible(false);
1836 items
.append(index
);
1839 recycleGroupHeaderForWidget(widget
);
1848 bool KItemListView::moveWidget(KItemListWidget
* widget
,const QPointF
& newPos
)
1850 if (widget
->pos() == newPos
) {
1854 bool startMovingAnim
= false;
1856 if (m_itemSize
.isEmpty()) {
1857 // The items are not aligned in a grid but either as columns or rows.
1858 startMovingAnim
= true;
1860 // When having a grid the moving-animation should only be started, if it is done within
1861 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1862 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1863 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1864 const int index
= widget
->index();
1865 const Cell cell
= m_visibleCells
.value(index
);
1866 if (cell
.column
>= 0 && cell
.row
>= 0) {
1867 if (scrollOrientation() == Qt::Vertical
) {
1868 startMovingAnim
= (cell
.row
== m_layouter
->itemRow(index
));
1870 startMovingAnim
= (cell
.column
== m_layouter
->itemColumn(index
));
1875 if (startMovingAnim
) {
1876 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1880 m_animation
->stop(widget
);
1881 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1885 void KItemListView::emitOffsetChanges()
1887 const qreal newScrollOffset
= m_layouter
->scrollOffset();
1888 if (m_oldScrollOffset
!= newScrollOffset
) {
1889 emit
scrollOffsetChanged(newScrollOffset
, m_oldScrollOffset
);
1890 m_oldScrollOffset
= newScrollOffset
;
1893 const qreal newMaximumScrollOffset
= m_layouter
->maximumScrollOffset();
1894 if (m_oldMaximumScrollOffset
!= newMaximumScrollOffset
) {
1895 emit
maximumScrollOffsetChanged(newMaximumScrollOffset
, m_oldMaximumScrollOffset
);
1896 m_oldMaximumScrollOffset
= newMaximumScrollOffset
;
1899 const qreal newItemOffset
= m_layouter
->itemOffset();
1900 if (m_oldItemOffset
!= newItemOffset
) {
1901 emit
itemOffsetChanged(newItemOffset
, m_oldItemOffset
);
1902 m_oldItemOffset
= newItemOffset
;
1905 const qreal newMaximumItemOffset
= m_layouter
->maximumItemOffset();
1906 if (m_oldMaximumItemOffset
!= newMaximumItemOffset
) {
1907 emit
maximumItemOffsetChanged(newMaximumItemOffset
, m_oldMaximumItemOffset
);
1908 m_oldMaximumItemOffset
= newMaximumItemOffset
;
1912 KItemListWidget
* KItemListView::createWidget(int index
)
1914 KItemListWidget
* widget
= widgetCreator()->create(this);
1915 widget
->setFlag(QGraphicsItem::ItemStacksBehindParent
);
1917 m_visibleItems
.insert(index
, widget
);
1918 m_visibleCells
.insert(index
, Cell());
1919 updateWidgetProperties(widget
, index
);
1920 initializeItemListWidget(widget
);
1924 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1927 recycleGroupHeaderForWidget(widget
);
1930 const int index
= widget
->index();
1931 m_visibleItems
.remove(index
);
1932 m_visibleCells
.remove(index
);
1934 widgetCreator()->recycle(widget
);
1937 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1939 const int oldIndex
= widget
->index();
1940 m_visibleItems
.remove(oldIndex
);
1941 m_visibleCells
.remove(oldIndex
);
1943 m_visibleItems
.insert(index
, widget
);
1944 m_visibleCells
.insert(index
, Cell());
1946 widget
->setIndex(index
);
1949 void KItemListView::moveWidgetToIndex(KItemListWidget
* widget
, int index
)
1951 const int oldIndex
= widget
->index();
1952 const Cell oldCell
= m_visibleCells
.value(oldIndex
);
1954 setWidgetIndex(widget
, index
);
1956 const Cell
newCell(m_layouter
->itemColumn(index
), m_layouter
->itemRow(index
));
1957 const bool vertical
= (scrollOrientation() == Qt::Vertical
);
1958 const bool updateCell
= (vertical
&& oldCell
.row
== newCell
.row
) ||
1959 (!vertical
&& oldCell
.column
== newCell
.column
);
1961 m_visibleCells
.insert(index
, newCell
);
1965 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1968 case LayouterSize
: m_layouter
->setSize(size
); break;
1969 case ItemSize
: m_layouter
->setItemSize(size
); break;
1974 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1976 widget
->setVisibleRoles(m_visibleRoles
);
1977 updateWidgetColumnWidths(widget
);
1978 widget
->setStyleOption(m_styleOption
);
1980 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1981 widget
->setCurrent(index
== selectionManager
->currentItem());
1982 widget
->setSelected(selectionManager
->isSelected(index
));
1983 widget
->setHovered(false);
1984 widget
->setEnabledSelectionToggle(enabledSelectionToggles());
1985 widget
->setIndex(index
);
1986 widget
->setData(m_model
->data(index
));
1987 widget
->setSiblingsInformation(QBitArray());
1988 updateAlternateBackgroundForWidget(widget
);
1991 updateGroupHeaderForWidget(widget
);
1995 void KItemListView::updateGroupHeaderForWidget(KItemListWidget
* widget
)
1997 Q_ASSERT(m_grouped
);
1999 const int index
= widget
->index();
2000 if (!m_layouter
->isFirstGroupItem(index
)) {
2001 // The widget does not represent the first item of a group
2002 // and hence requires no header
2003 recycleGroupHeaderForWidget(widget
);
2007 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2008 if (groups
.isEmpty() || !groupHeaderCreator()) {
2012 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2014 groupHeader
= groupHeaderCreator()->create(this);
2015 groupHeader
->setParentItem(widget
);
2016 m_visibleGroups
.insert(widget
, groupHeader
);
2017 connect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2019 Q_ASSERT(groupHeader
->parentItem() == widget
);
2021 const int groupIndex
= groupIndexForItem(index
);
2022 Q_ASSERT(groupIndex
>= 0);
2023 groupHeader
->setData(groups
.at(groupIndex
).second
);
2024 groupHeader
->setRole(model()->sortRole());
2025 groupHeader
->setStyleOption(m_styleOption
);
2026 groupHeader
->setScrollOrientation(scrollOrientation());
2027 groupHeader
->setItemIndex(index
);
2029 groupHeader
->show();
2032 void KItemListView::updateGroupHeaderLayout(KItemListWidget
* widget
)
2034 KItemListGroupHeader
* groupHeader
= m_visibleGroups
.value(widget
);
2035 Q_ASSERT(groupHeader
);
2037 const int index
= widget
->index();
2038 const QRectF groupHeaderRect
= m_layouter
->groupHeaderRect(index
);
2039 const QRectF itemRect
= m_layouter
->itemRect(index
);
2041 // The group-header is a child of the itemlist widget. Translate the
2042 // group header position to the relative position.
2043 if (scrollOrientation() == Qt::Vertical
) {
2044 // In the vertical scroll orientation the group header should always span
2045 // the whole width no matter which temporary position the parent widget
2046 // has. In this case the x-position and width will be adjusted manually.
2047 const qreal x
= -widget
->x() - itemOffset();
2048 const qreal width
= maximumItemOffset();
2049 groupHeader
->setPos(x
, -groupHeaderRect
.height());
2050 groupHeader
->resize(width
, groupHeaderRect
.size().height());
2052 groupHeader
->setPos(groupHeaderRect
.x() - itemRect
.x(), -widget
->y());
2053 groupHeader
->resize(groupHeaderRect
.size());
2057 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget
* widget
)
2059 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
2061 header
->setParentItem(0);
2062 groupHeaderCreator()->recycle(header
);
2063 m_visibleGroups
.remove(widget
);
2064 disconnect(widget
, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2068 void KItemListView::updateVisibleGroupHeaders()
2070 Q_ASSERT(m_grouped
);
2071 m_layouter
->markAsDirty();
2073 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2074 while (it
.hasNext()) {
2076 updateGroupHeaderForWidget(it
.value());
2080 int KItemListView::groupIndexForItem(int index
) const
2082 Q_ASSERT(m_grouped
);
2084 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2085 if (groups
.isEmpty()) {
2090 int max
= groups
.count() - 1;
2093 mid
= (min
+ max
) / 2;
2094 if (index
> groups
[mid
].first
) {
2099 } while (groups
[mid
].first
!= index
&& min
<= max
);
2102 while (groups
[mid
].first
> index
&& mid
> 0) {
2110 void KItemListView::updateAlternateBackgrounds()
2112 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2113 while (it
.hasNext()) {
2115 updateAlternateBackgroundForWidget(it
.value());
2119 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget
* widget
)
2121 bool enabled
= useAlternateBackgrounds();
2123 const int index
= widget
->index();
2124 enabled
= (index
& 0x1) > 0;
2126 const int groupIndex
= groupIndexForItem(index
);
2127 if (groupIndex
>= 0) {
2128 const QList
<QPair
<int, QVariant
> > groups
= model()->groups();
2129 const int indexOfFirstGroupItem
= groups
[groupIndex
].first
;
2130 const int relativeIndex
= index
- indexOfFirstGroupItem
;
2131 enabled
= (relativeIndex
& 0x1) > 0;
2135 widget
->setAlternateBackground(enabled
);
2138 bool KItemListView::useAlternateBackgrounds() const
2140 return m_itemSize
.isEmpty() && m_visibleRoles
.count() > 1;
2143 QHash
<QByteArray
, qreal
> KItemListView::preferredColumnWidths(const KItemRangeList
& itemRanges
) const
2145 QElapsedTimer timer
;
2148 QHash
<QByteArray
, qreal
> widths
;
2150 // Calculate the minimum width for each column that is required
2151 // to show the headline unclipped.
2152 const QFontMetricsF
fontMetrics(m_headerWidget
->font());
2153 const int gripMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderGripMargin
);
2154 const int headerMargin
= m_headerWidget
->style()->pixelMetric(QStyle::PM_HeaderMargin
);
2155 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2156 const QString headerText
= m_model
->roleDescription(visibleRole
);
2157 const qreal headerWidth
= fontMetrics
.width(headerText
) + gripMargin
+ headerMargin
* 2;
2158 widths
.insert(visibleRole
, headerWidth
);
2161 // Calculate the preferred column withs for each item and ignore values
2162 // smaller than the width for showing the headline unclipped.
2163 const KItemListWidgetCreatorBase
* creator
= widgetCreator();
2164 int calculatedItemCount
= 0;
2165 bool maxTimeExceeded
= false;
2166 foreach (const KItemRange
& itemRange
, itemRanges
) {
2167 const int startIndex
= itemRange
.index
;
2168 const int endIndex
= startIndex
+ itemRange
.count
- 1;
2170 for (int i
= startIndex
; i
<= endIndex
; ++i
) {
2171 foreach (const QByteArray
& visibleRole
, visibleRoles()) {
2172 qreal maxWidth
= widths
.value(visibleRole
, 0);
2173 const qreal width
= creator
->preferredRoleColumnWidth(visibleRole
, i
, this);
2174 maxWidth
= qMax(width
, maxWidth
);
2175 widths
.insert(visibleRole
, maxWidth
);
2178 if (calculatedItemCount
> 100 && timer
.elapsed() > 200) {
2179 // When having several thousands of items calculating the sizes can get
2180 // very expensive. We accept a possibly too small role-size in favour
2181 // of having no blocking user interface.
2182 maxTimeExceeded
= true;
2185 ++calculatedItemCount
;
2187 if (maxTimeExceeded
) {
2195 void KItemListView::applyColumnWidthsFromHeader()
2197 // Apply the new size to the layouter
2198 const qreal requiredWidth
= columnWidthsSum();
2199 const QSizeF
dynamicItemSize(qMax(size().width(), requiredWidth
),
2200 m_itemSize
.height());
2201 m_layouter
->setItemSize(dynamicItemSize
);
2203 // Update the role sizes for all visible widgets
2204 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2205 while (it
.hasNext()) {
2207 updateWidgetColumnWidths(it
.value());
2211 void KItemListView::updateWidgetColumnWidths(KItemListWidget
* widget
)
2213 foreach (const QByteArray
& role
, m_visibleRoles
) {
2214 widget
->setColumnWidth(role
, m_headerWidget
->columnWidth(role
));
2218 void KItemListView::updatePreferredColumnWidths(const KItemRangeList
& itemRanges
)
2220 Q_ASSERT(m_itemSize
.isEmpty());
2221 const int itemCount
= m_model
->count();
2222 int rangesItemCount
= 0;
2223 foreach (const KItemRange
& range
, itemRanges
) {
2224 rangesItemCount
+= range
.count
;
2227 if (itemCount
== rangesItemCount
) {
2228 const QHash
<QByteArray
, qreal
> preferredWidths
= preferredColumnWidths(itemRanges
);
2229 foreach (const QByteArray
& role
, m_visibleRoles
) {
2230 m_headerWidget
->setPreferredColumnWidth(role
, preferredWidths
.value(role
));
2233 // Only a sub range of the roles need to be determined.
2234 // The chances are good that the widths of the sub ranges
2235 // already fit into the available widths and hence no
2236 // expensive update might be required.
2237 bool changed
= false;
2239 const QHash
<QByteArray
, qreal
> updatedWidths
= preferredColumnWidths(itemRanges
);
2240 QHashIterator
<QByteArray
, qreal
> it(updatedWidths
);
2241 while (it
.hasNext()) {
2243 const QByteArray
& role
= it
.key();
2244 const qreal updatedWidth
= it
.value();
2245 const qreal currentWidth
= m_headerWidget
->preferredColumnWidth(role
);
2246 if (updatedWidth
> currentWidth
) {
2247 m_headerWidget
->setPreferredColumnWidth(role
, updatedWidth
);
2253 // All the updated sizes are smaller than the current sizes and no change
2254 // of the stretched roles-widths is required
2259 if (m_headerWidget
->automaticColumnResizing()) {
2260 applyAutomaticColumnWidths();
2264 void KItemListView::updatePreferredColumnWidths()
2267 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model
->count()));
2271 void KItemListView::applyAutomaticColumnWidths()
2273 Q_ASSERT(m_itemSize
.isEmpty());
2274 Q_ASSERT(m_headerWidget
->automaticColumnResizing());
2275 if (m_visibleRoles
.isEmpty()) {
2279 // Calculate the maximum size of an item by considering the
2280 // visible role sizes and apply them to the layouter. If the
2281 // size does not use the available view-size the size of the
2282 // first role will get stretched.
2284 foreach (const QByteArray
& role
, m_visibleRoles
) {
2285 const qreal preferredWidth
= m_headerWidget
->preferredColumnWidth(role
);
2286 m_headerWidget
->setColumnWidth(role
, preferredWidth
);
2289 const QByteArray firstRole
= m_visibleRoles
.first();
2290 qreal firstColumnWidth
= m_headerWidget
->columnWidth(firstRole
);
2291 QSizeF dynamicItemSize
= m_itemSize
;
2293 qreal requiredWidth
= columnWidthsSum();
2294 const qreal availableWidth
= size().width();
2295 if (requiredWidth
< availableWidth
) {
2296 // Stretch the first column to use the whole remaining width
2297 firstColumnWidth
+= availableWidth
- requiredWidth
;
2298 m_headerWidget
->setColumnWidth(firstRole
, firstColumnWidth
);
2299 } else if (requiredWidth
> availableWidth
&& m_visibleRoles
.count() > 1) {
2300 // Shrink the first column to be able to show as much other
2301 // columns as possible
2302 qreal shrinkedFirstColumnWidth
= firstColumnWidth
- requiredWidth
+ availableWidth
;
2304 // TODO: A proper calculation of the minimum width depends on the implementation
2305 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2307 const qreal minWidth
= qMin(firstColumnWidth
, qreal(m_styleOption
.iconSize
* 2 + 200));
2308 if (shrinkedFirstColumnWidth
< minWidth
) {
2309 shrinkedFirstColumnWidth
= minWidth
;
2312 m_headerWidget
->setColumnWidth(firstRole
, shrinkedFirstColumnWidth
);
2313 requiredWidth
-= firstColumnWidth
- shrinkedFirstColumnWidth
;
2316 dynamicItemSize
.rwidth() = qMax(requiredWidth
, availableWidth
);
2318 m_layouter
->setItemSize(dynamicItemSize
);
2320 // Update the role sizes for all visible widgets
2321 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2322 while (it
.hasNext()) {
2324 updateWidgetColumnWidths(it
.value());
2328 qreal
KItemListView::columnWidthsSum() const
2330 qreal widthsSum
= 0;
2331 foreach (const QByteArray
& role
, m_visibleRoles
) {
2332 widthsSum
+= m_headerWidget
->columnWidth(role
);
2337 QRectF
KItemListView::headerBoundaries() const
2339 return m_headerWidget
->isVisible() ? m_headerWidget
->geometry() : QRectF();
2342 bool KItemListView::changesItemGridLayout(const QSizeF
& newGridSize
,
2343 const QSizeF
& newItemSize
,
2344 const QSizeF
& newItemMargin
) const
2346 if (newItemSize
.isEmpty() || newGridSize
.isEmpty()) {
2350 if (m_layouter
->scrollOrientation() == Qt::Vertical
) {
2351 const qreal itemWidth
= m_layouter
->itemSize().width();
2352 if (itemWidth
> 0) {
2353 const int newColumnCount
= itemsPerSize(newGridSize
.width(),
2354 newItemSize
.width(),
2355 newItemMargin
.width());
2356 if (m_model
->count() > newColumnCount
) {
2357 const int oldColumnCount
= itemsPerSize(m_layouter
->size().width(),
2359 m_layouter
->itemMargin().width());
2360 return oldColumnCount
!= newColumnCount
;
2364 const qreal itemHeight
= m_layouter
->itemSize().height();
2365 if (itemHeight
> 0) {
2366 const int newRowCount
= itemsPerSize(newGridSize
.height(),
2367 newItemSize
.height(),
2368 newItemMargin
.height());
2369 if (m_model
->count() > newRowCount
) {
2370 const int oldRowCount
= itemsPerSize(m_layouter
->size().height(),
2372 m_layouter
->itemMargin().height());
2373 return oldRowCount
!= newRowCount
;
2381 bool KItemListView::animateChangedItemCount(int changedItemCount
) const
2383 if (m_itemSize
.isEmpty()) {
2384 // We have only columns or only rows, but no grid: An animation is usually
2385 // welcome when inserting or removing items.
2386 return !supportsItemExpanding();
2389 if (m_layouter
->size().isEmpty() || m_layouter
->itemSize().isEmpty()) {
2393 const int maximum
= (scrollOrientation() == Qt::Vertical
)
2394 ? m_layouter
->size().width() / m_layouter
->itemSize().width()
2395 : m_layouter
->size().height() / m_layouter
->itemSize().height();
2396 // Only animate if up to 2/3 of a row or column are inserted or removed
2397 return changedItemCount
<= maximum
* 2 / 3;
2401 bool KItemListView::scrollBarRequired(const QSizeF
& size
) const
2403 const QSizeF oldSize
= m_layouter
->size();
2405 m_layouter
->setSize(size
);
2406 const qreal maxOffset
= m_layouter
->maximumScrollOffset();
2407 m_layouter
->setSize(oldSize
);
2409 return m_layouter
->scrollOrientation() == Qt::Vertical
? maxOffset
> size
.height()
2410 : maxOffset
> size
.width();
2413 int KItemListView::showDropIndicator(const QPointF
& pos
)
2415 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
2416 while (it
.hasNext()) {
2418 const KItemListWidget
* widget
= it
.value();
2420 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
2421 const QRectF rect
= itemRect(widget
->index());
2422 if (mappedPos
.y() >= 0 && mappedPos
.y() <= rect
.height()) {
2423 if (m_model
->supportsDropping(widget
->index())) {
2424 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2425 const int gap
= qMax(4.0, 0.3 * rect
.height());
2426 if (mappedPos
.y() >= gap
&& mappedPos
.y() <= rect
.height() - gap
) {
2431 const bool isAboveItem
= (mappedPos
.y () < rect
.height() / 2);
2432 const qreal y
= isAboveItem
? rect
.top() : rect
.bottom();
2434 const QRectF
draggingInsertIndicator(rect
.left(), y
, rect
.width(), 1);
2435 if (m_dropIndicator
!= draggingInsertIndicator
) {
2436 m_dropIndicator
= draggingInsertIndicator
;
2440 int index
= widget
->index();
2448 const QRectF firstItemRect
= itemRect(firstVisibleIndex());
2449 return (pos
.y() <= firstItemRect
.top()) ? 0 : -1;
2452 void KItemListView::hideDropIndicator()
2454 if (!m_dropIndicator
.isNull()) {
2455 m_dropIndicator
= QRectF();
2460 void KItemListView::updateGroupHeaderHeight()
2462 qreal groupHeaderHeight
= m_styleOption
.fontMetrics
.height();
2463 qreal groupHeaderMargin
= 0;
2465 if (scrollOrientation() == Qt::Horizontal
) {
2466 // The vertical margin above and below the header should be
2467 // equal to the horizontal margin, not the vertical margin
2468 // from m_styleOption.
2469 groupHeaderHeight
+= 2 * m_styleOption
.horizontalMargin
;
2470 groupHeaderMargin
= m_styleOption
.horizontalMargin
;
2471 } else if (m_itemSize
.isEmpty()){
2472 groupHeaderHeight
+= 4 * m_styleOption
.padding
;
2473 groupHeaderMargin
= m_styleOption
.iconSize
/ 2;
2475 groupHeaderHeight
+= 2 * m_styleOption
.padding
+ m_styleOption
.verticalMargin
;
2476 groupHeaderMargin
= m_styleOption
.iconSize
/ 4;
2478 m_layouter
->setGroupHeaderHeight(groupHeaderHeight
);
2479 m_layouter
->setGroupHeaderMargin(groupHeaderMargin
);
2481 updateVisibleGroupHeaders();
2484 void KItemListView::updateSiblingsInformation(int firstIndex
, int lastIndex
)
2486 if (!supportsItemExpanding() || !m_model
) {
2490 if (firstIndex
< 0 || lastIndex
< 0) {
2491 firstIndex
= m_layouter
->firstVisibleIndex();
2492 lastIndex
= m_layouter
->lastVisibleIndex();
2494 const bool isRangeVisible
= (firstIndex
<= m_layouter
->lastVisibleIndex() &&
2495 lastIndex
>= m_layouter
->firstVisibleIndex());
2496 if (!isRangeVisible
) {
2501 int previousParents
= 0;
2502 QBitArray previousSiblings
;
2504 // The rootIndex describes the first index where the siblings get
2505 // calculated from. For the calculation the upper most parent item
2506 // is required. For performance reasons it is checked first whether
2507 // the visible items before or after the current range already
2508 // contain a siblings information which can be used as base.
2509 int rootIndex
= firstIndex
;
2511 KItemListWidget
* widget
= m_visibleItems
.value(firstIndex
- 1);
2513 // There is no visible widget before the range, check whether there
2514 // is one after the range:
2515 widget
= m_visibleItems
.value(lastIndex
+ 1);
2517 // The sibling information of the widget may only be used if
2518 // all items of the range have the same number of parents.
2519 const int parents
= m_model
->expandedParentsCount(lastIndex
+ 1);
2520 for (int i
= lastIndex
; i
>= firstIndex
; --i
) {
2521 if (m_model
->expandedParentsCount(i
) != parents
) {
2530 // Performance optimization: Use the sibling information of the visible
2531 // widget beside the given range.
2532 previousSiblings
= widget
->siblingsInformation();
2533 if (previousSiblings
.isEmpty()) {
2536 previousParents
= previousSiblings
.count() - 1;
2537 previousSiblings
.truncate(previousParents
);
2539 // Potentially slow path: Go back to the upper most parent of firstIndex
2540 // to be able to calculate the initial value for the siblings.
2541 while (rootIndex
> 0 && m_model
->expandedParentsCount(rootIndex
) > 0) {
2546 Q_ASSERT(previousParents
>= 0);
2547 for (int i
= rootIndex
; i
<= lastIndex
; ++i
) {
2548 // Update the parent-siblings in case if the current item represents
2549 // a child or an upper parent.
2550 const int currentParents
= m_model
->expandedParentsCount(i
);
2551 Q_ASSERT(currentParents
>= 0);
2552 if (previousParents
< currentParents
) {
2553 previousParents
= currentParents
;
2554 previousSiblings
.resize(currentParents
);
2555 previousSiblings
.setBit(currentParents
- 1, hasSiblingSuccessor(i
- 1));
2556 } else if (previousParents
> currentParents
) {
2557 previousParents
= currentParents
;
2558 previousSiblings
.truncate(currentParents
);
2561 if (i
>= firstIndex
) {
2562 // The index represents a visible item. Apply the parent-siblings
2563 // and update the sibling of the current item.
2564 KItemListWidget
* widget
= m_visibleItems
.value(i
);
2569 QBitArray siblings
= previousSiblings
;
2570 siblings
.resize(siblings
.count() + 1);
2571 siblings
.setBit(siblings
.count() - 1, hasSiblingSuccessor(i
));
2573 widget
->setSiblingsInformation(siblings
);
2578 bool KItemListView::hasSiblingSuccessor(int index
) const
2580 bool hasSuccessor
= false;
2581 const int parentsCount
= m_model
->expandedParentsCount(index
);
2582 int successorIndex
= index
+ 1;
2584 // Search the next sibling
2585 const int itemCount
= m_model
->count();
2586 while (successorIndex
< itemCount
) {
2587 const int currentParentsCount
= m_model
->expandedParentsCount(successorIndex
);
2588 if (currentParentsCount
== parentsCount
) {
2589 hasSuccessor
= true;
2591 } else if (currentParentsCount
< parentsCount
) {
2597 if (m_grouped
&& hasSuccessor
) {
2598 // If the sibling is part of another group, don't mark it as
2599 // successor as the group header is between the sibling connections.
2600 for (int i
= index
+ 1; i
<= successorIndex
; ++i
) {
2601 if (m_layouter
->isFirstGroupItem(i
)) {
2602 hasSuccessor
= false;
2608 return hasSuccessor
;
2611 void KItemListView::disconnectRoleEditingSignals(int index
)
2613 KItemListWidget
* widget
= m_visibleItems
.value(index
);
2618 widget
->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)), this);
2619 widget
->disconnect(SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)), this);
2622 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
2626 const int minSpeed
= 4;
2627 const int maxSpeed
= 128;
2628 const int speedLimiter
= 96;
2629 const int autoScrollBorder
= 64;
2631 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2632 // This assures that the autoscrolling speed grows gradually.
2633 const int incLimiter
= 1;
2635 if (pos
< autoScrollBorder
) {
2636 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
2637 inc
= qMax(inc
, -maxSpeed
);
2638 inc
= qMax(inc
, oldInc
- incLimiter
);
2639 } else if (pos
> range
- autoScrollBorder
) {
2640 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
2641 inc
= qMin(inc
, maxSpeed
);
2642 inc
= qMin(inc
, oldInc
+ incLimiter
);
2648 int KItemListView::itemsPerSize(qreal size
, qreal itemSize
, qreal itemMargin
)
2650 const qreal availableSize
= size
- itemMargin
;
2651 const int count
= availableSize
/ (itemSize
+ itemMargin
);
2657 KItemListCreatorBase::~KItemListCreatorBase()
2659 qDeleteAll(m_recycleableWidgets
);
2660 qDeleteAll(m_createdWidgets
);
2663 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
2665 m_createdWidgets
.insert(widget
);
2668 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
2670 Q_ASSERT(m_createdWidgets
.contains(widget
));
2671 m_createdWidgets
.remove(widget
);
2673 if (m_recycleableWidgets
.count() < 100) {
2674 m_recycleableWidgets
.append(widget
);
2675 widget
->setVisible(false);
2681 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
2683 if (m_recycleableWidgets
.isEmpty()) {
2687 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
2688 m_createdWidgets
.insert(widget
);
2692 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2696 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
2698 widget
->setParentItem(0);
2699 widget
->setOpacity(1.0);
2700 pushRecycleableWidget(widget
);
2703 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2707 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
2709 header
->setOpacity(1.0);
2710 pushRecycleableWidget(header
);
2713 #include "kitemlistview.moc"