2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
41 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
42 case KStandardItemListView::IconsLayout
:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
46 case KStandardItemListView::CompactLayout
:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
50 case KStandardItemListView::DetailsLayout
:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
60 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
62 const KItemListView
* view
) const
64 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
65 const KItemListStyleOption
& option
= view
->styleOption();
67 const QString text
= roleText(role
, values
);
68 qreal width
= KStandardItemListWidget::columnPadding(option
);
70 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
71 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
73 if (role
== "rating") {
74 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
76 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
77 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
79 width
+= fontMetrics
.horizontalAdvance(text
);
82 if (view
->supportsItemExpanding()) {
83 // Increase the width by the expansion-toggle and the current expansion level
84 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
85 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
86 width
+= (expandedParentsCount
+ 1) * height
;
89 // Increase the width by the required space for the icon
90 width
+= option
.padding
* 2 + option
.iconSize
;
97 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
* view
) const
99 return view
->model()->data(index
).value("text").toString();
102 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
* view
) const
109 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
110 const QHash
<QByteArray
, QVariant
>& values
) const
112 if (role
== "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
116 return values
.value(role
).toString();
119 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
& baseFont
) const
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
126 const KItemListStyleOption
& option
= view
->styleOption();
127 const QFont
& normalFont
= option
.font
;
128 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
130 const qreal itemWidth
= view
->itemSize().width();
131 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
132 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
133 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
135 const QFont linkFont
= customizedFontForLinks(normalFont
);
137 QTextOption
textOption(Qt::AlignHCenter
);
138 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
140 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
141 if (logicalHeightHints
.at(index
).first
> 0.0) {
145 // If the current item is a link, we use the customized link font instead of the normal font.
146 const QFont
& font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
148 const QString
& text
= KStringHandler::preProcessWrap(itemText(index
, view
));
150 // Calculate the number of lines required for wrapping the name
151 qreal textHeight
= 0;
152 QTextLayout
layout(text
, font
);
153 layout
.setTextOption(textOption
);
154 layout
.beginLayout();
157 bool isElided
= false;
158 while ((line
= layout
.createLine()).isValid()) {
159 line
.setLineWidth(maxWidth
);
160 line
.naturalTextWidth();
161 textHeight
+= line
.height();
164 if (lineCount
== option
.maxTextLines
) {
165 isElided
= layout
.createLine().isValid();
171 // Add one line for each additional information
172 textHeight
+= additionalRolesSpacing
;
174 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
175 logicalHeightHints
[index
].second
= isElided
;
178 logicalWidthHint
= itemWidth
;
181 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
183 const KItemListStyleOption
& option
= view
->styleOption();
184 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
185 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
187 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
188 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
189 const qreal maxWidth
= option
.maxTextWidth
;
190 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
191 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
193 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
195 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
196 if (logicalHeightHints
.at(index
).first
> 0.0) {
200 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
201 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
203 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
204 // to show all roles without horizontal clipping.
205 qreal maximumRequiredWidth
= 0.0;
207 if (showOnlyTextRole
) {
208 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
210 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
211 for (const QByteArray
& role
: visibleRoles
) {
212 const QString
& text
= roleText(role
, values
);
213 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
214 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
218 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
219 if (maxWidth
> 0 && width
> maxWidth
) {
223 logicalHeightHints
[index
].first
= width
;
226 logicalWidthHint
= height
;
229 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
231 const KItemListStyleOption
& option
= view
->styleOption();
234 if (option
.iconSize
>= KIconLoader::SizeEnormous
) {
236 } else if (option
.iconSize
>= KIconLoader::SizeHuge
) {
238 } else if (option
.iconSize
>= KIconLoader::SizeLarge
) {
240 } else if (option
.iconSize
>= KIconLoader::SizeMedium
) {
242 } else if (option
.iconSize
>= KIconLoader::SizeSmallMedium
) {
246 const qreal contentHeight
= qMax
<qreal
>(option
.iconSize
, zoomLevel
* option
.fontMetrics
.height());
247 logicalHeightHints
.fill(std::make_pair(contentHeight
+ 2 * option
.padding
, false));
248 logicalWidthHint
= -1.0;
251 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
252 KItemListWidget(informant
, parent
),
257 m_customizedFontMetrics(m_customizedFont
),
258 m_isExpandable(false),
259 m_supportsItemExpanding(false),
261 m_dirtyContent(true),
262 m_dirtyContentRoles(),
263 m_layout(IconsLayout
),
266 m_scaledPixmapSize(),
270 m_sortedVisibleRoles(),
273 m_additionalInfoTextColor(),
276 m_roleEditor(nullptr),
277 m_oldRoleEditor(nullptr)
281 KStandardItemListWidget::~KStandardItemListWidget()
283 qDeleteAll(m_textInfo
);
287 m_roleEditor
->deleteLater();
290 if (m_oldRoleEditor
) {
291 m_oldRoleEditor
->deleteLater();
295 void KStandardItemListWidget::setLayout(Layout layout
)
297 if (m_layout
!= layout
) {
299 m_dirtyLayout
= true;
300 updateAdditionalInfoTextColor();
305 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
310 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
312 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
313 m_supportsItemExpanding
= supportsItemExpanding
;
314 m_dirtyLayout
= true;
319 bool KStandardItemListWidget::supportsItemExpanding() const
321 return m_supportsItemExpanding
;
324 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
326 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
328 KItemListWidget::paint(painter
, option
, widget
);
330 if (!m_expansionArea
.isEmpty()) {
331 drawSiblingsInformation(painter
);
334 const KItemListStyleOption
& itemListStyleOption
= styleOption();
335 if (isHovered() && !m_pixmap
.isNull()) {
336 if (hoverOpacity() < 1.0) {
338 * Linear interpolation between m_pixmap and m_hoverPixmap.
340 * Note that this cannot be achieved by painting m_hoverPixmap over
341 * m_pixmap, even if the opacities are adjusted. For details see
342 * https://git.reviewboard.kde.org/r/109614/
344 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
345 QPixmap
pixmap1(m_pixmap
.size());
346 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
347 pixmap1
.fill(Qt::transparent
);
349 QPainter
p(&pixmap1
);
350 p
.setOpacity(1.0 - hoverOpacity());
351 p
.drawPixmap(0, 0, m_pixmap
);
354 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
355 QPixmap
pixmap2(pixmap1
.size());
356 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
357 pixmap2
.fill(Qt::transparent
);
359 QPainter
p(&pixmap2
);
360 p
.setOpacity(hoverOpacity());
361 p
.drawPixmap(0, 0, m_hoverPixmap
);
364 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
365 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
366 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
368 QPainter
p(&pixmap1
);
369 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
370 p
.drawPixmap(0, 0, pixmap2
);
373 // Finally paint pixmap1 on the widget
374 drawPixmap(painter
, pixmap1
);
376 drawPixmap(painter
, m_hoverPixmap
);
378 } else if (!m_pixmap
.isNull()) {
379 drawPixmap(painter
, m_pixmap
);
382 painter
->setFont(m_customizedFont
);
383 painter
->setPen(textColor());
384 const TextInfo
* textInfo
= m_textInfo
.value("text");
387 // It seems that we can end up here even if m_textInfo does not contain
388 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
389 // this can only happen if the index is negative. This can happen when
390 // the item is about to be removed, see KItemListView::slotItemsRemoved().
391 // TODO: try to reproduce the crash and find a better fix.
395 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
397 bool clipAdditionalInfoBounds
= false;
398 if (m_supportsItemExpanding
) {
399 // Prevent a possible overlapping of the additional-information texts
400 // with the icon. This can happen if the user has minimized the width
401 // of the name-column to a very small value.
402 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
403 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
404 clipAdditionalInfoBounds
= true;
406 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
410 painter
->setPen(m_additionalInfoTextColor
);
411 painter
->setFont(m_customizedFont
);
413 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
414 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
415 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
418 if (!m_rating
.isNull()) {
419 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
420 QPointF pos
= ratingTextInfo
->pos
;
421 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
422 if (align
& Qt::AlignHCenter
) {
423 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
425 painter
->drawPixmap(pos
, m_rating
);
428 if (clipAdditionalInfoBounds
) {
432 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
433 painter
->setBrush(Qt::NoBrush
);
434 painter
->setPen(Qt::green
);
435 painter
->drawRect(m_iconRect
);
437 painter
->setPen(Qt::blue
);
438 painter
->drawRect(m_textRect
);
440 painter
->setPen(Qt::red
);
441 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
442 painter
->drawRect(rect());
446 QRectF
KStandardItemListWidget::iconRect() const
448 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
452 QRectF
KStandardItemListWidget::textRect() const
454 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
458 QRectF
KStandardItemListWidget::textFocusRect() const
460 // In the compact- and details-layout a larger textRect() is returned to be aligned
461 // with the iconRect(). This is useful to have a larger selection/hover-area
462 // when having a quite large icon size but only one line of text. Still the
463 // focus rectangle should be shown as narrow as possible around the text.
465 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
468 case CompactLayout
: {
469 QRectF rect
= m_textRect
;
470 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
471 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
472 rect
.setTop(topText
->pos
.y());
473 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
477 case DetailsLayout
: {
478 QRectF rect
= m_textRect
;
479 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
480 rect
.setTop(textInfo
->pos
.y());
481 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
483 const KItemListStyleOption
& option
= styleOption();
484 if (option
.extendedSelectionRegion
) {
485 const QString text
= textInfo
->staticText
.text();
486 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
499 QRectF
KStandardItemListWidget::selectionRect() const
501 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
508 case DetailsLayout
: {
509 const int padding
= styleOption().padding
;
510 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
511 return adjustedIconRect
| m_textRect
;
522 QRectF
KStandardItemListWidget::expansionToggleRect() const
524 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
525 return m_isExpandable
? m_expansionArea
: QRectF();
528 QRectF
KStandardItemListWidget::selectionToggleRect() const
530 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
532 const int iconHeight
= styleOption().iconSize
;
534 int toggleSize
= KIconLoader::SizeSmall
;
535 if (iconHeight
>= KIconLoader::SizeEnormous
) {
536 toggleSize
= KIconLoader::SizeMedium
;
537 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
538 toggleSize
= KIconLoader::SizeSmallMedium
;
541 QPointF pos
= iconRect().topLeft();
543 // If the selection toggle has a very small distance to the
544 // widget borders, the size of the selection toggle will get
545 // increased to prevent an accidental clicking of the item
546 // when trying to hit the toggle.
547 const int widgetHeight
= size().height();
548 const int widgetWidth
= size().width();
549 const int minMargin
= 2;
551 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
552 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
553 toggleSize
= widgetHeight
;
556 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
557 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
558 toggleSize
= widgetWidth
;
562 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
565 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
568 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
569 if (m_layout
!= DetailsLayout
) {
573 // Only return the content of the text-column as pixmap
574 const int leftClip
= m_pixmapPos
.x();
576 const TextInfo
* textInfo
= m_textInfo
.value("text");
577 const int rightClip
= textInfo
->pos
.x() +
578 textInfo
->staticText
.size().width() +
579 2 * styleOption().padding
;
581 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
582 clippedPixmap
.fill(Qt::transparent
);
584 QPainter
painter(&clippedPixmap
);
585 painter
.drawPixmap(-leftClip
, 0, pixmap
);
587 return clippedPixmap
;
591 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
593 return new KStandardItemListWidgetInformant();
596 void KStandardItemListWidget::invalidateCache()
598 m_dirtyLayout
= true;
599 m_dirtyContent
= true;
602 void KStandardItemListWidget::invalidateIconCache()
604 m_dirtyContent
= true;
605 m_dirtyContentRoles
.insert("iconPixmap");
606 m_dirtyContentRoles
.insert("iconOverlays");
609 void KStandardItemListWidget::refreshCache()
613 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
619 bool KStandardItemListWidget::isHidden() const
624 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
629 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
631 return QPalette::Text
;
634 void KStandardItemListWidget::setTextColor(const QColor
& color
)
636 if (color
!= m_customTextColor
) {
637 m_customTextColor
= color
;
638 updateAdditionalInfoTextColor();
643 QColor
KStandardItemListWidget::textColor() const
647 return m_additionalInfoTextColor
;
648 } else if (m_customTextColor
.isValid()) {
649 return m_customTextColor
;
653 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
654 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
655 return styleOption().palette
.color(group
, role
);
658 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
661 m_dirtyContent
= true;
665 QPixmap
KStandardItemListWidget::overlay() const
671 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
672 const QHash
<QByteArray
, QVariant
>& values
) const
674 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
677 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
678 const QSet
<QByteArray
>& roles
)
682 m_dirtyContent
= true;
684 QSet
<QByteArray
> dirtyRoles
;
685 if (roles
.isEmpty()) {
686 const auto visibleRoles
= this->visibleRoles();
687 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
692 // The URL might have changed (i.e., if the sort order of the items has
693 // been changed). Therefore, the "is cut" state must be updated.
694 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
695 const QUrl itemUrl
= data().value("url").toUrl();
696 m_isCut
= clipboard
->isCut(itemUrl
);
698 // The icon-state might depend from other roles and hence is
699 // marked as dirty whenever a role has been changed
700 dirtyRoles
.insert("iconPixmap");
701 dirtyRoles
.insert("iconName");
703 QSetIterator
<QByteArray
> it(dirtyRoles
);
704 while (it
.hasNext()) {
705 const QByteArray
& role
= it
.next();
706 m_dirtyContentRoles
.insert(role
);
710 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
711 const QList
<QByteArray
>& previous
)
714 m_sortedVisibleRoles
= current
;
715 m_dirtyLayout
= true;
718 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
725 m_dirtyLayout
= true;
728 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
729 const KItemListStyleOption
& previous
)
733 updateAdditionalInfoTextColor();
734 m_dirtyLayout
= true;
737 void KStandardItemListWidget::hoveredChanged(bool hovered
)
740 m_dirtyLayout
= true;
743 void KStandardItemListWidget::selectedChanged(bool selected
)
746 updateAdditionalInfoTextColor();
747 m_dirtyContent
= true;
750 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
754 m_dirtyLayout
= true;
757 int KStandardItemListWidget::selectionLength(const QString
& text
) const
759 return text
.length();
762 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
766 QGraphicsView
* parent
= scene()->views()[0];
767 if (current
.isEmpty() || !parent
|| current
!= "text") {
769 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
771 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
772 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
773 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
774 this, &KStandardItemListWidget::slotRoleEditingFinished
);
776 if (m_oldRoleEditor
) {
777 m_oldRoleEditor
->deleteLater();
779 m_oldRoleEditor
= m_roleEditor
;
780 m_roleEditor
->hide();
781 m_roleEditor
= nullptr;
786 Q_ASSERT(!m_roleEditor
);
788 const TextInfo
* textInfo
= m_textInfo
.value("text");
790 m_roleEditor
= new KItemListRoleEditor(parent
);
791 m_roleEditor
->setRole(current
);
792 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
793 m_roleEditor
->setFont(styleOption().font
);
795 const QString text
= data().value(current
).toString();
796 m_roleEditor
->setPlainText(text
);
798 QTextOption textOption
= textInfo
->staticText
.textOption();
799 m_roleEditor
->document()->setDefaultTextOption(textOption
);
801 const int textSelectionLength
= selectionLength(text
);
803 if (textSelectionLength
> 0) {
804 QTextCursor cursor
= m_roleEditor
->textCursor();
805 cursor
.movePosition(QTextCursor::StartOfBlock
);
806 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
807 m_roleEditor
->setTextCursor(cursor
);
810 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
811 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
812 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
813 this, &KStandardItemListWidget::slotRoleEditingFinished
);
815 // Adjust the geometry of the editor
816 QRectF rect
= roleEditingRect(current
);
817 const int frameWidth
= m_roleEditor
->frameWidth();
818 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
819 rect
.translate(pos());
820 if (rect
.right() > parent
->width()) {
821 rect
.setWidth(parent
->width() - rect
.left());
823 m_roleEditor
->setGeometry(rect
.toRect());
824 m_roleEditor
->show();
825 m_roleEditor
->setFocus();
828 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
831 setEditedRole(QByteArray());
832 Q_ASSERT(!m_roleEditor
);
835 KItemListWidget::resizeEvent(event
);
837 m_dirtyLayout
= true;
840 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
842 KItemListWidget::showEvent(event
);
844 // Listen to changes of the clipboard to mark the item as cut/uncut
845 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
847 const QUrl itemUrl
= data().value("url").toUrl();
848 m_isCut
= clipboard
->isCut(itemUrl
);
850 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
851 this, &KStandardItemListWidget::slotCutItemsChanged
);
854 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
856 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
857 this, &KStandardItemListWidget::slotCutItemsChanged
);
859 KItemListWidget::hideEvent(event
);
862 bool KStandardItemListWidget::event(QEvent
*event
)
864 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
865 || event
->type() == QEvent::PaletteChange
) {
866 m_dirtyContent
= true;
869 return KItemListWidget::event(event
);
872 void KStandardItemListWidget::finishRoleEditing()
874 if (!editedRole().isEmpty() && m_roleEditor
) {
875 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
879 void KStandardItemListWidget::slotCutItemsChanged()
881 const QUrl itemUrl
= data().value("url").toUrl();
882 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
883 if (m_isCut
!= isCut
) {
885 m_pixmap
= QPixmap();
886 m_dirtyContent
= true;
891 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
892 const QVariant
& value
)
895 Q_EMIT
roleEditingCanceled(index(), role
, value
);
896 setEditedRole(QByteArray());
899 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
900 const QVariant
& value
)
903 Q_EMIT
roleEditingFinished(index(), role
, value
);
904 setEditedRole(QByteArray());
907 void KStandardItemListWidget::triggerCacheRefreshing()
909 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
915 const QHash
<QByteArray
, QVariant
> values
= data();
916 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
917 m_isHidden
= isHidden();
918 m_customizedFont
= customizedFont(styleOption().font
);
919 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
921 updateExpansionArea();
925 m_dirtyLayout
= false;
926 m_dirtyContent
= false;
927 m_dirtyContentRoles
.clear();
930 void KStandardItemListWidget::updateExpansionArea()
932 if (m_supportsItemExpanding
) {
933 const QHash
<QByteArray
, QVariant
> values
= data();
934 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
935 if (expandedParentsCount
>= 0) {
936 const KItemListStyleOption
& option
= styleOption();
937 const qreal widgetHeight
= size().height();
938 const qreal inc
= (widgetHeight
- option
.iconSize
) / 2;
939 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
941 m_expansionArea
= QRectF(x
, y
, option
.iconSize
, option
.iconSize
);
946 m_expansionArea
= QRectF();
949 void KStandardItemListWidget::updatePixmapCache()
951 // Precondition: Requires already updated m_textPos values to calculate
952 // the remaining height when the alignment is vertical.
954 const QSizeF widgetSize
= size();
955 const bool iconOnTop
= (m_layout
== IconsLayout
);
956 const KItemListStyleOption
& option
= styleOption();
957 const qreal padding
= option
.padding
;
959 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
960 const int maxIconHeight
= option
.iconSize
;
962 const QHash
<QByteArray
, QVariant
> values
= data();
964 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
965 if (!updatePixmap
&& m_dirtyContent
) {
966 updatePixmap
= m_dirtyContentRoles
.isEmpty()
967 || m_dirtyContentRoles
.contains("iconPixmap")
968 || m_dirtyContentRoles
.contains("iconName")
969 || m_dirtyContentRoles
.contains("iconOverlays");
973 m_pixmap
= QPixmap();
975 int sequenceIndex
= hoverSequenceIndex();
977 if (values
.contains("hoverSequencePixmaps")) {
978 // Use one of the hover sequence pixmaps instead of the default
981 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
983 if (values
.contains("hoverSequenceWraparoundPoint")) {
984 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
986 sequenceIndex
%= static_cast<int>(wap
);
990 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
992 if (loadedIndex
!= 0) {
993 m_pixmap
= pixmaps
[loadedIndex
];
997 if (m_pixmap
.isNull()) {
998 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1001 if (m_pixmap
.isNull()) {
1002 // Use the icon that fits to the MIME-type
1003 QString iconName
= values
["iconName"].toString();
1004 if (iconName
.isEmpty()) {
1005 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1006 // use a generic icon as fallback
1007 iconName
= QStringLiteral("unknown");
1009 const QStringList overlays
= values
["iconOverlays"].toStringList();
1010 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
1012 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1013 // A custom pixmap has been applied. Assure that the pixmap
1014 // is scaled to the maximum available size.
1015 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1018 if (m_pixmap
.isNull()) {
1019 m_hoverPixmap
= QPixmap();
1024 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1025 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1029 KIconEffect::semiTransparent(m_pixmap
);
1032 if (m_layout
== IconsLayout
&& isSelected()) {
1033 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1034 QImage image
= m_pixmap
.toImage();
1035 if (image
.isNull()) {
1036 m_hoverPixmap
= QPixmap();
1039 KIconEffect::colorize(image
, color
, 0.8f
);
1040 m_pixmap
= QPixmap::fromImage(image
);
1044 if (!m_overlay
.isNull()) {
1045 QPainter
painter(&m_pixmap
);
1046 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1049 int scaledIconSize
= 0;
1051 const TextInfo
* textInfo
= m_textInfo
.value("text");
1052 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1054 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1055 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1056 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1057 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1060 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1061 const int maxScaledIconHeight
= scaledIconSize
;
1063 m_scaledPixmapSize
= m_pixmap
.size();
1064 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1065 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1068 // Center horizontally and align on bottom within the icon-area
1069 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1070 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1072 // Center horizontally and vertically within the icon-area
1073 const TextInfo
* textInfo
= m_textInfo
.value("text");
1074 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1075 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1077 // Derive icon's vertical center from the center of the text frame, including
1078 // any necessary adjustment if the font's midline is offset from the frame center
1079 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1080 - m_customizedFontMetrics
.descent()
1081 - m_customizedFontMetrics
.capHeight() / 2.0;
1082 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1086 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1088 // Prepare the pixmap that is used when the item gets hovered
1090 m_hoverPixmap
= m_pixmap
;
1091 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1092 // In the KIconLoader terminology, active = hover.
1093 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1094 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1096 m_hoverPixmap
= m_pixmap
;
1098 } else if (hoverOpacity() <= 0.0) {
1099 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1100 m_hoverPixmap
= QPixmap();
1104 void KStandardItemListWidget::updateTextsCache()
1106 QTextOption textOption
;
1109 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1110 textOption
.setAlignment(Qt::AlignHCenter
);
1114 textOption
.setAlignment(Qt::AlignLeft
);
1115 textOption
.setWrapMode(QTextOption::NoWrap
);
1122 qDeleteAll(m_textInfo
);
1124 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1125 TextInfo
* textInfo
= new TextInfo();
1126 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1127 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1128 textInfo
->staticText
.setTextOption(textOption
);
1129 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1133 case IconsLayout
: updateIconsLayoutTextCache(); break;
1134 case CompactLayout
: updateCompactLayoutTextCache(); break;
1135 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1136 default: Q_ASSERT(false); break;
1139 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1140 if (ratingTextInfo
) {
1141 // The text of the rating-role has been set to empty to get
1142 // replaced by a rating-image showing the rating as stars.
1143 const KItemListStyleOption
& option
= styleOption();
1144 QSizeF ratingSize
= preferredRatingSize(option
);
1146 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1147 ? columnWidth("rating") - columnPadding(option
)
1149 if (ratingSize
.width() > availableWidth
) {
1150 ratingSize
.rwidth() = availableWidth
;
1152 const qreal dpr
= qApp
->devicePixelRatio();
1153 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1154 m_rating
.setDevicePixelRatio(dpr
);
1155 m_rating
.fill(Qt::transparent
);
1157 QPainter
painter(&m_rating
);
1158 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1159 const int rating
= data().value("rating").toInt();
1160 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1161 } else if (!m_rating
.isNull()) {
1162 m_rating
= QPixmap();
1166 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1168 const auto extensionIndex
= text
.lastIndexOf('.');
1169 if (extensionIndex
!= -1) {
1170 // has file extension
1171 const auto extensionLength
= text
.length() - extensionIndex
;
1172 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1173 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1174 // if we have room to display the file extension and the extension is not too long
1175 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1177 elidingWidth
- extensionWidth
);
1178 ret
.append(text
.rightRef(extensionLength
));
1182 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1186 void KStandardItemListWidget::updateIconsLayoutTextCache()
1193 // might get wrapped above
1195 // Additional role 1
1196 // Additional role 2
1198 const QHash
<QByteArray
, QVariant
> values
= data();
1200 const KItemListStyleOption
& option
= styleOption();
1201 const qreal padding
= option
.padding
;
1202 const qreal maxWidth
= size().width() - 2 * padding
;
1203 const qreal widgetHeight
= size().height();
1204 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1206 // Initialize properties for the "text" role. It will be used as anchor
1207 // for initializing the position of the other roles.
1208 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1209 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1210 nameTextInfo
->staticText
.setText(nameText
);
1212 // Calculate the number of lines required for the name and the required width
1213 qreal nameWidth
= 0;
1214 qreal nameHeight
= 0;
1217 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1218 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1219 layout
.beginLayout();
1220 int nameLineIndex
= 0;
1221 while ((line
= layout
.createLine()).isValid()) {
1222 line
.setLineWidth(maxWidth
);
1223 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1224 nameHeight
+= line
.height();
1227 if (nameLineIndex
== option
.maxTextLines
) {
1228 // The maximum number of textlines has been reached. If this is
1229 // the case provide an elided text if necessary.
1230 const int textLength
= line
.textStart() + line
.textLength();
1231 if (textLength
< nameText
.length()) {
1232 // Elide the last line of the text
1233 qreal elidingWidth
= maxWidth
;
1234 qreal lastLineWidth
;
1236 QString lastTextLine
= nameText
.mid(line
.textStart());
1237 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1238 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1239 nameTextInfo
->staticText
.setText(elidedText
);
1241 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1243 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1244 // to avoid problems related to different width calculation code paths
1245 // within Qt. (see bug 337104)
1246 elidingWidth
-= 1.0;
1247 } while (lastLineWidth
> maxWidth
);
1249 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1256 // Use one line for each additional information
1257 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1258 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1259 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1261 additionalRolesCount
* lineSpacing
-
1263 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1264 nameTextInfo
->pos
.y(),
1268 // Calculate the position for each additional information
1269 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1270 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1271 if (role
== "text") {
1275 const QString text
= roleText(role
, values
);
1276 TextInfo
* textInfo
= m_textInfo
.value(role
);
1277 textInfo
->staticText
.setText(text
);
1279 qreal requiredWidth
= 0;
1281 QTextLayout
layout(text
, m_customizedFont
);
1282 QTextOption textOption
;
1283 textOption
.setWrapMode(QTextOption::NoWrap
);
1284 layout
.setTextOption(textOption
);
1286 layout
.beginLayout();
1287 QTextLine textLine
= layout
.createLine();
1288 if (textLine
.isValid()) {
1289 textLine
.setLineWidth(maxWidth
);
1290 requiredWidth
= textLine
.naturalTextWidth();
1291 if (requiredWidth
> maxWidth
) {
1292 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1293 textInfo
->staticText
.setText(elidedText
);
1294 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1295 } else if (role
== "rating") {
1296 // Use the width of the rating pixmap, because the rating text is empty.
1297 requiredWidth
= m_rating
.width();
1302 textInfo
->pos
= QPointF(padding
, y
);
1303 textInfo
->staticText
.setTextWidth(maxWidth
);
1305 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1306 m_textRect
|= textRect
;
1311 // Add a padding to the text rectangle
1312 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1315 void KStandardItemListWidget::updateCompactLayoutTextCache()
1317 // +------+ Name role
1318 // | Icon | Additional role 1
1319 // +------+ Additional role 2
1321 const QHash
<QByteArray
, QVariant
> values
= data();
1323 const KItemListStyleOption
& option
= styleOption();
1324 const qreal widgetHeight
= size().height();
1325 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1326 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1327 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1329 qreal maximumRequiredTextWidth
= 0;
1330 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1331 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1332 const qreal maxWidth
= size().width() - x
- option
.padding
;
1333 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1334 const QString text
= roleText(role
, values
);
1335 TextInfo
* textInfo
= m_textInfo
.value(role
);
1336 textInfo
->staticText
.setText(text
);
1338 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1339 if (requiredWidth
> maxWidth
) {
1340 requiredWidth
= maxWidth
;
1341 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1342 textInfo
->staticText
.setText(elidedText
);
1345 textInfo
->pos
= QPointF(x
, y
);
1346 textInfo
->staticText
.setTextWidth(maxWidth
);
1348 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1353 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1356 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1358 // Precondition: Requires already updated m_expansionArea
1359 // to determine the left position.
1362 // | Icon | Name role Additional role 1 Additional role 2
1364 m_textRect
= QRectF();
1366 const KItemListStyleOption
& option
= styleOption();
1367 const QHash
<QByteArray
, QVariant
> values
= data();
1369 const qreal widgetHeight
= size().height();
1370 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1371 const int fontHeight
= m_customizedFontMetrics
.height();
1373 const qreal columnWidthInc
= columnPadding(option
);
1374 qreal firstColumnInc
= scaledIconSize
;
1375 if (m_supportsItemExpanding
) {
1376 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1378 firstColumnInc
+= option
.padding
;
1381 qreal x
= firstColumnInc
;
1382 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1384 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1385 QString text
= roleText(role
, values
);
1387 // Elide the text in case it does not fit into the available column-width
1388 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1389 const qreal roleWidth
= columnWidth(role
);
1390 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1392 const bool isTextRole
= (role
== "text");
1394 availableTextWidth
-= firstColumnInc
;
1397 if (requiredWidth
> availableTextWidth
) {
1398 text
= elideRightKeepExtension(text
, availableTextWidth
);
1399 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1402 TextInfo
* textInfo
= m_textInfo
.value(role
);
1403 textInfo
->staticText
.setText(text
);
1404 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1408 const qreal textWidth
= option
.extendedSelectionRegion
1409 ? size().width() - textInfo
->pos
.x()
1410 : requiredWidth
+ 2 * option
.padding
;
1411 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1412 textWidth
, size().height());
1414 // The column after the name should always be aligned on the same x-position independent
1415 // from the expansion-level shown in the name column
1416 x
-= firstColumnInc
;
1417 } else if (isRoleRightAligned(role
)) {
1418 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1423 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1426 if (m_customTextColor
.isValid()) {
1427 c1
= m_customTextColor
;
1428 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1429 c1
= styleOption().palette
.highlightedText().color();
1431 c1
= styleOption().palette
.text().color();
1434 // For the color of the additional info the inactive text color
1435 // is not used as this might lead to unreadable text for some color schemes. Instead
1436 // the text color c1 is slightly mixed with the background color.
1437 const QColor c2
= styleOption().palette
.base().color();
1439 const int p2
= 100 - p1
;
1440 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1441 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1442 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1445 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1447 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1448 QPixmap scaledPixmap
= pixmap
;
1449 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1450 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1451 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1453 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1454 painter
->setPen(Qt::blue
);
1455 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1458 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1462 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1464 const int siblingSize
= size().height();
1465 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1466 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1468 QStyleOption option
;
1469 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1470 bool isItemSibling
= true;
1472 const QBitArray siblings
= siblingsInformation();
1473 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1474 option
.rect
= siblingRect
;
1475 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1477 if (isItemSibling
) {
1478 option
.state
|= QStyle::State_Item
;
1479 if (m_isExpandable
) {
1480 option
.state
|= QStyle::State_Children
;
1482 if (data().value("isExpanded").toBool()) {
1483 option
.state
|= QStyle::State_Open
;
1485 isItemSibling
= false;
1488 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1490 siblingRect
.translate(-siblingRect
.width(), 0);
1494 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1496 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1501 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1502 if (m_layout
== DetailsLayout
) {
1503 rect
.setWidth(columnWidth(role
) - rect
.x());
1509 void KStandardItemListWidget::closeRoleEditor()
1511 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1512 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1513 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1514 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1516 if (m_roleEditor
->hasFocus()) {
1517 // If the editing was not ended by a FocusOut event, we have
1518 // to transfer the keyboard focus back to the KItemListContainer.
1519 scene()->views()[0]->parentWidget()->setFocus();
1522 if (m_oldRoleEditor
) {
1523 m_oldRoleEditor
->deleteLater();
1525 m_oldRoleEditor
= m_roleEditor
;
1526 m_roleEditor
->hide();
1527 m_roleEditor
= nullptr;
1530 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1532 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1534 size
*= qApp
->devicePixelRatio();
1536 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1539 if (!QPixmapCache::find(key
, &pixmap
)) {
1540 QIcon icon
= QIcon::fromTheme(name
);
1541 if (icon
.isNull()) {
1545 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1546 icon
= fallbackIcon
;
1549 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1550 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1551 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1554 // Strangely KFileItem::overlays() returns empty string-values, so
1555 // we need to check first whether an overlay must be drawn at all.
1556 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1557 // assumes that an overlay will be drawn and has some additional
1559 for (const QString
& overlay
: overlays
) {
1560 if (!overlay
.isEmpty()) {
1561 int state
= KIconLoader::DefaultState
;
1567 state
= KIconLoader::ActiveState
;
1569 case QIcon::Disabled
:
1570 state
= KIconLoader::DisabledState
;
1572 case QIcon::Selected
:
1573 state
= KIconLoader::SelectedState
;
1577 // There is at least one overlay, draw all overlays above m_pixmap
1578 // and cancel the check
1579 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1584 QPixmapCache::insert(key
, pixmap
);
1586 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1591 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1593 const qreal height
= option
.fontMetrics
.ascent();
1594 return QSizeF(height
* 5, height
);
1597 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1599 return option
.padding
* 6;